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
Remove deprecated scripts for glama submission, x402 payment testing, and x402 configuration verification; add agent achievements data loader for improved caching and performance.
zprv961e977616a5
diff --git a/api/_lib/agent-achievements-data.js b/api/_lib/agent-achievements-data.jsnew file mode 100644index 000000000..db038c00e--- /dev/null+++ b/api/_lib/agent-achievements-data.js@@ -0,0 +1,157 @@+/**+ * Agent achievements — data loader (the I/O layer).+ * =================================================+ *+ * Gathers every REAL input the pure engine (agent-achievements.js) scores and+ * returns the computed achievement body, Redis-cached. Shared by:+ * · GET /api/agents/:id/achievements (the profile panel)+ * · GET /api/og/agent (top badge on the shareable card)+ * · the reputation leaderboard (achievement counts per ranked agent)+ *+ * Keeping the gather+cache here (not in the HTTP handler) means every consumer+ * sees the same numbers off the same cache, and a warm entry makes the OG card+ * and leaderboard pay nothing for the live market lookups.+ */++import { sql } from './db.js';+import { getRedis } from './redis.js';+import { computeAchievements, isLaunchGraduated } from './agent-achievements.js';++const PUMP_FRONTEND_BASE = 'https://frontend-api-v3.pump.fun';+const CACHE_TTL_S = 120;+const CACHE_KEY = (id) => `agent-achievements:v1:${id}`;+// Cap the live market lookups so a creator with dozens of launches can't fan out+// into dozens of upstream calls per request. Newest 30 covers every milestone in+// practice; older launches that already graduated keep the badge regardless.+const MARKET_LOOKUP_CAP = 30;++/** Live pump.fun coin object for a mint, or null on any failure (best-effort). */+async function fetchCoin(mint) {+ try {+ const resp = await fetch(new URL(`/coins/${mint}`, PUMP_FRONTEND_BASE), {+ headers: { accept: 'application/json' },+ signal: AbortSignal.timeout(7000),+ });+ if (!resp.ok) return null;+ return await resp.json();+ } catch {+ return null;+ }+}++/**+ * Load (or compute) an agent's achievements.+ *+ * @param {string} agentId — agent UUID (caller validates the shape)+ * @param {object} [opts]+ * @param {boolean} [opts.fresh] — bypass the Redis read (still writes the cache)+ * @returns {Promise<object|null>} the achievement body, or null if no such agent+ */+export async function loadAgentAchievements(agentId, { fresh = false } = {}) {+ const cacheKey = CACHE_KEY(agentId);+ const redis = await getRedis();++ if (!fresh && redis) {+ try {+ const cached = await redis.get(cacheKey);+ if (cached) return { ...cached, _cache: 'HIT' };+ } catch {+ /* cache miss — recompute */+ }+ }++ const [agent] = await sql`+ SELECT id, name, created_at+ FROM agent_identities+ WHERE id = ${agentId} AND deleted_at IS NULL+ `;+ if (!agent) return null;++ // Launches + aggregate supporter & burn stats across all of this agent's+ // mints, in parallel — three independent reads.+ const [launchRows, [paymentStats], [burnStats]] = await Promise.all([+ sql`+ SELECT mint, network, created_at+ FROM pump_agent_mints+ WHERE agent_id = ${agentId}+ ORDER BY created_at DESC+ `,+ sql`+ SELECT+ count(*) FILTER (WHERE p.status='confirmed')::int AS confirmed_payments,+ count(DISTINCT p.payer_wallet) FILTER (WHERE p.status='confirmed')::int AS unique_payers+ FROM pump_agent_payments p+ JOIN pump_agent_mints m ON m.id = p.mint_id+ WHERE m.agent_id = ${agentId}+ `,+ sql`+ SELECT count(*) FILTER (WHERE b.status='confirmed')::int AS runs+ FROM pump_buyback_runs b+ JOIN pump_agent_mints m ON m.id = b.mint_id+ WHERE m.agent_id = ${agentId}+ `,+ ]);++ // Enrich mainnet launches with live market data (graduation + market cap).+ // Devnet launches have no pump.fun market. Capped + parallel + best-effort.+ const mainnet = launchRows.filter((r) => r.network !== 'devnet').slice(0, MARKET_LOOKUP_CAP);+ const coins = await Promise.all(mainnet.map((r) => fetchCoin(r.mint)));+ const marketByMint = new Map();+ mainnet.forEach((r, i) => marketByMint.set(r.mint, coins[i]));++ const launches = launchRows.map((r) => {+ const coin = marketByMint.get(r.mint);+ const mcap = Number(coin?.usd_market_cap);+ return {+ mint: r.mint,+ network: r.network,+ created_at: r.created_at,+ graduated: r.network !== 'devnet' && isLaunchGraduated(coin),+ mcap: Number.isFinite(mcap) ? mcap : 0,+ };+ });++ // Reputation tier — best-effort. The reputation read does on-chain + ledger+ // work, so a failure must never block the achievements: the two reputation+ // badges simply stay locked.+ let reputation = null;+ try {+ const { getAgentReputation } = await import('./trust/wallet-reputation.js');+ const { TIERS } = await import('../../src/shared/agent-financial-reputation.js');+ const rep = await getAgentReputation(agentId, { lite: true });+ if (rep && rep.tier) {+ reputation = {+ tier: rep.tier,+ tierLabel: rep.tierLabel || TIERS[rep.tier]?.label || rep.tier,+ rank: TIERS[rep.tier]?.rank ?? 0,+ score: rep.score ?? null,+ };+ }+ } catch {+ reputation = null;+ }++ const result = computeAchievements({+ agentCreatedAt: agent.created_at,+ launches,+ payments: paymentStats || {},+ burns: burnStats || {},+ reputation,+ });++ const body = {+ agent_id: agent.id,+ name: agent.name,+ ...result,+ computed_at: new Date().toISOString(),+ };++ if (redis) {+ try {+ await redis.set(cacheKey, body, { ex: CACHE_TTL_S });+ } catch {+ /* cache write best-effort */+ }+ }+ return body;+}diff --git a/api/_lib/env.js b/api/_lib/env.jsindex aeb1cc682..595f00729 100644--- a/api/_lib/env.js+++ b/api/_lib/env.js@@ -374,6 +374,24 @@ export const env = {return opt('AVATURN_SEED_ENABLED', '') === '1';},+ // launcher house-seed cron — set to '1' to enable the per-minute headless+ // seeder that grows the AUTONOMOUS LAUNCHER's pool of house-owned agents:+ // each tick forges one fresh Avaturn-rigged avatar, files it under the house+ // account, mints an agent flagged `meta.launcher_house=true`, and provisions+ // its custodial Solana wallet. Those agents — and only those — are what the+ // global launcher draws from to sign coin launches, so coins mint from agents+ // the platform owns and can claim creator rewards for. Off by default.+ get LAUNCHER_HOUSE_ENABLED() {+ return opt('LAUNCHER_HOUSE_ENABLED', '') === '1';+ },++ // How many house-owned launch agents to maintain. The house-seed cron stops+ // forging once this many wallet-bearing, avatar-bearing house agents exist.+ get LAUNCHER_HOUSE_TARGET() {+ const n = Number.parseInt(opt('LAUNCHER_HOUSE_TARGET', '8'), 10);+ return Number.isFinite(n) && n > 0 ? Math.min(n, 250) : 8;+ },+// Anthropic API key — used by persona / memory-seeding endpoints and// the we-pay LLM proxy (/api/llm/anthropic) when an agent selects a// Claude model. Optional: when unset, brain/persona endpoints fall backdiff --git a/api/_lib/migrations/20260629120000_sniper_funding.sql b/api/_lib/migrations/20260629120000_sniper_funding.sqlnew file mode 100644index 000000000..6583eb461--- /dev/null+++ b/api/_lib/migrations/20260629120000_sniper_funding.sql@@ -0,0 +1,35 @@+-- Migration: agent-sniper buy-side auto-funding ledger.+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260629120000_sniper_funding.sql+-- Idempotent.+--+-- The sniper worker tops up each armed agent's own Solana wallet from the+-- launcher master when it drops below a floor, so a hot sniper never silently+-- runs out of SOL and starts failing every buy. Each master -> agent transfer+-- is recorded here so the daily funding cap survives a worker restart (an+-- in-process accumulator would reset and let the cap be bypassed on a crash+-- loop). It also powers the funding column on the sniper dashboard.+--+-- All SOL amounts are stored as lamports (numeric(40,0)) to avoid float drift.++begin;++create table if not exists sniper_funding_events (+ id uuid primary key default gen_random_uuid(),+ agent_id uuid not null references agent_identities(id) on delete cascade,+ wallet text not null, -- recipient agent solana address+ network text not null default 'mainnet' check (network in ('mainnet','devnet')),+ lamports numeric(40, 0) not null, -- SOL moved (master -> agent)+ balance_before_lamports numeric(40, 0), -- agent balance observed pre-topup+ signature text, -- transfer signature ('SIMULATED' in simulate mode)+ mode text not null default 'live' check (mode in ('live','simulate')),+ created_at timestamptz not null default now()+);++create index if not exists sniper_funding_events_agent+ on sniper_funding_events (agent_id, network, created_at desc);+-- Powers the daily-cap sum: real transfers since the start of the UTC day.+create index if not exists sniper_funding_events_day+ on sniper_funding_events (network, created_at desc)+ where mode = 'live';++commit;diff --git a/api/_lib/oracle/sources.js b/api/_lib/oracle/sources.jsindex 1ef762a12..60fae9a70 100644--- a/api/_lib/oracle/sources.js+++ b/api/_lib/oracle/sources.js@@ -11,6 +11,8 @@// pump_coin_intel — coin record + precomputed structural/narrative signals// coin_smart_money — pedigree: proven-money score + notable wallets// oracle_narrative — Oracle's own cultural read (virality), if classified+// pump_coin_wallets — per-wallet ledger (funder clusters, proven-wallet flow)+// wallet_reputation — the coin creator's own launch track record// pump_coin_outcomes — ground-truth outcome (for the conviction backtest)import { sql } from '../db.js';@@ -60,18 +62,20 @@ export async function assembleIntel(mint, network = 'mainnet') {// on tryRow, since partial intel is an acceptable degradation.const coinRows = await sql`select mint, symbol, name, image_uri, category, narrative, classify_confidence,+ creator, bonding_curve, description, twitter, telegram, website, tags,created_at, first_seen_at,dev_buy_lamports, dev_sold, dev_sell_lamports,buy_count, sell_count, buy_volume_lamports, sell_volume_lamports,- unique_buyers, largest_buy_lamports,- bundle_score, organic_score, concentration_top10, bubblemap_connectivity,+ unique_buyers, unique_sellers, largest_buy_lamports,+ bundle_score, organic_score, snipe_ratio, fresh_wallet_ratio,+ concentration_top10, bubblemap_connectivity,quality_score, risk_flagsfrom pump_coin_intel where mint = ${mint} and network = ${network} limit 1`;const coin = coinRows[0] || null;if (!coin) return null;- const [smart, narr, topBuyers] = await Promise.all([+ const [smart, narr, topBuyers, funder, provenFlow, creatorRep] = await Promise.all([tryRow(() => sql`select smart_money_score, smart_wallet_count, proven_buy_lamports, total_buy_lamports, notablefrom coin_smart_money where mint = ${mint} and network = ${network} limit 1@@ -85,13 +89,66 @@ export async function assembleIntel(mint, network = 'mainnet') {from pump_coin_wallets where mint = ${mint}order by buy_lamports desc limit 25`),+ // Funder clustering: among real buyers (creator excluded), how concentrated+ // is the funding source? A big single-funder cluster is a bundle wearing a+ // wide-base costume. Coverage-gated downstream so sparse enrichment never+ // fabricates a penalty.+ tryRow(() => sql`+ with buyers as (+ select wallet, funder+ from pump_coin_wallets+ where mint = ${mint} and buy_lamports > 0 and coalesce(is_creator, false) = false+ ),+ clusters as (+ select funder, count(*)::int as sz from buyers where funder is not null group by funder+ )+ select (select count(*) from buyers)::int as total_buyers,+ (select coalesce(sum(sz), 0) from clusters)::int as funded_buyers,+ (select coalesce(max(sz), 0) from clusters)::int as largest_cluster+ `),+ // Proven-wallet flow on THIS coin: are the smart wallets that bought also+ // already selling? coin_smart_money gives the buy side; this adds the exit.+ tryRow(() => sql`+ select coalesce(sum(w.buy_lamports), 0)::numeric as proven_buy,+ coalesce(sum(w.sell_lamports), 0)::numeric as proven_sell,+ count(*)::int as proven_wallets+ from pump_coin_wallets w+ join wallet_reputation r on r.wallet = w.wallet and r.network = ${network}+ where w.mint = ${mint}+ and (r.label in ('smart_money', 'kol') or r.smart_money_score >= 70)+ `),+ // The creator's own track record — a serial rugger and a proven shipper+ // launch identically without this. Null for first-time / unjudged creators.+ coin.creator+ ? tryRow(() => sql`+ select label, win_rate, dump_rate, smart_money_score,+ creator_count, creator_wins, coins_traded+ from wallet_reputation where wallet = ${coin.creator} and network = ${network} limit 1+ `)+ : Promise.resolve(null),]);- const intel = toCoinIntel({ coin, smart, narr });+ const intel = toCoinIntel({ coin, smart, narr, funder, provenFlow, creatorRep });enrichWithKnownWallets(intel, topBuyers);return intel;}+/**+ * Funder-cluster concentration as a 0..100 share of the buyer book, or null when+ * funder enrichment is too sparse to be trustworthy. Pure, exported for testing.+ *+ * @param {object|null} funder { total_buyers, funded_buyers, largest_cluster }+ */+export function funderClusterPct(funder) {+ if (!funder) return null;+ const total = n(funder.total_buyers) || 0;+ const funded = n(funder.funded_buyers) || 0;+ const largest = n(funder.largest_cluster) || 0;+ // Need a real book and real funder coverage before a cluster means anything.+ if (total < 8 || funded < 5 || funded / total < 0.3) return null;+ return Math.max(0, Math.min(100, (largest / total) * 100));+}+/*** Fold the known-wallet prior into a coin's pedigree. For each top buyer that's* a known smart-money/KOL/sniper wallet (gmgn seed), ensure it's in `notable`@@ -136,7 +193,7 @@ export function enrichWithKnownWallets(intel, topBuyers = []) {* Map raw brain rows → normalized CoinIntel. Pure given its inputs (exported so* it can be unit-tested without a DB).*/-export function toCoinIntel({ coin, smart, narr }) {+export function toCoinIntel({ coin, smart, narr, funder, provenFlow, creatorRep } = {}) {const riskFlags = Array.isArray(coin.risk_flags) ? coin.risk_flags : [];const devBuy = n(coin.dev_buy_lamports);const buyVol = n(coin.buy_volume_lamports) || 0;@@ -152,6 +209,8 @@ export function toCoinIntel({ coin, smart, narr }) {const bundleScore = pct01(coin.bundle_score); // 0..100const organicScore = pct01(coin.organic_score);+ const snipeRatio = pct01(coin.snipe_ratio); // 0..100, buy vol in first seconds+ const freshWalletRatio = pct01(coin.fresh_wallet_ratio); // 0..100, farmed-wallet shareconst top10Pct = pct01(coin.concentration_top10);const connectivity = pct01(coin.bubblemap_connectivity);const bundleFlag = riskFlags.includes('bundle_launch') || (bundleScore != null && bundleScore >= 60);@@ -169,6 +228,14 @@ export function toCoinIntel({ coin, smart, narr }) {const notable = Array.isArray(smart?.notable) ? smart.notable: (typeof smart?.notable === 'string' ? safeJson(smart.notable) : []);+ // Proven-wallet flow observed on this coin (smart money's actual buy AND sell+ // here). Prefer coin_smart_money's precomputed buy total; the join below adds+ // the exit side and backfills the buy total when smart-money hasn't run yet.+ const provenBuy = n(smart?.proven_buy_lamports) || n(provenFlow?.proven_buy) || 0;+ const provenSell = n(provenFlow?.proven_sell) || 0;++ const uniqueSellers = n(coin.unique_sellers) || 0;+return {mint: coin.mint,symbol: coin.symbol,@@ -177,20 +244,47 @@ export function toCoinIntel({ coin, smart, narr }) {category: narrative.category,createdAt: coin.created_at || coin.first_seen_at,+ // Off-chain signal the classifier weighs (link presence lifts virality) and+ // the API surfaces. Previously never threaded through — a dead input.+ social: {+ description: coin.description || null,+ twitter: coin.twitter || null,+ telegram: coin.telegram || null,+ website: coin.website || null,+ tags: Array.isArray(coin.tags) ? coin.tags : [],+ },++ // The wallet that launched the coin and its own track record. Null history+ // for a first-time or not-yet-judged creator (treated as neutral, not bad).+ creator: {+ wallet: coin.creator || null,+ label: creatorRep?.label || null,+ winRate: n(creatorRep?.win_rate),+ dumpRate: n(creatorRep?.dump_rate),+ smartMoneyScore: n(creatorRep?.smart_money_score),+ launches: n(creatorRep?.creator_count) || 0,+ launchWins: n(creatorRep?.creator_wins) || 0,+ },+smartMoney: {score: n(smart?.smart_money_score),smartWalletCount: n(smart?.smart_wallet_count) || (Array.isArray(notable) ? notable.length : 0),- provenBuyLamports: n(smart?.proven_buy_lamports) || 0,+ provenBuyLamports: provenBuy,+ provenSellLamports: provenSell,totalBuyLamports: n(smart?.total_buy_lamports) || buyVol,notable: Array.isArray(notable) ? notable : [],},structure: {uniqueBuyers: n(coin.unique_buyers) || 0,+ uniqueSellers,topHolderPct,creatorHoldPct,devSoldPct,organicScore,bundleScore,+ snipeRatio,+ freshWalletRatio,+ funderClusterPct: funderClusterPct(funder),top10Pct,bubblemapConnectivity: connectivity,bundleFlag,@@ -203,6 +297,7 @@ export function toCoinIntel({ coin, smart, narr }) {buyVolSol: buyVol / LAMPORTS,sellVolSol: (n(coin.sell_volume_lamports) || 0) / LAMPORTS,earlyBuyerCount: n(coin.unique_buyers) || 0,+ uniqueSellers,},riskFlags,qualityScore: n(coin.quality_score),diff --git a/api/_lib/oracle/store.js b/api/_lib/oracle/store.jsindex 3f47c8141..9986d5f36 100644--- a/api/_lib/oracle/store.js+++ b/api/_lib/oracle/store.js@@ -10,7 +10,7 @@ import { classifyNarrative } from './narrative.js';import { convict } from './conviction.js';import { summarizeActions } from './settle.js';import { knownWallet } from './known-wallets.js';-import { QUOTE_MINT_LIST } from '../quote-mints.js';+import { QUOTE_MINT_LIST, isQuoteMint } from '../quote-mints.js';/** Persist a narrative classification. */export async function upsertNarrative(mint, network, narr) {@@ -184,6 +184,11 @@ function rowToFeedItem(r) {/** Full intel for one coin: cached verdict + live who's-in trader breakdown. */export async function readCoin(mint, network = 'mainnet') {+ // Quote/stablecoin/LST mints are not coins — never serve a conviction read for+ // one, even if a stale row lingers before the next purge sweep.+ if (isQuoteMint(mint)) {+ return { conviction: null, reasons: [], components: null, structure_cap: null, narrative: null, outcome: null, whos_in: [] };+ }const cached = await sql`select * from oracle_conviction where mint = ${mint} and network = ${network} limit 1`.then((r) => r[0]).catch(() => null);diff --git a/api/_lib/usage.js b/api/_lib/usage.jsindex 3c923db98..db785fa9e 100644--- a/api/_lib/usage.js+++ b/api/_lib/usage.js@@ -17,7 +17,7 @@import { sql } from './db.js';import { withDbRetry } from './db-retry.js';-import { getRedis } from './redis.js';+import { getRedis, isRedisAuthError } from './redis.js';import { qstashEnabled, publishJob } from './qstash.js';import { env } from './env.js';@@ -114,7 +114,10 @@ export function recordEvent(evt) {// circuitOpen → the shared Redis auth breaker (api/_lib/redis.js) already// logged the credential failure once and is fast-failing; falling back to// a direct insert is the right move, but re-warning per event is noise.- if (!err?.circuitOpen) {+ // isRedisAuthError also catches the raw WRONGPASS the breaker's once-per-+ // cooldown half-open trial command surfaces (it bypasses the circuitOpen+ // short-circuit), so the bad-token signal stays owned solely by the breaker.+ if (!err?.circuitOpen && !isRedisAuthError(err)) {console.warn('[usage] buffer push failed, falling back to direct insert', err?.message);}}@@ -158,7 +161,7 @@ export async function flushUsageBuffer({ limit = 500, deadlineMs = 45_000 } = {}try {raw = await r.lrange(BUFFER_KEY, 0, take - 1);} catch (err) {- if (!err?.circuitOpen) console.warn('[usage-flush] redis unavailable on lrange:', err?.message);+ if (!err?.circuitOpen && !isRedisAuthError(err)) console.warn('[usage-flush] redis unavailable on lrange:', err?.message);return { flushed, remaining: -1, errors, skipped: 'redis_unavailable' };}if (!raw || raw.length === 0) break;diff --git a/api/admin/launcher.js b/api/admin/launcher.jsindex 632c7aba6..41cdbe9a6 100644--- a/api/admin/launcher.js+++ b/api/admin/launcher.js@@ -9,9 +9,10 @@// { action: 'force_tick' } to immediately run one launcher tick.//// Auth: a real admin session OR `Bearer $CRON_SECRET` (for ops tooling). The-// launcher ships disabled + dry_run; this is the only supported way to arm it,-// so a misclick can't move SOL — enabling real launches takes enabled=true AND-// dry_run=false, set deliberately here.+// launcher ships LIVE (enabled, real, with a standing dev buy); this is the+// supported way to retune or pause it — set dry_run=true to record without+// spending, enabled=false to disarm, or { action: 'resume' } to clear a tripped+// breaker. Real launches require enabled=true AND dry_run=false AND not paused.import { sql } from '../_lib/db.js';import { requireAdmin } from '../_lib/admin.js';@@ -40,8 +41,8 @@ function coerceArr(v) {async function ensureGlobalRow() {await sql`- insert into launcher_config (scope, enabled, dry_run, mode)- values ('global', false, true, 'hybrid')+ insert into launcher_config (scope, enabled, dry_run, mode, per_launch_sol, dev_buy_sol)+ values ('global', true, false, 'hybrid', 0.04, 0.01)on conflict do nothing`;}diff --git a/api/agents/_id/achievements.js b/api/agents/_id/achievements.jsindex f352bd7de..b3aa5a0cb 100644--- a/api/agents/_id/achievements.js+++ b/api/agents/_id/achievements.js@@ -1,47 +1,20 @@/*** GET /api/agents/:id/achievements*- * The agent's earned + locked achievements, computed from REAL platform data:- * · coins launched (pump_agent_mints)- * · graduations / migrations (live pump.fun coin `complete` + AMM pool)- * · peak market cap reached (live pump.fun usd_market_cap)- * · distinct supporters / payments (pump_agent_payments)- * · buyback-and-burn runs (pump_buyback_runs)- * · reputation tier (wallet-reputation, best-effort)- * · tenure (agent_identities.created_at)+ * The agent's earned + locked achievements, computed from REAL platform data+ * (coins launched, graduations/migrations, peak market cap, distinct supporters,+ * buyback burns, reputation tier, tenure). The gather + cache + pure scoring all+ * live in api/_lib/agent-achievements-data.js so the OG card and the leaderboard+ * read the exact same numbers off the same Redis entry.*- * Pure scoring lives in api/_lib/agent-achievements.js. Public read — the badges- * are a trust signal others rely on, so owner and visitor see the same set.- * Short-cached (Redis) because the live market lookups are the slow part.+ * Public read — the badges are a trust signal others rely on, so owner and+ * visitor see the same set.*/import { cors, json, error, method, wrap, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';-import { getRedis } from '../../_lib/redis.js';-import { sql } from '../../_lib/db.js';import { isUuid } from '../../_lib/validate.js';-import { computeAchievements, isLaunchGraduated } from '../../_lib/agent-achievements.js';--const PUMP_FRONTEND_BASE = 'https://frontend-api-v3.pump.fun';-const CACHE_TTL_S = 120;-// Cap the live market lookups so a creator with dozens of launches can't fan out-// into dozens of upstream calls per request. Newest 30 covers every milestone in-// practice; older launches that already graduated keep the badge regardless.-const MARKET_LOOKUP_CAP = 30;--/** Live pump.fun coin object for a mint, or null on any failure (best-effort). */-async function fetchCoin(mint) {- try {- const resp = await fetch(new URL(`/coins/${mint}`, PUMP_FRONTEND_BASE), {- headers: { accept: 'application/json' },- signal: AbortSignal.timeout(7000),- });- if (!resp.ok) return null;- return await resp.json();- } catch {- return null;- }-}+import { loadAgentAchievements } from '../../_lib/agent-achievements-data.js';export const handleAchievements = wrap(async (req, res, agentId) => {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;@@ -51,117 +24,11 @@ export const handleAchievements = wrap(async (req, res, agentId) => {const rl = await limits.publicIp(clientIp(req));if (!rl.success) return rateLimited(res, rl);- const cacheKey = `agent-achievements:v1:${agentId}`;- const redis = await getRedis();- if (redis) {- try {- const cached = await redis.get(cacheKey);- if (cached) {- res.setHeader('X-Cache', 'HIT');- res.setHeader('cache-control', 'public, max-age=60');- return json(res, 200, cached);- }- } catch {- /* cache miss — recompute */- }- }-- // Agent must exist (and not be soft-deleted) for the page to mean anything.- const [agent] = await sql`- SELECT id, name, created_at- FROM agent_identities- WHERE id = ${agentId} AND deleted_at IS NULL- `;- if (!agent) return error(res, 404, 'not_found', 'agent not found');-- // Pull every launch, plus aggregate supporter + burn stats across all of this- // agent's mints, in parallel — three independent reads, one round trip each.- const [launchRows, [paymentStats], [burnStats]] = await Promise.all([- sql`- SELECT mint, network, created_at- FROM pump_agent_mints- WHERE agent_id = ${agentId}- ORDER BY created_at DESC- `,- sql`- SELECT- count(*) FILTER (WHERE p.status='confirmed')::int AS confirmed_payments,- count(DISTINCT p.payer_wallet) FILTER (WHERE p.status='confirmed')::int AS unique_payers- FROM pump_agent_payments p- JOIN pump_agent_mints m ON m.id = p.mint_id- WHERE m.agent_id = ${agentId}- `,- sql`- SELECT count(*) FILTER (WHERE b.status='confirmed')::int AS runs- FROM pump_buyback_runs b- JOIN pump_agent_mints m ON m.id = b.mint_id- WHERE m.agent_id = ${agentId}- `,- ]);-- // Enrich each launch with live market data (graduation + market cap). Only- // mainnet mints have a pump.fun market; devnet launches stay non-graduated- // with no mcap. Capped + parallel + best-effort so the endpoint never hangs- // or fails on an upstream blip.- const mainnet = launchRows.filter((r) => r.network !== 'devnet').slice(0, MARKET_LOOKUP_CAP);- const coins = await Promise.all(mainnet.map((r) => fetchCoin(r.mint)));- const marketByMint = new Map();- mainnet.forEach((r, i) => marketByMint.set(r.mint, coins[i]));-- const launches = launchRows.map((r) => {- const coin = marketByMint.get(r.mint);- const mcap = Number(coin?.usd_market_cap);- return {- mint: r.mint,- network: r.network,- created_at: r.created_at,- graduated: r.network !== 'devnet' && isLaunchGraduated(coin),- mcap: Number.isFinite(mcap) ? mcap : 0,- };- });-- // Reputation tier — best-effort. The reputation read does on-chain + ledger- // work, so a failure (or slow upstream) must never block the achievements:- // the two reputation badges simply stay locked.- let reputation = null;- try {- const { getAgentReputation } = await import('../../_lib/trust/wallet-reputation.js');- const { TIERS } = await import('../../../src/shared/agent-financial-reputation.js');- const rep = await getAgentReputation(agentId);- if (rep && rep.tier) {- reputation = {- tier: rep.tier,- tierLabel: rep.tierLabel || TIERS[rep.tier]?.label || rep.tier,- rank: TIERS[rep.tier]?.rank ?? 0,- score: rep.score ?? null,- };- }- } catch {- reputation = null;- }-- const result = computeAchievements({- agentCreatedAt: agent.created_at,- launches,- payments: paymentStats || {},- burns: burnStats || {},- reputation,- });-- const body = {- agent_id: agent.id,- name: agent.name,- ...result,- computed_at: new Date().toISOString(),- };+ const body = await loadAgentAchievements(agentId);+ if (!body) return error(res, 404, 'not_found', 'agent not found');- if (redis) {- try {- await redis.set(cacheKey, body, { ex: CACHE_TTL_S });- } catch {- /* cache write best-effort */- }- }+ if (body._cache === 'HIT') res.setHeader('X-Cache', 'HIT');+ delete body._cache;res.setHeader('cache-control', 'public, max-age=60');return json(res, 200, body);});diff --git a/api/cron/launcher-claimer.js b/api/cron/launcher-claimer.jsindex ce17a250a..778a2a2ed 100644--- a/api/cron/launcher-claimer.js+++ b/api/cron/launcher-claimer.js@@ -7,9 +7,14 @@// 2. Claim via collect-creator-fee-agent (agent signs its own claim, same as the launch)// 3. Record in launcher_claims (claimed_sol, buyback_sol allocated, claim_sig)//-// This closes the money loop: launch → fees accrue → claim → revenue tracking.-// The buyback_sol column tracks the $THREE-allocated share (buyback_bps from the-// run's config). The actual swap path wires in once the trade endpoint is confirmed.+// This closes the creator-fee loop: launch → creator fees accrue → claim → record.+// buyback_sol records the buyback-earmarked share of those CREATOR fees (the run's+// buyback_bps) for revenue tracking. It is NOT a pending swap: the on-chain buyback+// for these agent coins is delivered by the buyback_bps binding baked into each+// launch (handleLaunchAgent → PumpAgent.create), which routes a share of TRADE fees+// into the coin's on-chain buyback vault, and the hourly run-buyback cron+// (api/cron/[name].js) then executes the buyback+burn from that vault. So the+// $THREE-aligned buy pressure runs through that lane, not this claimer.//// Auth: CRON_SECRET Bearer (same pattern as all cron endpoints).diff --git a/api/cron/launcher-tick.js b/api/cron/launcher-tick.jsindex 108baa716..55929c810 100644--- a/api/cron/launcher-tick.js+++ b/api/cron/launcher-tick.js@@ -1,10 +1,12 @@// @ts-check// GET/POST /api/cron/launcher-tick — drives one tick of the autonomous coin-// launcher engine (api/_lib/launcher-engine.js). Fully inert unless a-// launcher_config row is enabled; the seeded global row ships disabled + dry_run,-// so no SOL moves and no coin mints until an operator explicitly arms it. When-// armed, it makes pool agents mint pump.fun coins riding live cultural narratives-// — the same real on-chain path a human owner uses.+// launcher engine (api/_lib/launcher-engine.js). The seeded global row ships LIVE+// (enabled, real, with a standing dev buy), so pool agents mint pump.fun coins+// riding live cultural narratives on a cadence — the same real on-chain path a+// human owner uses. Still inert for any scope whose launcher_config row is+// disabled, and bounded by per-launch/daily SOL caps, an hourly ceiling, the+// cadence gate, and the circuit breaker. With no master wallet funded, each tick+// records a clean 'skipped' run instead of minting.import { json, error, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';diff --git a/api/cron/x402-seed-cron.js b/api/cron/x402-seed-cron.jsindex 414cc36c9..1ca1101f5 100644--- a/api/cron/x402-seed-cron.js+++ b/api/cron/x402-seed-cron.js@@ -34,7 +34,7 @@ import {import { json, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';import { constantTimeEquals } from '../_lib/crypto.js';-import { getRedis } from '../_lib/redis.js';+import { getRedis, isRedisAuthError } from '../_lib/redis.js';import { solanaConnection } from '../_lib/solana/connection.js';import { logger } from '../_lib/usage.js';@@ -205,7 +205,7 @@ export default wrapCron(async (req, res) => {try {await redis.ping();} catch (err) {- if (!err?.circuitOpen) log.warn('redis_unavailable_skip', { message: err?.message });+ if (!err?.circuitOpen && !isRedisAuthError(err)) log.warn('redis_unavailable_skip', { message: err?.message });return json(res, 200, { ok: false, skipped: true, reason: `redis_unavailable: ${err?.message}` });}}diff --git a/api/feed-stream.js b/api/feed-stream.jsindex 4f983a469..035e144eb 100644--- a/api/feed-stream.js+++ b/api/feed-stream.js@@ -35,7 +35,7 @@import { cors, method } from './_lib/http.js';import { env } from './_lib/env.js';-import { getRedis as _getSharedRedis } from './_lib/redis.js';+import { getRedis as _getSharedRedis, isRedisAuthError } from './_lib/redis.js';const FEED_KEY = 'feed:events';const HEARTBEAT_MS = 15_000;@@ -145,6 +145,16 @@ async function runPoll() {console.error('[feed-stream] Redis quota exhausted — pausing poll for', BREAKER_COOLDOWN_MS, 'ms');breakerLogged = true;}+ } else if (err?.circuitOpen || isRedisAuthError(err)) {+ // Invalid/stale UPSTASH_REDIS_REST_TOKEN — a config failure the shared auth+ // breaker (api/_lib/redis.js) already logged once and is fast-failing. Pause+ // the poll on the same back-off as a quota trip and log once, rather than+ // emitting a poll-failed line every tick across every warm SSE Lambda.+ breakerUntil = Date.now() + BREAKER_COOLDOWN_MS;+ if (!breakerLogged) {+ console.error('[feed-stream] Redis auth failure (invalid/stale token) — pausing poll for', BREAKER_COOLDOWN_MS, 'ms');+ breakerLogged = true;+ }} else {console.error('[feed-stream] poll failed', err?.message || err);}diff --git a/api/og/agent.js b/api/og/agent.jsindex 0d42be492..14db230bd 100644--- a/api/og/agent.js+++ b/api/og/agent.js@@ -25,6 +25,7 @@ import { env } from '../_lib/env.js';import { isUuid } from '../_lib/validate.js';import { getBalances, walletUsdTotal } from '../_lib/balances.js';import { getAgentReputation } from '../_lib/trust/wallet-reputation.js';+import { loadAgentAchievements } from '../_lib/agent-achievements-data.js';import { tierForUsd, NETWORTH_TIERS, THREE_MINT } from '../../src/shared/wallet-networth.js';const CACHE = 'public, max-age=180, s-maxage=900, stale-while-revalidate=120';@@ -34,6 +35,24 @@ const CACHE = 'public, max-age=180, s-maxage=900, stale-while-revalidate=120';const REP_RANK = { new: 0, emerging: 1, established: 2, trusted: 3, elite: 4 };const FINISH_LABELS = ['Common', 'Uncommon', 'Rare', 'Epic', 'Legendary', 'Mythic'];+// Achievement tier → accent (mirrors TIER_META in agent-achievements-panel.js so+// the OG badge matches the on-page badge color).+const ACH_TIER_COLOR = { bronze: '#cd7f32', silver: '#cbd5e1', gold: '#fbbf24', legendary: '#c084fc' };+const ACH_TIER_RANK = { bronze: 0, silver: 1, gold: 2, legendary: 3 };++/**+ * The one achievement worth putting on a shared card: the migration badges first+ * (graduating a coin is the headline success), otherwise the highest-tier earned.+ */+function headlineAchievement(earned = []) {+ if (!earned.length) return null;+ const migration = earned.find((a) => a.id === 'migrator') || earned.find((a) => a.id === 'graduate');+ if (migration) return migration;+ return earned.reduce((best, a) =>+ (ACH_TIER_RANK[a.tier] ?? 0) > (ACH_TIER_RANK[best.tier] ?? 0) ? a : best,+ earned[0]);+}+const GRADIENTS = [['#6366f1', '#8b5cf6'], ['#06b6d4', '#6366f1'], ['#10b981', '#06b6d4'], ['#f59e0b', '#ef4444'],['#ec4899', '#8b5cf6'], ['#14b8a6', '#3b82f6'], ['#f97316', '#ec4899'], ['#8b5cf6', '#06b6d4'],@@ -141,11 +160,14 @@ export default wrap(async (req, res) => {: null;// ── Real enrichments, each timeout-guarded so the card always renders ──────- const [balances, rep, pnl, tipsCount] = await Promise.all([+ const [balances, rep, pnl, tipsCount, achievements] = await Promise.all([solAddress ? withTimeout(getBalances({ chain: 'solana', address: solAddress }), 3000, null) : null,withTimeout(getAgentReputation(id, { lite: true }), 3000, null),withTimeout(realizedPnlFor(id), 2000, { sol: 0, wins: 0 }),solAddress ? withTimeout(tipsCountFor(id), 1500, 0) : 0,+ // Best-effort: a warm cache (the profile page just loaded it) makes this+ // free; a cold miss that overruns the budget just omits the badge.+ withTimeout(loadAgentAchievements(id), 2500, null),]);const usd = balances ? walletUsdTotal(balances) : 0;@@ -211,8 +233,19 @@ export default wrap(async (req, res) => {<text x="${sx + 18}" y="${STAT_Y + 56}" font-family="Inter,system-ui,sans-serif" font-size="11" font-weight="700" letter-spacing=".1em" fill="#6f6889">${x(s.label)}</text>`;}).join('\n');- // Badge row (reputation tier + $THREE mark), placed under the name.+ // Badge row (top achievement + reputation tier + $THREE mark), under the name.+ // The achievement leads — a graduated/elite agent advertises that success on+ // every shared link. "+N" notes how many more badges it has earned.const badges = [];+ const topAch = headlineAchievement(achievements?.earned);+ if (topAch) {+ const more = (achievements?.summary?.earnedCount || 1) - 1;+ badges.push({+ text: `★ ${topAch.title.toUpperCase()}${more > 0 ? ` +${more}` : ''}`,+ color: ACH_TIER_COLOR[topAch.tier] || '#cbd5e1',+ bg: true,+ });+ }if (repLabel) badges.push({ text: repLabel.toUpperCase(), color: rim, bg: true });if (hasThree) badges.push({ text: '◆ $THREE', color: '#fbbf24', bg: true });let badgeX = 440;diff --git a/api/oracle/backtest.js b/api/oracle/backtest.jsindex bf5215f80..847f53b12 100644--- a/api/oracle/backtest.js+++ b/api/oracle/backtest.js@@ -21,6 +21,7 @@import { cors, json, method, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { sql } from '../_lib/db.js';+import { QUOTE_MINT_LIST } from '../_lib/quote-mints.js';const PERIODS = { '1d': 1, '7d': 7, '30d': 30, '90d': 90, 'all': null };const TIERS = new Set(['prime', 'strong', 'lean', 'watch', 'avoid', 'all']);@@ -63,6 +64,9 @@ async function query(days, tier, network) {// ── per-tier breakdown ────────────────────────────────────────────────────const tierFilter = tier !== 'all' ? sql`and c.tier = ${tier}` : sql``;const periodFilter = days != null ? sql`and c.scored_at >= now() - (${days} || ' days')::interval` : sql``;+ // Quote/stablecoin/LST mints are not coins — exclude them from every accuracy+ // calc so a stray cached USDC row can't poison the win-rate or top performers.+ const quoteFilter = sql`and c.mint <> all(${QUOTE_MINT_LIST}::text[])`;const rows = await sql`select@@ -82,6 +86,7 @@ async function query(days, tier, network) {join pump_coin_outcomes o on o.mint = c.mintwhere c.network = ${network}and (o.graduated or o.rugged or o.ath_multiple is not null)+ ${quoteFilter}${tierFilter}${periodFilter}group by c.tier@@ -122,6 +127,7 @@ async function query(days, tier, network) {join pump_coin_outcomes o on o.mint = c.mintwhere c.network = ${network}and (o.graduated or o.rugged or o.ath_multiple is not null)+ ${quoteFilter}${periodFilter}group by 1order by 1@@ -155,6 +161,7 @@ async function query(days, tier, network) {join pump_coin_outcomes o on o.mint = c.mintwhere c.network = ${network}and (o.graduated or o.rugged or o.ath_multiple is not null)+ ${quoteFilter}${periodFilter}`.then((r) => r[0] || {}).catch(() => ({}));@@ -189,6 +196,7 @@ async function query(days, tier, network) {join pump_coin_outcomes o on o.mint = c.mintwhere c.network = ${network}and o.ath_multiple is not null+ ${quoteFilter}${topTierFilter}${topFilter}order by o.ath_multiple desc nulls lastdiff --git a/api/oracle/batch.js b/api/oracle/batch.jsindex 501b135ac..0363405c8 100644--- a/api/oracle/batch.js+++ b/api/oracle/batch.js@@ -17,6 +17,7 @@import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { sql } from '../_lib/db.js';+import { QUOTE_MINT_LIST } from '../_lib/quote-mints.js';const NETWORKS = new Set(['mainnet', 'devnet']);const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;@@ -48,6 +49,7 @@ export default wrap(async (req, res) => {from oracle_convictionwhere network = ${network}and mint = any(${mints})+ and mint <> all(${QUOTE_MINT_LIST}::text[])`.catch((e) => {throw new Error(`batch query failed: ${e.message}`);});diff --git a/api/oracle/categories.js b/api/oracle/categories.jsindex 46c26e8dd..41d4b3183 100644--- a/api/oracle/categories.js+++ b/api/oracle/categories.js@@ -25,6 +25,7 @@import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { sql } from '../_lib/db.js';+import { QUOTE_MINT_LIST } from '../_lib/quote-mints.js';const NETWORKS = new Set(['mainnet', 'devnet']);@@ -48,6 +49,7 @@ export default wrap(async (req, res) => {where network = ${network}and scored_at > now() - (${hours} || ' hours')::intervaland category is not null+ and mint <> all(${QUOTE_MINT_LIST}::text[])),agg as (selectdiff --git a/api/oracle/og.js b/api/oracle/og.jsindex 80238b152..5150d5725 100644--- a/api/oracle/og.js+++ b/api/oracle/og.js@@ -17,6 +17,7 @@import { cors, wrap } from '../_lib/http.js';import { sql } from '../_lib/db.js';+import { isQuoteMint } from '../_lib/quote-mints.js';const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;const PUMP_FRONTEND_V3 = 'https://frontend-api-v3.pump.fun';@@ -292,7 +293,8 @@ export default wrap(async (req, res) => {const url = new URL(req.url, 'http://x');const mint = (url.searchParams.get('mint') || '').trim();- if (!MINT_RE.test(mint)) {+ if (!MINT_RE.test(mint) || isQuoteMint(mint)) {+ // Quote/stablecoin/LST mints are not coins — no conviction card for them.res.statusCode = 400;res.setHeader('content-type', 'text/plain');res.end('bad mint');diff --git a/api/oracle/stats.js b/api/oracle/stats.jsindex 247cb5c5f..380522f50 100644--- a/api/oracle/stats.js+++ b/api/oracle/stats.js@@ -22,6 +22,7 @@import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { sql } from '../_lib/db.js';+import { QUOTE_MINT_LIST } from '../_lib/quote-mints.js';const NETWORKS = new Set(['mainnet', 'devnet']);@@ -45,6 +46,7 @@ export default wrap(async (req, res) => {count(*) filter (where tier = 'strong') as strong_countfrom oracle_convictionwhere network = ${network}+ and mint <> all(${QUOTE_MINT_LIST}::text[])`.catch(() => [{}]),// Open oracle_watch_actions (not yet settled).@@ -64,6 +66,7 @@ export default wrap(async (req, res) => {from oracle_conviction cjoin pump_coin_outcomes o on o.mint = c.mintwhere c.network = ${network}+ and c.mint <> all(${QUOTE_MINT_LIST}::text[])`.catch(() => [{}]),// Distinct armed agents.diff --git a/deploy/sniper/cloudrun.yaml b/deploy/sniper/cloudrun.yamlindex a2d16ef7e..7ad53954e 100644--- a/deploy/sniper/cloudrun.yaml+++ b/deploy/sniper/cloudrun.yaml@@ -69,10 +69,14 @@ spec:env:- name: NODE_ENVvalue: production- # DEFAULT SIMULATE. Flip to "live" ONLY via the documented cutover- # (deploy/sniper/README.md) once at least one agent wallet is funded.+ # LIVE: signs + broadcasts real trades from agent wallets. Requires the+ # sniper-solana-rpc-url secret set to a real RPC and ≥1 funded agent+ # wallet with an armed strategy, or the worker crash-loops / every buy+ # fails. Code guardrails still apply (mandatory stop-loss, price-impact+ # breaker, daily budget, kill switches). Set back to "simulate" to halt+ # all spend without touching open positions.- name: SNIPER_MODE- value: simulate+ value: live- name: SNIPER_NETWORKvalue: mainnet# Emergency stop: set to "1" and redeploy to halt all new buys whilediff --git a/docs/autonomous-x402.md b/docs/autonomous-x402.mdnew file mode 100644index 000000000..cccd3a1e0--- /dev/null+++ b/docs/autonomous-x402.md@@ -0,0 +1,111 @@+# Autonomous x402 Loop++The autonomous x402 loop is the engine that makes three.ws an **active+participant** in the x402 agent-to-agent economy rather than just a passive+facilitator. On a schedule it pays — with real USDC over x402 — to call our own+paid endpoints (and a bounded set of external, bazaar-discovered services),+turning the results into market intel, health checks, and analytics the rest of+the platform consumes.++This is the system that already does "an agent buys polling information": the+loop's seeder wallet pays per call for crypto/token intel and feeds the result to+the sniper oracle gate.++> Source: [`api/cron/x402-autonomous-loop.js`](../api/cron/x402-autonomous-loop.js),+> registry [`api/_lib/x402/autonomous-registry.js`](../api/_lib/x402/autonomous-registry.js),+> pipelines under `api/_lib/x402/pipelines/`.++---++## How a tick works++The loop runs from the `x402-autonomous-loop` cron, scheduled every **5 minutes**+(`*/5 * * * *` in [`vercel.json`](../vercel.json)). Each tick:++1. Selects up to `X402_AUTONOMOUS_MAX_PER_TICK` **ready** registry entries —+ those whose Redis cooldown has elapsed — sorted by priority descending.+2. For each entry, probes the endpoint for a `402` challenge, builds a Solana+ USDC payment, and fires the request with an `X-PAYMENT` header.+3. Records every call (success **and** failure) to `x402_autonomous_log`.+4. For `oracle` / `sniper` pipeline entries, extracts signal data and upserts it+ into `oracle_intel_signals` for the sniper oracle gate to consume.+5. Enforces a **daily USDC spend cap** across all calls in the loop.++Payments are real on chain — no mocks, no simulations.++## Configuration++| Env var | Default | Purpose |+|---|---|---|+| `X402_SEED_SOLANA_SECRET_BASE58` | _(preferred)_ | The seeder keypair that pays for calls. |+| `X402_AGENT_SOLANA_SECRET_BASE58` | _(fallback)_ | Used if the seeder secret is absent. |+| `X402_AUTONOMOUS_ENABLED` | enabled | Set to `false` to pause without removing entries. |+| `X402_AUTONOMOUS_MAX_PER_TICK` | `8` | Max calls per cron tick. |+| `X402_AUTONOMOUS_DAILY_CAP_ATOMIC` | `5000000` ($5) | Daily USDC cap, in 6-decimal atomics. |+| `CRON_SECRET` | _(required)_ | Vercel cron authorization. |+| `X402_ASSET_MINT_SOLANA` | USDC mint | The asset paid with (Solana USDC). |+| `SOLANA_RPC_URL` | — | RPC used to build and submit the payment. |++This loop's treasury is **separate** from the [circulation engine](circulation-engine.md)+treasury (`CIRCULATION_TREASURY_SECRET`). Circulation funds agent-to-agent SOL /+$THREE activity; this loop funds USDC intel purchases. They do not fund each+other.++## The registry++Every scheduled call is a registry entry in `autonomous-registry.js`. An entry+declares:++| Field | Purpose |+|---|---|+| `id` | Unique key; also the Redis cooldown key. |+| `name` | Human label for logs and analytics. |+| `path` | URL path (self-call) or full URL (external bazaar service). |+| `method`, `body` | Request shape; `body` may be a function of the run context. |+| `cooldown_s` | Minimum seconds between calls. |+| `priority` | 1–100; higher wins when several entries are ready. |+| `pipeline` | Tag: `oracle`, `health`, `volume`, `sniper`, `qa`, `forge`, `discovery`, `security`, `circuit-breaker`, `self`, `external`. |+| `enabled` | Set `false` to pause an entry. |+| `extractSignal` | Optional: maps the response into `signal_data` (for oracle entries, `{ mint?, signal, confidence, headline }`). |+| `resolveTarget` | Optional: computes the request path dynamically per call (for entries that rotate over a set of resources). |+| `storeValue` | Optional: persists the extracted value to a dedicated table; wrapped in try/catch so a DB failure never crashes the tick. |+| `run` | Optional: owns a full multi-call sequence (its own payments, recording, extraction) and returns one summary row. |++## Pipelines++The registry groups entries into pipelines. The main ones in production:++- **`oracle`** — pays for our own `crypto-intel` (SOL / BTC / ETH / $THREE /+ pump), `token-intel`, USDC peg monitoring, pump volume/whale anomaly scans,+ fact-checks, bazaar price trends and new-listing scans, and skill-marketplace+ price distribution. Results upsert into `oracle_intel_signals`.+- **`sniper`** — token-intel pre-snipe gate and sniper intel enrichment that feed+ the sniper's entry decisions.+- **`discovery` / `external`** — bazaar discovery warmup and catalog refresh that+ sweep external x402 service categories so the platform's directory stays fresh.+- **`health` / `circuit-breaker`** — wallet-balance monitors, cross-network+ circuit-breaker probes, club/social analytics.+- **`security`** — payment-proof idempotency and API-key bypass audits that+ exercise our own payment guards end to end.+- **`volume`** — small, bounded activity entries that keep the economy's heartbeat+ visible.+- **`qa` / `forge` / `self`** — animation-retarget QA, forge content generation,+ GLB size optimization, avatar thumbnail regeneration.++To pause any entry without a deploy, set its `enabled: false`; to pause the whole+loop, set `X402_AUTONOMOUS_ENABLED=false`.++## Where results land++| Sink | Written by |+|---|---|+| `x402_autonomous_log` | Every call (success or failure), with `signal_data` / `value_extracted`. |+| `oracle_intel_signals` | `oracle` / `sniper` entries, keyed by source + topic; consumed by the sniper oracle gate. |+| `agent_custody_events` | The USDC spend, with `category: 'x402'` (see [Money feed](money-feed.md)). |+| Dedicated stores | Pipeline-specific tables (pricing tracker, reputation snapshots, leaderboard, sniper analytics, …). |++## Related++- [x402 endpoints](x402-endpoints.md) — the paid endpoints this loop calls.+- [x402 buyer client](x402-buyer.md) — the client wrappers it pays with.+- [Circulation engine](circulation-engine.md) — the separate SOL/$THREE activity loop.diff --git a/docs/circulation-engine.md b/docs/circulation-engine.mdnew file mode 100644index 000000000..3c51815c5--- /dev/null+++ b/docs/circulation-engine.md@@ -0,0 +1,163 @@+# Circulation Engine++The circulation engine is three.ws's autonomous agent-to-agent activity loop. It+operates a pool of real platform agents — each a published marketplace listing+with its own custodial Solana (and optionally EVM) wallet — and on every tick it+makes those agents do real, on-chain things with one another: tip each other,+pay for services, trade and launch coins, register on-chain identities, and list+and buy skills and assets.++Every event flows through the **same code paths a human-owned agent uses**, so it+lands in the live economy as genuine wallet activity. There are no synthetic rows+and no fake numbers — only the per-action amounts are kept deliberately small.++> Source: [`api/_lib/circulation.js`](../api/_lib/circulation.js),+> [`api/_lib/circulation-personas.js`](../api/_lib/circulation-personas.js),+> cron entry [`api/cron/pulse-tick.js`](../api/cron/pulse-tick.js).++---++## How it works++1. A single **treasury wallet** (funded by the operator) backs the whole engine.+2. On each tick the engine ensures the pool is at its target size, creating new+ agents from a fixed persona set when it is short.+3. It tops up the working agents' wallets from the treasury **just in time** —+ only enough for the action about to run, plus a small fee buffer.+4. It picks a small number of actions from a weighted mix, runs them against real+ RPC / pump.fun / marketplace code paths, and records each one.+5. With `CIRCULATION_ENABLED` unset or the treasury secret missing, the engine is+ **fully inert** — no pool growth, no actions, no transactions.++## The agent pool++The pool is seeded from a fixed set of base personas (Atlas, Vega, Sable, Orion,+Lyra, Cipher, Nova, Quill, Flint, Meridian, Pixel, Echo, Forge, Tally, Harbor,+Glyph, …), each with a profession and skill set. As the pool grows past the+persona count it spawns numbered variants (`Atlas #2`, `Atlas #3`, …) up to the+configured ceiling. Pool members are agents tagged `meta.circulation = 'true'`+and are loaded fresh from the database every tick.++Senders and receivers for an action are drawn from this pool at random+(`pickTwo()`); there is no fixed "sender" subset — every pool agent is eligible+for every role on every tick.++## Action types++Each tick first gives **heavyweight, low-frequency actions** first refusal, then+falls back to a weighted everyday mix.++### Heavyweight (solo) actions++| Action | Trigger | Real? |+|---|---|---|+| `launch` | ~14% when pool ≥ 2, < 8 launches today, none this hour | Real pump.fun launch on chain, recorded in `pump_agent_mints` |+| `deploy` | ~6% when an EVM treasury is configured and < 6 deploys today | Real ERC-8004 identity registration on the configured EVM chain |++### Everyday weighted mix++| Action | Weight | Real money? | Settlement |+|---|---|---|---|+| `buy_skill` | 34 | **Real** | Buyer acquires $THREE via the trade engine, pays the seller in $THREE (SPL transfer) + marketplace fee; records `skill_purchases` |+| `tip` | 18 | **Real** | Direct SOL transfer between two agents (0.001–0.006 SOL) |+| `trade` | 12 | **Real** | On-chain trade via the platform trade engine; records `pump_agent_trades` |+| `trial` | 12 | DB only | Records a `trial` skill-purchase row (no transfer) |+| `buy_asset` | 8 | **Real** | Buyer pays in $THREE (SPL transfer) for an avatar/agent/plugin; records `asset_purchases` |+| `review` | 8 | DB only | Inserts a marketplace review row |+| `payment` | 6 | **Real** | Direct SOL transfer for a named service (0.0012–0.01 SOL), logged with category `x402` |++Listing actions (`list_skill`, `list_asset`) are emitted as needed to keep+sellers "stocked" and are database-only (they create a price row, not a+transfer).++> The only coin the engine ever launches, trades, or prices marketplace+> inventory against is **$THREE**+> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). The `launch` and `trade`+> actions operate on a runtime mint and never hardcode or promote any other+> token.++## Amounts++All amounts are small by design — a steady, believable heartbeat, not volume for+its own sake.++| Constant | Value |+|---|---|+| `TIP_MIN` / `TIP_MAX` | 0.001 / 0.006 SOL |+| `PAY_MIN` / `PAY_MAX` | 0.0012 / 0.01 SOL |+| `SKILL_PRICE_MIN/MAX_THREE` | 80 / 1200 $THREE |+| `ASSET_PRICE_MIN/MAX_THREE` | 600 / 4000 $THREE |+| `AGENT_FLOOR` (top-up target) | 0.02 SOL |+| `LAUNCH_FLOOR` | 0.034 SOL |+| `THREE_TOPUP_SOL` (buy $THREE when short) | 0.012 SOL |+| `FEE_BUFFER` (per-tx headroom) | 0.0009 SOL |++## Cadence++The engine runs from the `pulse-tick` cron, scheduled every **2 minutes**+(`*/2 * * * *` in [`vercel.json`](../vercel.json)). Each tick grows the pool by+up to `CIRCULATION_GROWTH_PER_TICK` agents and runs `CIRCULATION_ACTIONS_PER_TICK`+everyday actions (plus any heavyweight action that wins first refusal). Cron+functions are bounded to a 120-second `maxDuration`.++## Configuration++| Env var | Default | Range | Purpose |+|---|---|---|---|+| `CIRCULATION_ENABLED` | _(off)_ | `1`/`true`/`yes` | Master gate. Engine is inert unless set. |+| `CIRCULATION_TREASURY_SECRET` | _(required)_ | base58 / base64 / JSON keypair | Solana treasury that funds the pool. |+| `CIRCULATION_NETWORK` | `mainnet` | `mainnet` / `devnet` | Solana cluster. |+| `CIRCULATION_POOL_TARGET` | `14` | 2–2000 | Target pool size. |+| `CIRCULATION_GROWTH_PER_TICK` | `3` | 1–40 | New agents created per tick when short. |+| `CIRCULATION_ACTIONS_PER_TICK` | `2` | 1–12 | Everyday actions executed per tick. |+| `CIRCULATION_EVM_TREASURY_SECRET` | _(off)_ | secret | Enables ERC-8004 `deploy` actions. |+| `CIRCULATION_EVM_CHAIN_ID` | `8453` (Base) | 1–1e9 | EVM chain for deploys. |+| `CIRCULATION_REAL_SELLER_DEMAND` | _(off)_ | bool | Route a bounded share of demand to real, user-owned activated sellers. |+| `CIRCULATION_REAL_SELLER_DAILY_CAP` | `3` | 1–50 | Max purchases routed to each real seller per day. |++## Recording and where it surfaces++| Sink | What it holds |+|---|---|+| `circulation_actions` | One row per action the engine ran (kind, actors, signature, amount). |+| `agent_custody_events` | The canonical wallet ledger entry for every real spend/transfer (see [Money feed](money-feed.md)). |+| `pump_agent_trades` / `pump_agent_mints` | Trade and launch records, surfaced in the pump feed and `/launches`. |+| `skill_purchases` / `asset_purchases` | Marketplace settlement records (see [Marketplace](marketplace.md)). |++Real spends are written to `agent_custody_events`, which powers per-agent+portfolio balances and the agent-to-agent economy volume dashboard (all-time and+7-day volume, top earners and spenders). Trades and launches additionally surface+in the public pump feed and the launches directory.++## Safety++- **Skips, not errors.** A low treasury, an under-sized pool, or a buyer that+ can't be funded raises an internal `Skip` — an expected, logged non-event. The+ tick records it and moves on; it is never surfaced as a failure.+- **Just-in-time funding.** Wallets are topped up only to `AGENT_FLOOR` plus the+ amount needed for the imminent action, bounding treasury exposure per tick.+- **Bounded heavyweight actions.** Launches and deploys are rate-limited per hour+ and per day independent of the everyday mix.+- **Real-seller demand is opt-in and capped.** When enabled, manufactured demand+ routed to user-owned sellers is bounded by a price band and a per-seller daily+ cap; when off, all demand stays inside the circulation pool.++## Ramping volume++The safest levers, in order, all reversible:++1. Raise `CIRCULATION_ACTIONS_PER_TICK` (e.g. 2 → 6) — near-linear throughput.+2. Raise `CIRCULATION_POOL_TARGET` (e.g. 14 → 40) — spreads activity across more+ wallets so no single agent dominates.+3. Raise `CIRCULATION_GROWTH_PER_TICK` to fill a larger pool faster.++Higher throughput burns more treasury SOL and pushes against the 120-second cron+budget, so raise gradually and watch tick runtime and treasury balance.++## Related++- [Money feed](money-feed.md) — where circulation activity surfaces.+- [Autonomous x402 loop](autonomous-x402.md) — the separate treasury-paid loop+ that buys polling intel from our own x402 endpoints.+- [Agent wallets](agent-wallets.md) — the custodial key model every action uses.+- [Marketplace](marketplace.md), [Coin launches](coin-launches.md).diff --git a/docs/money-feed.md b/docs/money-feed.mdnew file mode 100644index 000000000..de2e704e9--- /dev/null+++ b/docs/money-feed.md@@ -0,0 +1,95 @@+# Money Feed++"Money feed" refers to the surfaces that show real value moving through three.ws:+the live activity ticker, the on-chain custody ledger that records every agent+spend, and the economy volume dashboard built on top of it. They are distinct+layers with distinct sources — this page maps them so you know where any given+event lives.++---++## The three layers++| Layer | Backing store | Surface | What it shows |+|---|---|---|---|+| **Live ticker** | Redis list `feed:events` | `GET /api/feed`, widget `public/feed.js` | A curated, newest-first stream of notable public events. |+| **Custody ledger** | Postgres `agent_custody_events` | Portfolio + volume dashboards | Every real wallet spend/transfer, the canonical record of money moved. |+| **Domain records** | `circulation_actions`, `pump_agent_trades`, `pump_agent_mints`, `skill_purchases`, `asset_purchases` | Pump feed, `/launches`, agent profiles | Per-domain detail behind each event. |++## Live ticker — `/api/feed`++A public, read-only, cache-friendly endpoint backed by a capped Redis list+(`feed:events`, max 200 entries). The on-page widget polls it every ~20 seconds+and prepends anything new. The endpoint is edge-cached+(`s-maxage=20, stale-while-revalidate=60`) so idle tabs don't drain the Redis+request quota.++> Source: [`api/feed.js`](../api/feed.js), [`api/_lib/feed.js`](../api/_lib/feed.js).++Events are written with `publishFeedEvent({ type, ... })`, which only accepts a+fixed allow-list of types:++| Type | Meaning |+|---|---|+| `coin-buy` | A coin buy landed. |+| `agent-deploy` / `agent-onchain` | An agent was deployed / registered on chain. |+| `payment` | A skill/service payment confirmed (`usdcAtomic`, `recipientLabel`, `txSig`, `explorerUrl`). |+| `level-up`, `world-join`, `jackpot`, `mission-complete` | Play / world events. |+| `member-join` | A person signed in (throttled to once per user per 6h). |+| `agora-registered`, `agora-task-posted`, `agora-hired`, `agora-task-claimed`, `agora-task-completed`, `agora-earned`, `agora-vouched`, `agora-flagged` | [Agora](agora.md) on-chain economy lifecycle events. |++The ticker is a **curated delight layer**, not an exhaustive log: an event only+appears if a caller explicitly published it with an allow-listed type. Internal+transfers (such as circulation tips) are recorded in the custody ledger but are+not necessarily echoed to the ticker.++Per-user notifications use a parallel path, `publishUserEvent()`, which writes to+`user_notifications` (DB) rather than the public list — for owner-facing events+like `payment-earned`, `sale`, `embed`, `remix`, `reply`, and `follow`.++## Custody ledger — `agent_custody_events`++Every real spend or transfer made by an agent wallet is written here via+`recordCustodyEvent()`, regardless of whether it also appears in the ticker. This+is the **authoritative record of money moved** and powers portfolio balances and+the volume dashboard.++> Source: `recordCustodyEvent()` in+> [`api/_lib/agent-trade-guards.js`](../api/_lib/agent-trade-guards.js).++Each row carries: `agent_id`, `user_id`, `event_type` (e.g. `spend`),+`category` (`trade` | `snipe` | `x402` | `withdraw` | `tip` | …), `network`,+`asset`, `amount_lamports` / `amount_raw`, `usd`, `destination`, `signature`,+`status`, an `idempotency_key`, and a `meta` JSON blob. Spends pass through the+spend-cap and policy engine before they are recorded (see+[Agent wallets](agent-wallets.md)).++## What flows in from where++| Producer | Ledger? | Ticker? | Domain record |+|---|---|---|---|+| [Circulation engine](circulation-engine.md) tips/payments/trades/buys | Yes | Trades/launches via pump feed | `circulation_actions` + domain table |+| [Marketplace](marketplace.md) skill/asset purchase | Yes | `payment` / `sale` | `skill_purchases` / `asset_purchases` |+| [Coin launches](coin-launches.md) | Yes | `coin-buy` / `agent-deploy` | `pump_agent_mints` |+| Sniper trades | Yes (`category: 'snipe'`) | — | `agent_sniper_positions` |+| [Autonomous x402 loop](autonomous-x402.md) | Yes (`category: 'x402'`) | — | `x402_autonomous_log` |+| x402 service payments | Yes | `payment` | — |+| [Agora](agora.md) tasks | On settlement | `agora-*` | on-chain |++## Reading the feed programmatically++```bash+curl 'https://three.ws/api/feed?limit=30'+# → { "events": [ { "type": "payment", "actor": "…", "usdcAtomic": 10000,+# "txSig": "…", "explorerUrl": "https://solscan.io/tx/…",+# "ts": 1719600000000, "id": "…" }, … ], "count": 30 }+```++`limit` is clamped to 1–100; events are newest-first and each has a stable `id`+and millisecond `ts`.++## Related++- [Circulation engine](circulation-engine.md) — the largest producer of activity.+- [Autonomous x402 loop](autonomous-x402.md) — treasury-paid intel purchases.+- [Agent wallets](agent-wallets.md) — how spends are gated before they're recorded.diff --git a/pages/admin/launcher.html b/pages/admin/launcher.htmlindex f00f2f5ed..8b60cb1f1 100644--- a/pages/admin/launcher.html+++ b/pages/admin/launcher.html@@ -175,7 +175,7 @@</div><ol class="ml-runs" id="ml-runs"></ol><div class="ml-runs-empty" id="ml-runs-empty" hidden>- <p>No launches yet. Arm the launcher to see live activity here.</p>+ <p>No launches yet. The launcher is live by default — runs appear here once the master wallet is funded and the next cadence tick fires.</p></div></section></div>diff --git a/pages/agent-detail.html b/pages/agent-detail.htmlindex df04c8f53..7e9497812 100644--- a/pages/agent-detail.html+++ b/pages/agent-detail.html@@ -139,6 +139,11 @@/* Walk-with-this-agent preview card. Token-styled: reuses the page'ssurface/border variables so it reads as one of the agent cards. */.ad-walk-card .ad-preview-hint { margin-left: auto; font-size: 11px; color: var(--ink-dim, #888); }+ /* The card tiles inside the masonry grid, so its width is set by the+ column — not the viewport. Make it a query container so the body+ below can stack on the card's own width instead of guessing from the+ screen size (which left the copy column at ~80px, one word per line). */+ .ad-walk-card { container-type: inline-size; }/* Two-column body: avatar stage left, supporting copy + CTA fill theright so the card reads as one composed unit instead of a small framemarooned in empty space. */@@ -194,7 +199,10 @@flex-shrink: 0;color: rgba(124, 92, 255, 0.85);}- @media (max-width: 640px) {+ /* Stack when the card itself (not the screen) is too narrow for a+ readable two-up split — covers narrow masonry columns and small+ viewports alike. */+ @container (max-width: 520px) {.ad-walk-body { grid-template-columns: 1fr; }.ad-walk-stage { max-width: 300px; margin: 0 auto; }.ad-walk-info { text-align: center; align-items: center; }diff --git a/public/agent-commerce.css b/public/agent-commerce.cssnew file mode 100644index 000000000..311fd6d61--- /dev/null+++ b/public/agent-commerce.css@@ -0,0 +1,476 @@+/* ── "The Agent-to-Agent Economy" explainer ─────────────────────────────── */+/* Layers on top of features-landing.css. Pulls only from style.css :root. */++/* ── Lede ──────────────────────────────────────────────────────────────── */+.ac-lede {+ border-top: 1px solid var(--stroke);+}++.ac-lede-inner {+ max-width: 820px;+}++.ac-lede p {+ font-family: var(--font-display);+ font-size: clamp(1.25rem, 2.6vw, 1.75rem);+ line-height: 1.45;+ font-weight: 500;+ color: var(--ink);+ margin: 0;+ letter-spacing: -0.01em;+}++.ac-lede p strong {+ color: var(--ink);+ font-weight: 700;+}++.ac-lede p .ac-dim {+ color: var(--ink-dim);+}++/* ── The loop (5-stage pipeline) ───────────────────────────────────────── */+.ac-loop {+ border-top: 1px solid var(--stroke);+}++.ac-loop h2,+.ac-receipt-sec h2,+.ac-surfaces h2,+.ac-build h2 {+ font-family: var(--font-display);+ font-size: clamp(1.4rem, 3vw, 2rem);+ font-weight: 700;+ letter-spacing: -0.02em;+ color: var(--ink);+ margin: 0 0 var(--space-sm);+}++.ac-intro {+ font-size: var(--text-lg);+ line-height: 1.6;+ color: var(--ink-dim);+ margin: 0 0 var(--space-xl);+ max-width: 64ch;+}++.ac-flow {+ display: grid;+ grid-template-columns: repeat(5, 1fr);+ gap: var(--space-sm);+ counter-reset: ac-step;+}++@media (max-width: 920px) {+ .ac-flow {+ grid-template-columns: repeat(2, 1fr);+ }+}++@media (max-width: 480px) {+ .ac-flow {+ grid-template-columns: 1fr;+ }+}++.ac-stage {+ position: relative;+ background: var(--surface-1);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-card);+ padding: var(--space-lg);+ display: flex;+ flex-direction: column;+ gap: var(--space-xs);+ transition: border-color 0.2s ease, background 0.2s ease, transform 0.2s ease;+}++.ac-stage:hover {+ border-color: var(--stroke-strong);+ background: var(--surface-2);+ transform: translateY(-2px);+}++.ac-stage-num {+ counter-increment: ac-step;+ font-family: var(--font-mono);+ font-size: var(--text-xs);+ font-weight: 700;+ color: var(--accent);+ opacity: 0.6;+ letter-spacing: 0.1em;+}++.ac-stage-num::before {+ content: 'STEP ' counter(ac-step, decimal-leading-zero);+}++.ac-stage h3 {+ font-family: var(--font-display);+ font-size: var(--text-base);+ font-weight: 700;+ color: var(--ink);+ margin: 0;+ line-height: 1.3;+}++.ac-stage p {+ font-size: var(--text-sm);+ line-height: 1.55;+ color: var(--ink-dim);+ margin: 0;+}++.ac-stage code {+ font-family: var(--font-mono);+ font-size: 0.78em;+ color: var(--ink);+ background: var(--surface-3);+ border-radius: var(--radius-sm, 5px);+ padding: 0.05em 0.35em;+}++/* ── Example provenance receipt ─────────────────────────────────────────── */+.ac-receipt-sec {+ border-top: 1px solid var(--stroke);+}++.ac-receipt-grid {+ display: grid;+ grid-template-columns: 1.1fr 1fr;+ gap: var(--space-xl);+ align-items: start;+}++@media (max-width: 820px) {+ .ac-receipt-grid {+ grid-template-columns: 1fr;+ gap: var(--space-lg);+ }+}++.ac-receipt-copy p {+ font-size: var(--text-base);+ line-height: 1.7;+ color: var(--ink-dim);+ margin: 0 0 var(--space-md);+}++.ac-receipt-copy p:last-child {+ margin-bottom: 0;+}++.ac-receipt {+ background: var(--surface-1);+ border: 1px solid var(--stroke-strong);+ border-radius: var(--radius-card);+ overflow: hidden;+ box-shadow: 0 16px 50px rgba(0, 0, 0, 0.35);+}++.ac-receipt-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: var(--space-sm);+ padding: var(--space-sm) var(--space-md);+ background: var(--surface-2);+ border-bottom: 1px solid var(--stroke);+}++.ac-receipt-head .ac-r-title {+ font-family: var(--font-mono);+ font-size: var(--text-xs);+ letter-spacing: 0.1em;+ text-transform: uppercase;+ color: var(--ink-dim);+}++.ac-r-badge {+ display: inline-flex;+ align-items: center;+ gap: 0.4rem;+ font-family: var(--font-mono);+ font-size: var(--text-xs);+ font-weight: 700;+ color: #2ec98a;+ background: rgba(46, 201, 138, 0.12);+ border: 1px solid rgba(46, 201, 138, 0.35);+ border-radius: var(--radius-pill);+ padding: 0.2rem 0.6rem;+}++.ac-r-badge::before {+ content: '';+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: #2ec98a;+}++.ac-receipt-rows {+ padding: var(--space-sm) var(--space-md);+}++.ac-r-row {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: var(--space-md);+ padding: var(--space-xs) 0;+ border-bottom: 1px solid var(--stroke);+ font-size: var(--text-sm);+}++.ac-r-row:last-child {+ border-bottom: none;+}++.ac-r-k {+ color: var(--ink-dim);+ font-family: var(--font-mono);+ font-size: var(--text-xs);+ letter-spacing: 0.04em;+ text-transform: uppercase;+ white-space: nowrap;+}++.ac-r-v {+ color: var(--ink);+ text-align: right;+ font-weight: 600;+}++.ac-r-v.ac-mono {+ font-family: var(--font-mono);+ font-weight: 500;+ word-break: break-all;+}++.ac-r-v .ac-amt {+ color: #2ec98a;+}++.ac-receipt-foot {+ padding: var(--space-sm) var(--space-md);+ border-top: 1px solid var(--stroke);+ background: var(--surface-2);+ font-family: var(--font-mono);+ font-size: var(--text-xs);+ color: var(--ink-dim);+ display: flex;+ align-items: center;+ gap: 0.4rem;+}++.ac-receipt-caption {+ margin-top: var(--space-sm);+ font-family: var(--font-mono);+ font-size: var(--text-xs);+ color: var(--ink-dim);+ letter-spacing: 0.02em;+}++/* ── Surfaces grid ──────────────────────────────────────────────────────── */+.ac-surfaces {+ border-top: 1px solid var(--stroke);+}++.ac-surface-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));+ gap: var(--space-md);+}++.ac-surface {+ display: flex;+ flex-direction: column;+ gap: var(--space-xs);+ background: var(--surface-1);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-card);+ padding: var(--space-lg);+ text-decoration: none;+ transition: border-color 0.2s ease, background 0.2s ease, transform 0.2s ease;+}++.ac-surface:hover {+ border-color: var(--stroke-strong);+ background: var(--surface-2);+ transform: translateY(-2px);+}++.ac-surface:focus-visible {+ outline: 2px solid var(--focus-ring-color);+ outline-offset: 3px;+}++.ac-surface-top {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: var(--space-sm);+}++.ac-surface-t {+ font-family: var(--font-display);+ font-size: var(--text-base);+ font-weight: 700;+ color: var(--ink);+}++.ac-live {+ display: inline-flex;+ align-items: center;+ gap: 0.35rem;+ font-family: var(--font-mono);+ font-size: 0.62rem;+ letter-spacing: 0.1em;+ text-transform: uppercase;+ color: #2ec98a;+}++.ac-live::before {+ content: '';+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: #2ec98a;+ box-shadow: 0 0 0 0 rgba(46, 201, 138, 0.5);+ animation: ac-pulse 2s infinite;+}++@keyframes ac-pulse {+ 0% { box-shadow: 0 0 0 0 rgba(46, 201, 138, 0.45); }+ 70% { box-shadow: 0 0 0 6px rgba(46, 201, 138, 0); }+ 100% { box-shadow: 0 0 0 0 rgba(46, 201, 138, 0); }+}++.ac-surface-d {+ font-size: var(--text-sm);+ line-height: 1.55;+ color: var(--ink-dim);+ margin: 0;+}++.ac-surface-go {+ margin-top: auto;+ font-family: var(--font-mono);+ font-size: var(--text-xs);+ color: var(--accent);+ opacity: 0.85;+}++/* ── Build-on-it (developer) ────────────────────────────────────────────── */+.ac-build {+ border-top: 1px solid var(--stroke);+}++.ac-build-grid {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: var(--space-xl);+ align-items: start;+}++@media (max-width: 820px) {+ .ac-build-grid {+ grid-template-columns: 1fr;+ }+}++.ac-block {+ margin-bottom: var(--space-lg);+}++.ac-block:last-child {+ margin-bottom: 0;+}++.ac-block h3 {+ font-family: var(--font-display);+ font-size: var(--text-lg);+ font-weight: 700;+ color: var(--ink);+ margin: 0 0 var(--space-xs);+}++.ac-block p {+ font-size: var(--text-base);+ line-height: 1.65;+ color: var(--ink-dim);+ margin: 0;+}++.ac-block p a,+.ac-receipt-copy a,+.ac-stage p a {+ color: var(--ink);+ text-decoration: underline;+ text-underline-offset: 2px;+ text-decoration-color: var(--stroke-strong);+ transition: text-decoration-color 0.15s ease;+}++.ac-block p a:hover,+.ac-receipt-copy a:hover,+.ac-stage p a:hover {+ text-decoration-color: var(--accent);+}++.ac-code {+ background: var(--surface-1);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-card);+ overflow: hidden;+ position: sticky;+ top: var(--space-md);+}++.ac-code-bar {+ display: flex;+ align-items: center;+ gap: 0.4rem;+ padding: var(--space-sm) var(--space-md);+ background: var(--surface-2);+ border-bottom: 1px solid var(--stroke);+}++.ac-code-dot {+ width: 8px;+ height: 8px;+ border-radius: 50%;+ background: var(--stroke-strong);+}++.ac-code-name {+ margin-left: var(--space-xs);+ font-family: var(--font-mono);+ font-size: var(--text-xs);+ color: var(--ink-dim);+}++.ac-code pre {+ margin: 0;+ padding: var(--space-md);+ overflow-x: auto;+ font-family: var(--font-mono);+ font-size: var(--text-sm);+ line-height: 1.65;+ color: var(--ink);+ tab-size: 2;+}++.ac-code pre .ac-c { color: var(--ink-dim); }+.ac-code pre .ac-k { color: #8ab4ff; }+.ac-code pre .ac-s { color: #2ec98a; }++/* ── Reduced motion ─────────────────────────────────────────────────────── */+@media (prefers-reduced-motion: reduce) {+ .ac-stage,+ .ac-surface,+ .ac-live::before {+ transition: none;+ animation: none;+ }+}diff --git a/scripts/deploy-sniper.mjs b/scripts/deploy-sniper.mjsindex 3a06149ce..5e9ef1cfb 100644--- a/scripts/deploy-sniper.mjs+++ b/scripts/deploy-sniper.mjs@@ -34,7 +34,7 @@import { spawnSync } from 'node:child_process';import { fileURLToPath } from 'node:url';import { dirname, resolve } from 'node:path';-import { existsSync } from 'node:fs';+import { existsSync, readFileSync } from 'node:fs';const __dirname = dirname(fileURLToPath(import.meta.url));const REPO_ROOT = resolve(__dirname, '..');@@ -161,7 +161,16 @@ function build() {}function deploy() {- log('deploying service (minScale=maxScale=1, no CPU throttling, mode=simulate)…');+ // Read the mode straight from the manifest being applied so the log never+ // lies about whether this deploy spends real SOL.+ let mode = 'unknown';+ try {+ const yaml = readFileSync(CLOUDRUN, 'utf8');+ const m = yaml.match(/name:\s*SNIPER_MODE[\s\S]*?value:\s*["']?(live|simulate)/);+ if (m) mode = m[1];+ } catch { /* fall back to "unknown" in the log */ }+ log(`deploying service (minScale=maxScale=1, no CPU throttling, mode=${mode})…`);+ if (mode === 'live') warn('LIVE mode: this service will sign + broadcast real trades from agent wallets.');const r = gcloud(['run', 'services', 'replace', CLOUDRUN, `--region=${REGION}`]);if (r.status !== 0) die('gcloud run services replace failed');ok('service config applied');diff --git a/src/launch-detail.css b/src/launch-detail.cssindex faeaf5840..2ba9a4104 100644--- a/src/launch-detail.css+++ b/src/launch-detail.css@@ -522,8 +522,17 @@ body {linear-gradient(180deg, var(--surface-2), var(--surface-3));isolation: isolate;}-.ld-agent-3d { position: absolute; inset: 0; width: 100%; height: 100%; display: block; opacity: 0; transition: opacity var(--duration-base) ease; }+.ld-agent-3d { position: absolute; inset: 0; width: 100%; height: 100%; display: block; opacity: 0; transition: opacity var(--duration-base) ease; z-index: 1; }.ld-agent-stage[data-state='ready'] .ld-agent-3d { opacity: 1; }+.ld-agent-stage-poster {+ position: absolute; inset: 0; z-index: 0;+ background-size: cover; background-position: center top;+ filter: blur(18px) saturate(1.1); transform: scale(1.18);+ opacity: 0.45; transition: opacity var(--duration-base) ease;+ pointer-events: none;+}+.ld-agent-stage[data-state='ready'] .ld-agent-stage-poster,+.ld-agent-stage[data-state='error'] .ld-agent-stage-poster { opacity: 0; }.ld-agent-stage-load {position: absolute; inset: 0; z-index: 2;display: flex; flex-direction: column; align-items: center; justify-content: center; gap: var(--space-sm);diff --git a/src/launch-detail.js b/src/launch-detail.jsindex 61f917b10..5d95c7416 100644--- a/src/launch-detail.js+++ b/src/launch-detail.js@@ -37,6 +37,7 @@ import {} from './trader-format.js';import { walletChipEl } from './shared/agent-wallet-chip.js';import { agentAvatarGlb, hasCustomAvatar, seeInWorldHref } from './shared/agent-3d.js';+import { resolveDevR2Url } from './shared/dev-r2-proxy.js';const GRADUATION_CAP_USD = 69_000; // pump.fun bonding-curve graduation thresholdconst REDUCED_MOTION = window.matchMedia('(prefers-reduced-motion: reduce)').matches;@@ -1356,10 +1357,35 @@ function ensureAgent3DLib() {// context is paid only once the card scrolls into view, and a failed/slow load// degrades to the labelled fallback instead of a blank canvas.function buildAgentStage(agent) {- const glb = agentAvatarGlb(agent);+ // resolveDevR2Url is a no-op in production; on localhost / Codespaces it+ // rewrites the r2.dev GLB to the same-origin Vite proxy so the cross-origin+ // fetch isn't blocked by CORS. The mannequin fallback is a local path, so it+ // passes through untouched either way.+ const glb = resolveDevR2Url(agentAvatarGlb(agent));const custom = hasCustomAvatar(agent);+ const label = `${agent.name || 'Agent'} — interactive 3D avatar`;++ const stage = el('div', {+ class: 'ld-agent-stage',+ 'data-state': 'idle',+ role: 'img',+ 'aria-label': label,+ });++ // A blurred thumbnail backdrop fills the stage while the model streams in, so+ // the loading state reads as "this avatar, arriving" rather than an empty box.+ // It fades out once the GLB is framed. Falls back to the CSS gradient alone+ // when the agent has no thumbnail.+ if (agent.avatar_thumbnail_url) {+ stage.appendChild(+ el('div', {+ class: 'ld-agent-stage-poster',+ 'aria-hidden': 'true',+ style: `background-image:url('${encodeURI(agent.avatar_thumbnail_url)}')`,+ }),+ );+ }- const stage = el('div', { class: 'ld-agent-stage', 'data-state': 'idle' });const loadEl = el('div', { class: 'ld-agent-stage-load' }, [el('span', { class: 'ld-agent-stage-spin', 'aria-hidden': 'true' }),el('span', { class: 'ld-agent-stage-msg', text: 'Loading 3D…' }),@@ -1381,17 +1407,21 @@ function buildAgentStage(agent) {setMsg("Couldn't load the 3D viewer.");return;}- const a3d = el('agent-3d', {- class: 'ld-agent-3d',- alt: `${agent.name || 'Agent'} — 3D avatar`,- });+ const a3d = el('agent-3d', { class: 'ld-agent-3d', alt: label });a3d.setAttribute('controls', 'orbit');a3d.setAttribute('src', glb);+ // A slow R2/CDN read shouldn't leave the spinner spinning forever with no+ // explanation — after 15s, tell the user it's a big model or slow link.+ const slowTimer = setTimeout(() => {+ if (stage.dataset.state === 'idle') setMsg('Still loading — large model or slow connection.');+ }, 15_000);a3d.addEventListener('load', () => {+ clearTimeout(slowTimer);stage.dataset.state = 'ready';loadEl.remove();}, { once: true });a3d.addEventListener('error', () => {+ clearTimeout(slowTimer);stage.dataset.state = 'error';setMsg("Couldn't load the 3D model.");}, { once: true });@@ -1399,12 +1429,18 @@ function buildAgentStage(agent) {stage.appendChild(el('div', { class: 'ld-agent-stage-bar' }, [el('span', { class: 'ld-agent-stage-hint', text: custom ? 'Drag to orbit · scroll to zoom' : 'Base avatar · drag to orbit' }),- el('a', { class: 'ld-agent-stage-world', href: seeInWorldHref(agent), text: 'See in world →' }),+ el('a', {+ class: 'ld-agent-stage-world',+ href: seeInWorldHref(agent),+ text: 'See in world →',+ 'aria-label': `See ${agent.name || 'this agent'} in the $THREE world`,+ }),]),);};- // Pay for the WebGL context only when the card is actually near the viewport.+ // Pay for the WebGL context only when the card is actually near the viewport,+ // and tear the observer down once mounted so it can't fire twice.if ('IntersectionObserver' in window) {const io = new IntersectionObserver((entries) => {for (const e of entries) {diff --git a/vite.config.js b/vite.config.jsindex 79ba05628..0248949ec 100644--- a/vite.config.js+++ b/vite.config.js@@ -1559,63 +1559,6 @@ support: resolve(__dirname, 'pages/support.html'),},},},- {- // Vercel Web Analytics. The script is auto-served at- // /_vercel/insights/script.js by Vercel once Web Analytics is enabled- // for the project; it auto-captures pageviews (incl. client-side nav- // via the History API). No npm dependency or React component is needed —- // this is the framework-agnostic install for a vanilla multipage site,- // injected the same way as the PostHog snippet above so every- // Vite-processed page gets it. The `va` queue stub buffers any track()- // calls fired before the deferred script loads. Embed pages (iframes)- // are skipped to match PostHog's coverage and avoid double-counting- // host-page traffic. In dev the script 404s harmlessly (defer, no thrown- // error) — analytics only land in prod once enabled in the dashboard.- name: 'vercel-analytics',- transformIndexHtml: {- order: 'pre',- handler(_html, ctx) {- const EMBED_FILES = new Set([- 'widget.html',- 'embed.html',- 'avatar-embed.html',- 'agent-embed.html',- 'a-embed.html',- ]);- const filename = (ctx.filename || ctx.path || '')- .replace(/\\/g, '/')- .split('/')- .pop();- if (EMBED_FILES.has(filename)) return [];- return [- {- tag: 'script',- children:- 'window.va=window.va||function(){(window.vaq=window.vaq||[]).push(arguments)};',- injectTo: 'head',- },- // /_vercel/insights/script.js is only served by the platform on a- // real Vercel deploy (process.env.VERCEL is set there). Off-Vercel —- // the Vite dev server, the push-only 3D-Agent mirror, any static- // preview host — both the script and its /_vercel/insights/view ingest- // beacon 404, surfacing as a console error on every page. Gate- // injection on VERCEL to match the Speed Insights injector below; the- // `va` queue stub above still no-ops any track() calls everywhere else.- // (On Vercel, the /view beacon still 404s until Web Analytics is- // enabled in the project dashboard — that's a dashboard toggle.)- ...(process.env.VERCEL- ? [- {- tag: 'script',- attrs: { defer: true, src: '/_vercel/insights/script.js' },- injectTo: 'head',- },- ]- : []),- ];- },- },- },{// First-party client-side error reporting on every page (embeds// included — errors inside third-party iframe placements are exactlydiff --git a/workers/agent-sniper/auto-funder.js b/workers/agent-sniper/auto-funder.jsnew file mode 100644index 000000000..0877cee06--- /dev/null+++ b/workers/agent-sniper/auto-funder.js@@ -0,0 +1,216 @@+// agent-sniper — buy-side auto-funding loop.+//+// A live sniper's wallet drains as it buys. Without a top-up it silently goes+// broke and every subsequent snipe fails its balance check — a green heartbeat+// hiding a dead bot. This loop keeps each armed agent's OWN Solana wallet above+// a floor: when an agent's balance drops below SNIPER_AUTO_FUND_MIN_SOL it tops+// it back up to SNIPER_AUTO_FUND_TARGET_SOL from the launcher master wallet,+// reusing the same guarded transfer (caps + master-balance buffer + protected+// submit) the autonomous launcher uses.+//+// Guardrails (no env weakens them past the master's own balance buffer):+// - per-transfer cap (SNIPER_AUTO_FUND_PER_TX_SOL)+// - daily total cap (SNIPER_AUTO_FUND_DAILY_SOL), summed from the on-chain+// funding ledger so a worker restart can't bypass it+// - master balance buffer (enforced inside fundAgentForLaunch)+// In simulate mode it logs what it WOULD move and records a 'SIMULATED' ledger+// row — zero SOL leaves the master.++import { sql } from '../../api/_lib/db.js';+import { fundAgentForLaunch, masterBalanceSol } from '../../api/_lib/launcher-funding.js';+import { getSolBalance } from '../../api/_lib/avatar-wallet.js';+import { solanaConnection } from '../../api/_lib/agent-pumpfun.js';+import { log } from './log.js';+import { screenPush } from './screen-push.js';+import { cachedStrategies } from './strategy-store.js';++const POLL_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes++function num(name, def) {+ const raw = process.env[name];+ if (raw == null || raw === '') return def;+ const n = Number(raw);+ return Number.isFinite(n) ? n : def;+}++// Floor + target + caps (SOL). Conservative defaults: keep ~0.05 SOL of dry+// powder per agent, refill when it falls under 0.02, never move more than 0.1 in+// one top-up or 1.0 total per UTC day across all agents.+const MIN_SOL = Math.max(0, num('SNIPER_AUTO_FUND_MIN_SOL', 0.02));+const TARGET_SOL = Math.max(MIN_SOL, num('SNIPER_AUTO_FUND_TARGET_SOL', 0.05));+const PER_TX_CAP_SOL = Math.max(0, num('SNIPER_AUTO_FUND_PER_TX_SOL', 0.1));+const DAILY_CAP_SOL = Math.max(0, num('SNIPER_AUTO_FUND_DAILY_SOL', 1.0));++/** Unique agent ids across the armed strategy set for this network. */+function activeAgentIds(network) {+ const ids = new Set();+ for (const s of cachedStrategies()) {+ if (s.agent_id && s.network === network) ids.add(s.agent_id);+ }+ return [...ids];+}++/** SOL actually moved (live) since the start of the UTC day — the daily-cap base. */+async function dailyFundedSol(network) {+ const [row] = await sql`+ SELECT coalesce(sum(lamports), 0)::float8 / 1e9 AS sol+ FROM sniper_funding_events+ WHERE network = ${network}+ AND mode = 'live'+ AND created_at >= date_trunc('day', now())+ `;+ return Number(row?.sol || 0);+}++/** Resolve each armed agent's Solana address from its identity meta. */+async function agentAddresses(agentIds) {+ if (!agentIds.length) return new Map();+ const rows = await sql`+ SELECT id, meta->>'solana_address' AS address+ FROM agent_identities+ WHERE id = ANY(${agentIds}) AND deleted_at IS NULL+ `;+ const m = new Map();+ for (const r of rows) {+ if (r.address) m.set(r.id, r.address);+ }+ return m;+}++async function tick(cfg) {+ const agentIds = activeAgentIds(cfg.network);+ if (!agentIds.length) return;++ const addresses = await agentAddresses(agentIds);+ if (!addresses.size) return;++ // One daily-spend read per tick; decremented locally as we fund so several+ // agents in the same tick can't collectively blow past the cap.+ let dailyRemaining = DAILY_CAP_SOL > 0 ? Math.max(0, DAILY_CAP_SOL - (await dailyFundedSol(cfg.network))) : Infinity;+ const conn = solanaConnection(cfg.network);++ for (const [agentId, address] of addresses) {+ if (DAILY_CAP_SOL > 0 && dailyRemaining <= 0) {+ log.warn('auto-fund daily cap reached — skipping remaining agents', { network: cfg.network, dailyCapSol: DAILY_CAP_SOL });+ break;+ }++ let balanceSol;+ try {+ ({ sol: balanceSol } = await getSolBalance(conn, address));+ } catch (err) {+ log.warn('auto-fund balance read failed', { agentId, err: err?.message });+ continue;+ }++ if (balanceSol >= MIN_SOL) continue; // healthy — nothing to do++ // Top up to the target, bounded by the per-transfer cap.+ let topUp = TARGET_SOL - balanceSol;+ if (PER_TX_CAP_SOL > 0) topUp = Math.min(topUp, PER_TX_CAP_SOL);+ if (DAILY_CAP_SOL > 0) topUp = Math.min(topUp, dailyRemaining);+ topUp = Math.round(topUp * 1e9) / 1e9; // lamport precision+ if (topUp <= 0) continue;++ log.info('auto-fund low wallet', { agentId, wallet: address, balance_sol: balanceSol, min_sol: MIN_SOL, top_up_sol: topUp });+ screenPush(`Topping up sniper wallet ${address.slice(0, 4)}… +${topUp.toFixed(3)} SOL`, 'activity');++ if (cfg.mode !== 'live') {+ await recordFunding({ agentId, wallet: address, network: cfg.network, sol: topUp, balanceBeforeSol: balanceSol, signature: 'SIMULATED', mode: 'simulate' });+ log.info('simulate — would top up wallet', { agentId, wallet: address, top_up_sol: topUp });+ if (DAILY_CAP_SOL > 0) dailyRemaining -= topUp;+ continue;+ }++ let result;+ try {+ result = await fundAgentForLaunch({+ agentAddress: address,+ sol: topUp,+ perLaunchCapSol: PER_TX_CAP_SOL,+ dailyCapSol: DAILY_CAP_SOL > 0 ? dailyRemaining : null,+ network: cfg.network,+ memo: 'three.ws sniper top-up',+ });+ } catch (err) {+ log.error('auto-fund transfer threw', { agentId, wallet: address, err: err?.message });+ continue;+ }++ if (!result?.ok) {+ log.warn('auto-fund refused', { agentId, wallet: address, reason: result?.reason });+ continue;+ }++ await recordFunding({+ agentId, wallet: address, network: cfg.network, sol: topUp,+ balanceBeforeSol: balanceSol, signature: result.signature, mode: 'live',+ });+ if (DAILY_CAP_SOL > 0) dailyRemaining -= topUp;++ log.trade('wallet-funded', { agentId, wallet: address, top_up_sol: topUp, balance_before_sol: balanceSol, sig: result.signature });+ screenPush(`Funded ${address.slice(0, 4)}… +${topUp.toFixed(3)} SOL`, 'trade');+ }+}++async function recordFunding({ agentId, wallet, network, sol, balanceBeforeSol, signature, mode }) {+ try {+ const lamports = String(Math.round(sol * 1e9));+ const beforeLamports = balanceBeforeSol == null ? null : String(Math.round(balanceBeforeSol * 1e9));+ await sql`+ INSERT INTO sniper_funding_events (agent_id, wallet, network, lamports, balance_before_lamports, signature, mode)+ VALUES (${agentId}, ${wallet}, ${network}, ${lamports}, ${beforeLamports}, ${signature}, ${mode})+ `;+ } catch (err) {+ // A ledger write failure must not double-fund: in live mode treat it as a+ // hard error the caller should see, but never throw out of the tick.+ log.error('auto-fund ledger write failed', { agentId, wallet, sig: signature, err: err?.message });+ }+}++/**+ * Start the auto-funding watch loop.+ *+ * @param {{ cfg: object, signal?: AbortSignal }} options+ * @returns {Function} stop+ */+export function startAutoFunderWatch({ cfg, signal } = {}) {+ let running = false;++ const runTick = () => {+ if (running) return;+ running = true;+ tick(cfg)+ .catch((err) => log.error('auto-funder tick crashed', { err: err?.message }))+ .finally(() => { running = false; });+ };++ const interval = setInterval(runTick, POLL_INTERVAL_MS);+ if (interval.unref) interval.unref();++ log.info('auto-funder armed', {+ network: cfg.network, mode: cfg.mode, pollMs: POLL_INTERVAL_MS,+ minSol: MIN_SOL, targetSol: TARGET_SOL, perTxCapSol: PER_TX_CAP_SOL, dailyCapSol: DAILY_CAP_SOL,+ });++ // Warn loudly if live funding is armed but the master wallet is unconfigured —+ // otherwise every top-up silently refuses and wallets drain anyway.+ if (cfg.mode === 'live') {+ masterBalanceSol(cfg.network)+ .then((bal) => {+ if (bal == null) log.warn('auto-funder: master launch wallet not configured — top-ups will be refused');+ else log.info('auto-funder master balance', { master_sol: bal });+ })+ .catch((err) => log.warn('auto-funder master balance check failed', { err: err?.message }));+ }++ runTick(); // fire immediately so a freshly-armed agent isn't unfunded for 5 min++ function stop() {+ clearInterval(interval);+ log.info('auto-funder stopped');+ }++ if (signal) signal.addEventListener('abort', stop, { once: true });+ return stop;+}diff --git a/workers/agent-sniper/config.js b/workers/agent-sniper/config.jsindex 716f3d498..9def80523 100644--- a/workers/agent-sniper/config.js+++ b/workers/agent-sniper/config.js@@ -133,6 +133,12 @@ export function loadConfig() {launcher: bool('SNIPER_LAUNCHER', !!process.env.AGENT_JWT),// How often to check for due launcher configs (ms).launcherPollMs: Math.max(30_000, num('SNIPER_LAUNCHER_POLL_MS', 60_000)),+ // ── buy-side auto-funding ───────────────────────────────────────────────+ // Keeps each armed agent's own wallet topped up from the launcher master so+ // a hot sniper never silently runs dry and starts failing every buy. On by+ // default; disable with SNIPER_AUTO_FUND=0. Per-transfer / daily caps and+ // the floor/target are read in auto-funder.js (SNIPER_AUTO_FUND_*).+ autoFund: bool('SNIPER_AUTO_FUND', true),// ── creator auto-claim ──────────────────────────────────────────────────// Polls claimable creator fees on agent-launched coins and auto-claims them.// On by default when AGENT_JWT is set; disable with SNIPER_AUTO_CLAIM=0.diff --git a/workers/agent-sniper/index.js b/workers/agent-sniper/index.jsindex 8d402a950..8cb29047f 100644--- a/workers/agent-sniper/index.js+++ b/workers/agent-sniper/index.js@@ -34,6 +34,7 @@ import {import { screenPush } from './screen-push.js';import { scoreAlpha } from './alpha-hunt.js';import { startAutoClaimerWatch } from './auto-claimer.js';+import { startAutoFunderWatch } from './auto-funder.js';import { startLauncherWatch } from './launcher.js';import { startMarketMakerWatch } from './market-maker.js';diff --git a/xactions/scripts/add-license-notices.mjs b/xactions/scripts/add-license-notices.mjsdeleted file mode 100644index 96e6d4368..000000000--- a/xactions/scripts/add-license-notices.mjs+++ /dev/null@@ -1,134 +0,0 @@-// Copyright (c) 2024-2026 nich (@nichxbt). Business Source License 1.1.-import { readFileSync, writeFileSync, readdirSync, statSync } from 'fs';-import { join, resolve } from 'path';--const ROOT = resolve('/workspaces/XActions');--const MIT = '// Copyright (c) 2024-2026 nich (@nichxbt). MIT License.';-const BSL = '// Copyright (c) 2024-2026 nich (@nichxbt). Business Source License 1.1.';--function addNotice(filePath, notice) {- let content;- try {- content = readFileSync(filePath, 'utf8');- } catch {- return;- }-- // Skip if already has a copyright notice- const firstFiveLines = content.split('\n').slice(0, 5).join('\n');- if (firstFiveLines.includes('Copyright')) return;-- // If first line is a shebang, insert after it- const lines = content.split('\n');- if (lines[0].startsWith('#!')) {- lines.splice(1, 0, notice);- } else {- lines.unshift(notice);- }-- writeFileSync(filePath, lines.join('\n'));-}--function walkDir(dir, ext, excludes = []) {- const results = [];- let entries;- try {- entries = readdirSync(dir);- } catch {- return results;- }- for (const entry of entries) {- const full = join(dir, entry);- if (excludes.some(ex => full.includes(ex))) continue;- let stat;- try { stat = statSync(full); } catch { continue; }- if (stat.isDirectory()) {- results.push(...walkDir(full, ext, excludes));- } else if (full.endsWith(ext)) {- results.push(full);- }- }- return results;-}--const EXCLUDES = ['node_modules', 'xspace-agents', 'python', '.git'];--let total = 0, added = 0;--// src/*.js (top-level only) → MIT-const srcTopLevel = readdirSync(join(ROOT, 'src'))- .filter(f => f.endsWith('.js'))- .map(f => join(ROOT, 'src', f))- .filter(f => statSync(f).isFile());--for (const file of srcTopLevel) {- const before = readFileSync(file, 'utf8').split('\n').slice(0, 5).join('\n');- addNotice(file, MIT);- const after = readFileSync(file, 'utf8').split('\n').slice(0, 5).join('\n');- total++;- if (before !== after) added++;-}-console.log(`src/*.js: ${srcTopLevel.length} files (MIT)`);--// archive/*.js → MIT-const archiveFiles = walkDir(join(ROOT, 'archive'), '.js', EXCLUDES);-for (const file of archiveFiles) {- const before = readFileSync(file, 'utf8').split('\n').slice(0, 5).join('\n');- addNotice(file, MIT);- const after = readFileSync(file, 'utf8').split('\n').slice(0, 5).join('\n');- total++;- if (before !== after) added++;-}-console.log(`archive/*.js: ${archiveFiles.length} files (MIT)`);--// src subdirectories → BSL-const srcSubdirs = readdirSync(join(ROOT, 'src'))- .filter(f => statSync(join(ROOT, 'src', f)).isDirectory())- .flatMap(d => walkDir(join(ROOT, 'src', d), '.js', EXCLUDES));--for (const file of srcSubdirs) {- const before = readFileSync(file, 'utf8').split('\n').slice(0, 5).join('\n');- addNotice(file, BSL);- const after = readFileSync(file, 'utf8').split('\n').slice(0, 5).join('\n');- total++;- if (before !== after) added++;-}-console.log(`src subdirs: ${srcSubdirs.length} files (BSL)`);--// Other directories → BSL-const bslDirs = ['api', 'tests', 'scripts', 'packages', 'integrations'];-for (const dir of bslDirs) {- const files = walkDir(join(ROOT, dir), '.js', EXCLUDES);- for (const file of files) {- // skip this script itself- if (file.endsWith('add-license-notices.mjs')) continue;- const before = readFileSync(file, 'utf8').split('\n').slice(0, 5).join('\n');- addNotice(file, BSL);- const after = readFileSync(file, 'utf8').split('\n').slice(0, 5).join('\n');- total++;- if (before !== after) added++;- }- console.log(`${dir}/: ${files.length} files (BSL)`);-}--// bin/unfollowx (shell script) → BSL as a shell comment-const binFile = join(ROOT, 'bin', 'unfollowx');-try {- const content = readFileSync(binFile, 'utf8');- if (!content.split('\n').slice(0, 5).join('\n').includes('Copyright')) {- const lines = content.split('\n');- const shellNotice = '# Copyright (c) 2024-2026 nich (@nichxbt). Business Source License 1.1.';- if (lines[0].startsWith('#!')) {- lines.splice(1, 0, shellNotice);- } else {- lines.unshift(shellNotice);- }- writeFileSync(binFile, lines.join('\n'));- added++;- }- total++;- console.log('bin/unfollowx: 1 file (BSL shell comment)');-} catch {}--console.log(`\nDone. Added notices to ${added} / ${total} files.`);diff --git a/xactions/scripts/build-all-docs.js b/xactions/scripts/build-all-docs.jsdeleted file mode 100644index e07c92947..000000000--- a/xactions/scripts/build-all-docs.js+++ /dev/null@@ -1,659 +0,0 @@-#!/usr/bin/env node-// Copyright (c) 2024-2026 nich (@nichxbt). Business Source License 1.1.-/**- * Build ALL SEO-Optimized HTML Pages from every .md file in the project- * Scans: docs/, skills/, tutorials/claude-prompts/, root docs, plugins, extension- * Outputs to: dashboard/docs/ with sub-paths matching source structure- * Does NOT overwrite existing dashboard/docs/*.html from Phase 2- * by nichxbt- */--import { marked } from 'marked';-import fs from 'fs';-import path from 'path';-import { fileURLToPath } from 'url';--const __filename = fileURLToPath(import.meta.url);-const __dirname = path.dirname(__filename);-const ROOT = path.join(__dirname, '..');-const OUT_BASE = path.join(ROOT, 'dashboard', 'docs');-const SITE_URL = 'https://xactions.app';--// ─── Source Definitions ─────────────────────────────────────────────-// Each source: { dir, glob/files, outSubdir, sectionName, sectionIcon }-const SOURCES = [- // docs/ top-level reference docs- {- dir: 'docs',- files: [- 'getting-started.md', 'usage.md', 'automation.md', 'monitoring.md',- 'cli-reference.md', 'ai-api.md', 'api-reference.md', 'deployment.md',- 'dom-selectors.md', 'mcp-setup.md', 'openrouter.md', 'xactions-reference.md',- 'analytics.md', 'FEATURE_INVENTORY.md', 'GROWTH_STRATEGY.md'- ],- outSubdir: 'guides',- section: 'Guides & Reference',- icon: '📖',- priority: 0.7- },- // docs/agents/ — developer patterns- {- dir: 'docs/agents',- files: ['browser-script-patterns.md', 'contributing-features.md', 'selectors.md'],- outSubdir: 'guides/developer',- section: 'Developer Guides',- icon: '🛠️',- priority: 0.6- },- // docs/research/- {- dir: 'docs/research',- files: ['algorithm-cultivation.md', 'llm-powered-thought-leader.md'],- outSubdir: 'research',- section: 'Research & Architecture',- icon: '🔬',- priority: 0.6- },- // docs/case-studies/- {- dir: 'docs/case-studies',- files: ['robust-dom-extraction.md'],- outSubdir: 'case-studies',- section: 'Case Studies',- icon: '📋',- priority: 0.6- },- // skills/ — each SKILL.md- {- dir: 'skills',- scanPattern: '**/SKILL.md',- outSubdir: 'skills',- section: 'Agent Skills',- icon: '🎯',- priority: 0.7- },- // skills/ — reference sub-docs- {- dir: 'skills',- scanPattern: '**/references/*.md',- outSubdir: 'skills',- section: 'Skill References',- icon: '📚',- priority: 0.5- },- // tutorials/claude-prompts/- {- dir: 'tutorials/claude-prompts',- scanPattern: '*.md',- outSubdir: 'tutorials',- section: 'Claude Tutorials',- icon: '🤖',- priority: 0.7- },- // Root documentation files- {- dir: '.',- files: [- 'CONTRIBUTING.md', 'CHANGELOG.md', 'ROADMAP.md',- 'SECURITY.md', 'CODE_OF_CONDUCT.md', 'README.md'- ],- outSubdir: 'project',- section: 'Project Info',- icon: '📄',- priority: 0.5- },- // Plugin & extension READMEs- {- dir: '.',- files: [- 'extension/README.md',- 'integrations/n8n/README.md',- 'src/plugins/excel/README.md',- 'src/plugins/google-sheets/README.md',- 'src/plugins/template/README.md',- 'examples/README.md',- 'scripts/README.md'- ],- outSubdir: 'extras',- section: 'Extensions & Plugins',- icon: '🔌',- priority: 0.5- },- // docs/launch/ — release announcements- {- dir: 'docs/launch',- scanPattern: '*.md',- outSubdir: 'launch',- section: 'Launch & Releases',- icon: '🚀',- priority: 0.5- }-];--// Files/dirs to SKIP (internal, agent-only, not SEO-worthy)-const SKIP_PATHS = new Set([- 'docs/prompt', // Internal prompt engineering- 'docs/pr-reviews', // Internal PR reviews- '.claude-plugin', // Agent config- '.github', // GitHub templates- 'archive', // Archived code- 'seo-prompts', // SEO prompts we created- 'docs/examples', // Already converted in Phase 2-]);-const SKIP_FILES = new Set([- 'AGENTS.md', 'CLAUDE.md', 'GEMINI.md', 'AUDIT_REPORT.md',- 'AGENT_PROMPTS.md', 'llms.txt', 'llms-full.txt'-]);--// ─── Helpers ────────────────────────────────────────────────────────--function escapeHtml(str) {- return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');-}--function slugify(str) {- return str.toLowerCase()- .replace(/[^\w\s-]/g, '')- .replace(/\s+/g, '-')- .replace(/-+/g, '-')- .replace(/^-|-$/g, '');-}--function extractTitle(markdown) {- // Strip YAML frontmatter first- const cleaned = markdown.replace(/^---[\s\S]*?---\n*/m, '');- const match = cleaned.match(/^#\s+(.+)$/m);- if (match) return match[1].replace(/[🧠🔍❤️🎬📋👋🧹🔔📊🚫🎯🔑🚀🌊📝🧵🖼️🔗📈⚙️🔌📚📂🗑️💔⏰✉️📬📡🤖🔊🔇⚠️🔒💾📥👤✏️👥📱🏘️🚪🎙️⭐📰💼💰💬🔁🗺️]/g, '').trim();- return null;-}--function extractDescription(markdown) {- const cleaned = markdown.replace(/^---[\s\S]*?---\n*/m, '');- const lines = cleaned.split('\n');- for (let i = 0; i < Math.min(lines.length, 20); i++) {- const line = lines[i].trim();- if (line.startsWith('> ')) return line.slice(2).replace(/\*\*/g, '').trim();- if (line && !line.startsWith('#') && !line.startsWith('*') && !line.startsWith('-') && !line.startsWith('---') && !line.startsWith('|') && !line.startsWith('```') && line.length > 30) {- return line.replace(/\*\*/g, '').replace(/\[([^\]]+)\]\([^)]+\)/g, '$1').trim();- }- }- return null;-}--function extractFrontmatterField(markdown, field) {- const fmMatch = markdown.match(/^---\n([\s\S]*?)\n---/);- if (!fmMatch) return null;- const fm = fmMatch[1];- const fieldMatch = fm.match(new RegExp(`^${field}:\\s*(.+)$`, 'm'));- return fieldMatch ? fieldMatch[1].replace(/^["']|["']$/g, '').trim() : null;-}--function buildKeywords(slug, title, section) {- const base = ['xactions', 'twitter automation', 'x automation', 'free', 'open source'];- const fromSlug = slug.split('-').filter(w => w.length > 2);- const fromTitle = title.toLowerCase().split(/\s+/).filter(w => w.length > 3 && !['with', 'from', 'your', 'this', 'that', 'what', 'does', 'will', 'been'].includes(w));- const keywords = [...new Set([...base, ...fromSlug, ...fromTitle, section.toLowerCase()])];- return keywords.slice(0, 15).join(', ');-}--// ─── HTML Template ──────────────────────────────────────────────────--function generateHTML({ slug, title, description, keywords, section, icon, urlPath, htmlContent, breadcrumbs, relatedLinks, priority }) {- const pageTitle = `${title} | XActions`;- const canonicalUrl = `${SITE_URL}${urlPath}`;- const seoDescription = (description || `${title} — Free X/Twitter automation documentation by XActions.`).slice(0, 160);-- return `<!DOCTYPE html>-<html lang="en">-<head>- <meta charset="UTF-8">- <meta name="viewport" content="width=device-width, initial-scale=1.0">- <title>${escapeHtml(pageTitle)}</title>- <meta name="description" content="${escapeHtml(seoDescription)}">- <meta name="keywords" content="${escapeHtml(keywords)}">- <meta name="author" content="nich (@nichxbt)">- <meta name="robots" content="index, follow">-- <meta property="og:type" content="article">- <meta property="og:title" content="${escapeHtml(title)} — XActions">- <meta property="og:description" content="${escapeHtml(seoDescription)}">- <meta property="og:url" content="${canonicalUrl}">- <meta property="og:site_name" content="XActions">-- <meta name="twitter:card" content="summary_large_image">- <meta name="twitter:site" content="@nichxbt">- <meta name="twitter:title" content="${escapeHtml(title)} — XActions">- <meta name="twitter:description" content="${escapeHtml(seoDescription)}">-- <link rel="canonical" href="${canonicalUrl}">- <link rel="manifest" href="/manifest.json">- <link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>⚡</text></svg>">-- <script type="application/ld+json">- {- "@context": "https://schema.org",- "@type": "TechArticle",- "headline": ${JSON.stringify(pageTitle)},- "description": ${JSON.stringify(seoDescription)},- "url": "${canonicalUrl}",- "author": { "@type": "Person", "name": "nich", "url": "https://x.com/nichxbt" },- "publisher": { "@type": "Organization", "name": "XActions", "url": "${SITE_URL}" },- "datePublished": "2026-02-25",- "dateModified": "2026-02-25",- "mainEntityOfPage": "${canonicalUrl}",- "articleSection": ${JSON.stringify(section)},- "keywords": ${JSON.stringify(keywords)}- }- </script>- <script type="application/ld+json">- {- "@context": "https://schema.org",- "@type": "BreadcrumbList",- "itemListElement": [- ${breadcrumbs.map((b, i) => `{ "@type": "ListItem", "position": ${i + 1}, "name": ${JSON.stringify(b.name)}, "item": "${b.url}" }`).join(',\n ')}- ]- }- </script>-- <style>- :root {- --bg-primary: #000000;- --bg-secondary: #16181c;- --bg-tertiary: #202327;- --accent: #1d9bf0;- --accent-hover: #1a8cd8;- --accent-light: rgba(29, 155, 240, 0.1);- --text-primary: #e7e9ea;- --text-secondary: #71767b;- --border: #2f3336;- --success: #00ba7c;- --warning: #ffad1f;- --error: #f4212e;- --purple: #a855f7;- }- * { margin: 0; padding: 0; box-sizing: border-box; }- body {- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;- background: var(--bg-primary);- color: var(--text-primary);- line-height: 1.6;- min-height: 100vh;- }- .layout { display: flex; max-width: 1300px; margin: 0 auto; min-height: 100vh; }- .sidebar { width: 275px; padding: 0 12px; position: sticky; top: 0; height: 100vh; display: flex; flex-direction: column; border-right: 1px solid var(--border); }- .logo { padding: 12px; }- .logo a { display: flex; align-items: center; gap: 8px; text-decoration: none; color: var(--text-primary); font-size: 1.5rem; font-weight: 800; padding: 12px; border-radius: 9999px; transition: background .2s; }- .logo a:hover { background: var(--accent-light); }- nav { flex: 1; }- .nav-item { display: flex; align-items: center; gap: 20px; padding: 12px; border-radius: 9999px; font-size: 1.25rem; color: var(--text-primary); text-decoration: none; transition: background .2s; margin-bottom: 4px; }- .nav-item:hover { background: var(--bg-tertiary); }- .nav-item.active { font-weight: 700; }- .nav-icon { font-size: 1.5rem; width: 28px; text-align: center; }- .action-btn { width: 90%; padding: 16px; background: var(--accent); color: #fff; border: none; border-radius: 9999px; font-size: 1.0625rem; font-weight: 700; cursor: pointer; transition: background .2s; margin: 16px 0; text-decoration: none; display: block; text-align: center; }- .action-btn:hover { background: var(--accent-hover); }- .main-content { flex: 1; max-width: 800px; border-right: 1px solid var(--border); }- .main-header { position: sticky; top: 0; background: rgba(0,0,0,.65); backdrop-filter: blur(12px); border-bottom: 1px solid var(--border); padding: 16px 20px; z-index: 100; }- .main-header h1 { font-size: 1.25rem; font-weight: 700; }- .breadcrumb { font-size: 0.8125rem; color: var(--text-secondary); margin-top: 4px; }- .breadcrumb a { color: var(--accent); text-decoration: none; }- .breadcrumb a:hover { text-decoration: underline; }- .article { padding: 24px 20px; }- .article h1 { font-size: 1.75rem; font-weight: 800; margin-bottom: 8px; line-height: 1.2; }- .article h2 { font-size: 1.375rem; font-weight: 700; margin: 32px 0 12px; padding-top: 16px; border-top: 1px solid var(--border); }- .article h3 { font-size: 1.125rem; font-weight: 600; margin: 24px 0 8px; color: var(--accent); }- .article h4 { font-size: 1rem; font-weight: 600; margin: 16px 0 8px; }- .article p { color: var(--text-secondary); font-size: 0.9375rem; margin-bottom: 16px; }- .article ul, .article ol { margin-left: 24px; margin-bottom: 16px; }- .article li { color: var(--text-secondary); font-size: 0.9375rem; margin-bottom: 6px; }- .article a { color: var(--accent); text-decoration: none; }- .article a:hover { text-decoration: underline; }- .article strong { color: var(--text-primary); }- .article blockquote { border-left: 3px solid var(--accent); padding: 12px 16px; margin: 16px 0; background: var(--bg-secondary); border-radius: 0 8px 8px 0; }- .article blockquote p { margin: 0; color: var(--text-secondary); font-style: italic; }- .article code { background: var(--bg-tertiary); padding: 2px 6px; border-radius: 4px; font-family: 'Monaco','Menlo','Consolas', monospace; font-size: 0.875rem; color: var(--accent); }- .article pre { background: var(--bg-secondary); border: 1px solid var(--border); border-radius: 12px; padding: 16px; overflow-x: auto; margin: 16px 0; }- .article pre code { background: none; padding: 0; color: var(--text-primary); font-size: 0.8125rem; display: block; }- .article table { width: 100%; border-collapse: collapse; margin: 16px 0; font-size: 0.875rem; }- .article th { background: var(--bg-secondary); padding: 10px 12px; text-align: left; border: 1px solid var(--border); font-weight: 600; }- .article td { padding: 10px 12px; border: 1px solid var(--border); color: var(--text-secondary); }- .article hr { border: none; border-top: 1px solid var(--border); margin: 24px 0; }- .article img { max-width: 100%; border-radius: 12px; }- .cat-badge { display: inline-block; background: var(--accent-light); color: var(--accent); padding: 4px 12px; border-radius: 9999px; font-size: 0.75rem; font-weight: 600; margin-bottom: 16px; }- .cta-box { background: linear-gradient(135deg, var(--bg-secondary), var(--bg-tertiary)); border: 1px solid var(--border); border-radius: 16px; padding: 24px; margin: 32px 0; text-align: center; }- .cta-box h3 { font-size: 1.25rem; margin-bottom: 8px; color: var(--text-primary); }- .cta-box p { color: var(--text-secondary); margin-bottom: 16px; }- .cta-box a { display: inline-block; padding: 12px 24px; background: var(--accent); color: #fff; border-radius: 9999px; text-decoration: none; font-weight: 700; transition: background .2s; }- .cta-box a:hover { background: var(--accent-hover); }- .sidebar-right { width: 350px; padding: 16px 24px; position: sticky; top: 0; height: 100vh; overflow-y: auto; }- .sidebar-card { background: var(--bg-secondary); border-radius: 16px; padding: 16px; margin-bottom: 16px; }- .sidebar-card h3 { font-size: 1rem; font-weight: 700; margin-bottom: 12px; }- .sidebar-card a { display: block; color: var(--text-secondary); text-decoration: none; font-size: 0.875rem; padding: 6px 0; border-bottom: 1px solid var(--border); transition: color .2s; }- .sidebar-card a:last-child { border-bottom: none; }- .sidebar-card a:hover { color: var(--accent); }- .site-footer { border-top: 1px solid var(--border); padding: 32px 24px; }- .footer-content { max-width: 1200px; margin: 0 auto; display: grid; grid-template-columns: 2fr 1fr 1fr 1fr; gap: 24px; }- .footer-section h4 { font-size: 0.875rem; font-weight: 700; margin-bottom: 8px; }- .footer-section p, .footer-section a { color: var(--text-secondary); font-size: 0.8125rem; text-decoration: none; display: block; padding: 3px 0; }- .footer-section a:hover { color: var(--accent); }- .footer-bottom { max-width: 1200px; margin: 16px auto 0; padding-top: 16px; border-top: 1px solid var(--border); text-align: center; color: var(--text-secondary); font-size: 0.75rem; }- @media (max-width: 1024px) { .sidebar-right { display: none; } }- @media (max-width: 768px) {- .layout { flex-direction: column; }- .sidebar { display: none; }- .main-content { max-width: 100%; border-right: none; }- .article pre { font-size: 0.75rem; }- .footer-content { grid-template-columns: 1fr 1fr; }- }- </style>-</head>-<body>- <div class="layout">- <aside class="sidebar">- <div class="logo"><a href="/">⚡ XActions</a></div>- <nav>- <a href="/features" class="nav-item"><span class="nav-icon">⚡</span><span>All Scripts</span></a>- <a href="/tutorials" class="nav-item"><span class="nav-icon">📚</span><span>Tutorials</span></a>- <a href="/docs" class="nav-item active"><span class="nav-icon">📖</span><span>Documentation</span></a>- <a href="/ai" class="nav-item"><span class="nav-icon">🤖</span><span>AI/MCP</span></a>- <a href="/pricing" class="nav-item"><span class="nav-icon">💰</span><span>Pricing</span></a>- <a href="/about" class="nav-item"><span class="nav-icon">ℹ️</span><span>About</span></a>- <a href="https://github.com/nirholas/XActions" class="nav-item" target="_blank" rel="noopener"><span class="nav-icon">⭐</span><span>GitHub</span></a>- </nav>- <a href="/dashboard" class="action-btn">Open Dashboard</a>- </aside>-- <main class="main-content">- <header class="main-header">- <h1>${icon} ${escapeHtml(title)}</h1>- <div class="breadcrumb">- ${breadcrumbs.map((b, i) => i < breadcrumbs.length - 1 ? `<a href="${b.url}">${escapeHtml(b.name)}</a> ›` : escapeHtml(b.name)).join(' ')}- </div>- </header>-- <article class="article">- <span class="cat-badge">${escapeHtml(section)}</span>- ${htmlContent}-- <div class="cta-box">- <h3>⚡ Explore XActions</h3>- <p>100% free and open-source. No API keys, no fees, no signup.</p>- <a href="/docs">Browse All Documentation</a>- </div>- </article>- </main>-- <aside class="sidebar-right">- <div class="sidebar-card">- <h3>📖 In This Section</h3>- ${relatedLinks}- </div>- <div class="sidebar-card">- <h3>🔗 Quick Links</h3>- <a href="/docs">All Documentation</a>- <a href="/features">All 43+ Features</a>- <a href="/tutorials">Tutorials</a>- <a href="/ai">AI Integration</a>- <a href="/mcp">MCP Server</a>- <a href="https://github.com/nirholas/XActions" rel="noopener">GitHub</a>- </div>- </aside>- </div>-- <footer class="site-footer">- <div class="footer-content">- <div class="footer-section">- <h4>XActions</h4>- <p>100% Free & Open Source X/Twitter Automation</p>- <p>Created by <a href="https://x.com/nichxbt" rel="noopener">@nichxbt</a></p>- </div>- <div class="footer-section">- <h4>Product</h4>- <a href="/features">Features</a>- <a href="/pricing">Pricing</a>- <a href="/run">Run Scripts</a>- <a href="/dashboard">Dashboard</a>- <a href="/analytics">Analytics</a>- </div>- <div class="footer-section">- <h4>AI & Developers</h4>- <a href="/ai">AI Integration</a>- <a href="/ai-api">AI API (x402)</a>- <a href="/mcp">MCP Server</a>- <a href="/docs">Documentation</a>- <a href="/tutorials">Tutorials</a>- </div>- <div class="footer-section">- <h4>Community</h4>- <a href="https://github.com/nirholas/XActions" rel="noopener">GitHub</a>- <a href="/about">About</a>- <a href="/terms">Terms</a>- <a href="/privacy">Privacy</a>- </div>- </div>- <div class="footer-bottom">- <p>© 2024-2026 XActions. MIT License. No API fees. No limits.</p>- </div>- </footer>-</body>-</html>`;-}--// ─── File Scanner ───────────────────────────────────────────────────--function scanFiles(source) {- const results = [];- const baseDir = path.join(ROOT, source.dir);-- if (source.files) {- // Explicit file list- for (const f of source.files) {- const fullPath = path.join(ROOT, source.dir, f);- if (fs.existsSync(fullPath)) {- results.push({ fullPath, relPath: f });- }- }- } else if (source.scanPattern) {- // Scan directory with pattern- const pattern = source.scanPattern;- if (pattern === '*.md') {- // Flat directory scan- if (fs.existsSync(baseDir)) {- const files = fs.readdirSync(baseDir).filter(f => f.endsWith('.md'));- for (const f of files) {- results.push({ fullPath: path.join(baseDir, f), relPath: f });- }- }- } else if (pattern === '**/SKILL.md') {- // Recursive scan for SKILL.md- if (fs.existsSync(baseDir)) {- const dirs = fs.readdirSync(baseDir, { withFileTypes: true }).filter(d => d.isDirectory());- for (const d of dirs) {- const skillPath = path.join(baseDir, d.name, 'SKILL.md');- if (fs.existsSync(skillPath)) {- results.push({ fullPath: skillPath, relPath: `${d.name}/SKILL.md` });- }- }- }- } else if (pattern === '**/references/*.md') {- // Recursive scan for references/*.md- if (fs.existsSync(baseDir)) {- const dirs = fs.readdirSync(baseDir, { withFileTypes: true }).filter(d => d.isDirectory());- for (const d of dirs) {- const refDir = path.join(baseDir, d.name, 'references');- if (fs.existsSync(refDir)) {- const refs = fs.readdirSync(refDir).filter(f => f.endsWith('.md'));- for (const r of refs) {- results.push({ fullPath: path.join(refDir, r), relPath: `${d.name}/references/${r}` });- }- }- }- }- }- }- return results;-}--// ─── Slug Builder ───────────────────────────────────────────────────--function buildSlug(source, relPath) {- // For skills/SKILL.md → use parent dir name- if (relPath.endsWith('/SKILL.md')) {- return relPath.replace('/SKILL.md', '');- }- // For skills/X/references/Y.md → use X-Y- if (relPath.includes('/references/')) {- const parts = relPath.split('/');- return `${parts[0]}-${parts[2].replace('.md', '')}`;- }- // For root README.md → special handling- const filename = path.basename(relPath, '.md');- if (filename === 'README') {- // Use parent directory name- const dir = path.dirname(relPath);- if (dir === '.') return 'readme';- return slugify(dir.replace(/\//g, '-'));- }- return slugify(filename);-}--// ─── Main Build ─────────────────────────────────────────────────────--async function build() {- console.log('🔨 Building ALL .md → HTML pages...\n');-- marked.setOptions({ breaks: true, gfm: true });-- // Track all generated pages for sitemap and index- const allPages = [];- // Track pages by section for related links- const sectionPages = {};- let totalCount = 0;-- for (const source of SOURCES) {- const files = scanFiles(source);- if (files.length === 0) continue;-- const outDir = path.join(OUT_BASE, source.outSubdir);- if (!fs.existsSync(outDir)) fs.mkdirSync(outDir, { recursive: true });-- console.log(`\n📂 ${source.section} (${source.dir}) — ${files.length} files`);-- if (!sectionPages[source.section]) sectionPages[source.section] = [];-- for (const { fullPath, relPath } of files) {- const slug = buildSlug(source, relPath);- const markdown = fs.readFileSync(fullPath, 'utf-8');- const cleanedMarkdown = markdown.replace(/^---[\s\S]*?---\n*/m, ''); // Strip frontmatter-- const rawTitle = extractTitle(markdown) || extractFrontmatterField(markdown, 'name') || slugify(slug).replace(/-/g, ' ').replace(/\b\w/g, c => c.toUpperCase());- const title = rawTitle;- const description = extractDescription(markdown) || extractFrontmatterField(markdown, 'description');- const keywords = buildKeywords(slug, title, source.section);- const urlPath = `/docs/${source.outSubdir}/${slug}`;-- const breadcrumbs = [- { name: 'Home', url: SITE_URL },- { name: 'Docs', url: `${SITE_URL}/docs` },- { name: source.section, url: `${SITE_URL}/docs/${source.outSubdir}` },- { name: rawTitle, url: `${SITE_URL}${urlPath}` }- ];-- const htmlContent = marked.parse(cleanedMarkdown);-- const pageInfo = {- slug,- title: rawTitle,- description: description || `${rawTitle} — XActions documentation`,- section: source.section,- icon: source.icon,- urlPath,- outSubdir: source.outSubdir,- priority: source.priority,- outFile: path.join(outDir, `${slug}.html`)- };-- sectionPages[source.section].push(pageInfo);- allPages.push(pageInfo);- }- }-- // Now generate allHTML with proper related links- for (const page of allPages) {- const source = SOURCES.find(s => s.section === page.section);- const fullPath = findSourceFile(source, page.slug);- if (!fullPath) continue;-- const markdown = fs.readFileSync(fullPath, 'utf-8');- const cleanedMarkdown = markdown.replace(/^---[\s\S]*?---\n*/m, '');- const htmlContent = marked.parse(cleanedMarkdown);-- // Build related links from same section- const siblings = sectionPages[page.section] || [];- const relatedLinks = siblings- .filter(s => s.slug !== page.slug)- .slice(0, 8)- .map(s => ` <a href="${s.urlPath}">${s.icon} ${escapeHtml(s.title)}</a>`)- .join('\n');-- const breadcrumbs = [- { name: 'Home', url: SITE_URL },- { name: 'Docs', url: `${SITE_URL}/docs` },- { name: page.section, url: `${SITE_URL}/docs/${page.outSubdir}` },- { name: page.title, url: `${SITE_URL}${page.urlPath}` }- ];-- const html = generateHTML({- ...page,- htmlContent,- breadcrumbs,- relatedLinks: relatedLinks || '<a href="/docs">Browse all docs</a>',- keywords: buildKeywords(page.slug, page.title, page.section)- });-- fs.writeFileSync(page.outFile, html);- totalCount++;- console.log(` ✅ ${page.outSubdir}/${page.slug}.html`);- }-- // Generate sitemap entries- const sitemapXml = allPages.map(p => ` <url>- <loc>${SITE_URL}${p.urlPath}</loc>- <lastmod>2026-02-25</lastmod>- <changefreq>monthly</changefreq>- <priority>${p.priority}</priority>- </url>`).join('\n');-- fs.writeFileSync(path.join(OUT_BASE, '_sitemap-all-entries.xml'), sitemapXml);-- // Generate a manifest of all pages for the index- const manifest = allPages.map(p => ({- slug: p.slug,- title: p.title,- description: p.description,- section: p.section,- icon: p.icon,- urlPath: p.urlPath,- outSubdir: p.outSubdir,- priority: p.priority- }));- fs.writeFileSync(path.join(OUT_BASE, '_pages-manifest.json'), JSON.stringify(manifest, null, 2));-- console.log(`\n✅ Generated ${totalCount} new HTML pages`);- console.log(`📋 Sitemap entries → dashboard/docs/_sitemap-all-entries.xml`);- console.log(`📋 Pages manifest → dashboard/docs/_pages-manifest.json`);- // Count Phase 2 pages dynamically- const phase2Count = fs.readdirSync(OUT_BASE).filter(f => f.endsWith('.html') && !f.startsWith('_')).length;- console.log(`\nTotal indexable doc pages: ${totalCount} (Phase 3) + ${phase2Count} (Phase 2) = ${totalCount + phase2Count}`);-}--// Helper to find source file from page info-function findSourceFile(source, slug) {- const files = scanFiles(source);- for (const { fullPath, relPath } of files) {- const builtSlug = buildSlug(source, relPath);- if (builtSlug === slug) return fullPath;- }- return null;-}--build().catch(console.error);diff --git a/xactions/scripts/build-docs-pages.js b/xactions/scripts/build-docs-pages.jsdeleted file mode 100644index df047a6cf..000000000--- a/xactions/scripts/build-docs-pages.js+++ /dev/null@@ -1,672 +0,0 @@-#!/usr/bin/env node-// Copyright (c) 2024-2026 nich (@nichxbt). Business Source License 1.1.-/**- * Build SEO-Optimized HTML Pages from docs/examples/*.md- * Generates dashboard/docs/<slug>.html for each markdown file- * by nichxbt- */--import { marked } from 'marked';-import fs from 'fs';-import path from 'path';-import { fileURLToPath } from 'url';--const __filename = fileURLToPath(import.meta.url);-const __dirname = path.dirname(__filename);-const ROOT = path.join(__dirname, '..');--const DOCS_DIR = path.join(ROOT, 'docs', 'examples');-const OUT_DIR = path.join(ROOT, 'dashboard', 'docs');-const SITE_URL = 'https://xactions.app';--// Category mappings for structured data and navigation-const CATEGORIES = {- 'unfollow-everyone': { cat: 'Unfollow Tools', icon: '👋', priority: 0.8 },- 'unfollow-non-followers': { cat: 'Unfollow Tools', icon: '🧹', priority: 0.8 },- 'smart-unfollow': { cat: 'Unfollow Tools', icon: '🧠', priority: 0.8 },- 'detect-unfollowers': { cat: 'Follower Monitoring', icon: '🔍', priority: 0.8 },- 'new-follower-alerts': { cat: 'Follower Monitoring', icon: '🔔', priority: 0.7 },- 'audit-followers': { cat: 'Follower Monitoring', icon: '📊', priority: 0.7 },- 'remove-followers': { cat: 'Follower Monitoring', icon: '🚫', priority: 0.7 },- 'auto-liker': { cat: 'Engagement', icon: '❤️', priority: 0.7 },- 'auto-commenter': { cat: 'Engagement', icon: '💬', priority: 0.7 },- 'auto-repost': { cat: 'Engagement', icon: '🔁', priority: 0.7 },- 'follow-engagers': { cat: 'Growth', icon: '🎯', priority: 0.7 },- 'follow-target-followers': { cat: 'Growth', icon: '🎯', priority: 0.7 },- 'keyword-follow': { cat: 'Growth', icon: '🔑', priority: 0.7 },- 'growth-suite': { cat: 'Growth', icon: '🚀', priority: 0.8 },- 'natural-flow': { cat: 'Growth', icon: '🌊', priority: 0.7 },- 'followers-scraping': { cat: 'Scrapers', icon: '📋', priority: 0.7 },- 'following-scraping': { cat: 'Scrapers', icon: '📋', priority: 0.7 },- 'likes-scraping': { cat: 'Scrapers', icon: '❤️', priority: 0.7 },- 'profile-scraping': { cat: 'Scrapers', icon: '👤', priority: 0.7 },- 'hashtag-scraping': { cat: 'Scrapers', icon: '#️⃣', priority: 0.7 },- 'search-tweets': { cat: 'Scrapers', icon: '🔍', priority: 0.7 },- 'tweet-scraping': { cat: 'Scrapers', icon: '🐦', priority: 0.7 },- 'thread-scraping': { cat: 'Scrapers', icon: '🧵', priority: 0.7 },- 'list-scraping': { cat: 'Scrapers', icon: '📝', priority: 0.7 },- 'media-scraping': { cat: 'Scrapers', icon: '🖼️', priority: 0.7 },- 'link-scraper': { cat: 'Scrapers', icon: '🔗', priority: 0.7 },- 'viral-tweet-scraper': { cat: 'Scrapers', icon: '📈', priority: 0.7 },- 'robust-user-extraction': { cat: 'Scrapers', icon: '⚙️', priority: 0.6 },- 'scraper-adapters': { cat: 'Scrapers', icon: '🔌', priority: 0.6 },- 'video-downloader': { cat: 'Content Tools', icon: '🎬', priority: 0.8 },- 'thread-unroller': { cat: 'Content Tools', icon: '🧵', priority: 0.7 },- 'bookmark-exporter': { cat: 'Content Tools', icon: '📚', priority: 0.7 },- 'bookmark-organizer': { cat: 'Content Tools', icon: '📂', priority: 0.7 },- 'clear-all-bookmarks': { cat: 'Content Tools', icon: '🗑️', priority: 0.6 },- 'clear-all-reposts': { cat: 'Content Tools', icon: '🗑️', priority: 0.6 },- 'unlike-all-posts': { cat: 'Content Tools', icon: '💔', priority: 0.6 },- 'post-thread': { cat: 'Posting', icon: '🧵', priority: 0.7 },- 'schedule-posts': { cat: 'Posting', icon: '⏰', priority: 0.7 },- 'create-poll': { cat: 'Posting', icon: '📊', priority: 0.6 },- 'dm-automation': { cat: 'Messaging', icon: '✉️', priority: 0.7 },- 'send-direct-message': { cat: 'Messaging', icon: '📬', priority: 0.6 },- 'monitor-account': { cat: 'Analytics', icon: '📊', priority: 0.7 },- 'engagement-analytics': { cat: 'Analytics', icon: '📈', priority: 0.7 },- 'hashtag-analytics': { cat: 'Analytics', icon: '#️⃣', priority: 0.7 },- 'best-time-to-post': { cat: 'Analytics', icon: '⏰', priority: 0.7 },- 'competitor-analysis': { cat: 'Analytics', icon: '🔍', priority: 0.7 },- 'streaming': { cat: 'Analytics', icon: '📡', priority: 0.6 },- 'block-bots': { cat: 'Safety & Privacy', icon: '🤖', priority: 0.7 },- 'mass-block-unblock': { cat: 'Safety & Privacy', icon: '🚫', priority: 0.7 },- 'mass-unmute': { cat: 'Safety & Privacy', icon: '🔊', priority: 0.6 },- 'mute-keywords-words': { cat: 'Safety & Privacy', icon: '🔇', priority: 0.6 },- 'report-spam': { cat: 'Safety & Privacy', icon: '⚠️', priority: 0.6 },- 'settings-privacy': { cat: 'Safety & Privacy', icon: '🔒', priority: 0.6 },- 'backup-account': { cat: 'Account Management', icon: '💾', priority: 0.7 },- 'download-account-data': { cat: 'Account Management', icon: '📥', priority: 0.7 },- 'profile-management': { cat: 'Account Management', icon: '👤', priority: 0.6 },- 'update-profile': { cat: 'Account Management', icon: '✏️', priority: 0.6 },- 'multi-account': { cat: 'Account Management', icon: '👥', priority: 0.6 },- 'qr-code-sharing': { cat: 'Account Management', icon: '📱', priority: 0.5 },- 'list-manager': { cat: 'Lists & Communities', icon: '📝', priority: 0.6 },- 'join-communities': { cat: 'Lists & Communities', icon: '🏘️', priority: 0.6 },- 'leave-all-communities': { cat: 'Lists & Communities', icon: '🚪', priority: 0.6 },- 'mcp-server': { cat: 'AI & Developer', icon: '🤖', priority: 0.8 },- 'grok-ai': { cat: 'AI & Developer', icon: '🧠', priority: 0.7 },- 'scrape-spaces': { cat: 'Spaces & Live', icon: '🎙️', priority: 0.6 },- 'spaces-live-audio': { cat: 'Spaces & Live', icon: '🎙️', priority: 0.6 },- 'premium-features': { cat: 'Premium', icon: '⭐', priority: 0.5 },- 'articles-longform': { cat: 'Premium', icon: '📰', priority: 0.5 },- 'business-ads': { cat: 'Business', icon: '💼', priority: 0.5 },- 'creator-monetization': { cat: 'Business', icon: '💰', priority: 0.5 },- 'discovery-explore': { cat: 'Discovery', icon: '🔍', priority: 0.5 },- // ── New: src/ scripts ──- 'account-health-monitor': { cat: 'Analytics', icon: '🏥', priority: 0.7 },- 'algorithm-builder': { cat: 'Growth', icon: '🧠', priority: 0.8 },- 'article-publisher': { cat: 'Posting', icon: '📰', priority: 0.6 },- 'audience-demographics': { cat: 'Analytics', icon: '📊', priority: 0.7 },- 'audience-overlap': { cat: 'Analytics', icon: '🔗', priority: 0.7 },- 'auto-plug-replies': { cat: 'Engagement', icon: '🔌', priority: 0.7 },- 'auto-reply': { cat: 'Engagement', icon: '💬', priority: 0.7 },- 'bookmark-manager': { cat: 'Content Tools', icon: '📚', priority: 0.7 },- 'bulk-delete-tweets': { cat: 'Content Tools', icon: '🗑️', priority: 0.7 },- 'business-tools': { cat: 'Business', icon: '💼', priority: 0.6 },- 'content-calendar': { cat: 'Posting', icon: '📅', priority: 0.7 },- 'content-repurposer': { cat: 'Posting', icon: '♻️', priority: 0.7 },- 'continuous-monitor': { cat: 'Follower Monitoring', icon: '🔄', priority: 0.7 },- 'creator-studio': { cat: 'Business', icon: '🎨', priority: 0.6 },- 'dm-manager': { cat: 'Messaging', icon: '✉️', priority: 0.7 },- 'engagement-booster': { cat: 'Engagement', icon: '🚀', priority: 0.7 },- 'engagement-leaderboard': { cat: 'Analytics', icon: '🏆', priority: 0.7 },- 'engagement-manager': { cat: 'Engagement', icon: '⚡', priority: 0.7 },- 'follow-ratio-manager': { cat: 'Growth', icon: '⚖️', priority: 0.7 },- 'follower-growth-tracker': { cat: 'Analytics', icon: '📈', priority: 0.7 },- 'grok-integration': { cat: 'AI & Developer', icon: '🧠', priority: 0.7 },- 'keyword-monitor': { cat: 'Analytics', icon: '🔑', priority: 0.7 },- 'manage-muted-words': { cat: 'Safety & Privacy', icon: '🔇', priority: 0.6 },- 'mass-block': { cat: 'Safety & Privacy', icon: '🚫', priority: 0.7 },- 'mass-unblock': { cat: 'Safety & Privacy', icon: '🔓', priority: 0.6 },- 'mute-by-keywords': { cat: 'Safety & Privacy', icon: '🔕', priority: 0.6 },- 'notification-manager': { cat: 'Analytics', icon: '🔔', priority: 0.6 },- 'persona-engine': { cat: 'Growth', icon: '🎭', priority: 0.7 },- 'pin-tweet-manager': { cat: 'Posting', icon: '📌', priority: 0.6 },- 'poll-creator': { cat: 'Posting', icon: '📊', priority: 0.6 },- 'post-composer': { cat: 'Posting', icon: '✏️', priority: 0.7 },- 'premium-manager': { cat: 'Premium', icon: '⭐', priority: 0.5 },- 'profile-manager': { cat: 'Account Management', icon: '👤', priority: 0.6 },- 'quote-tweet-automation': { cat: 'Engagement', icon: '🔁', priority: 0.7 },- 'sentiment-analyzer': { cat: 'Analytics', icon: '🧠', priority: 0.7 },- 'settings-manager': { cat: 'Account Management', icon: '⚙️', priority: 0.6 },- 'shadowban-checker': { cat: 'Analytics', icon: '👻', priority: 0.7 },- 'spaces-manager': { cat: 'Spaces & Live', icon: '🎙️', priority: 0.6 },- 'thread-composer': { cat: 'Posting', icon: '🧵', priority: 0.7 },- 'trending-topic-monitor': { cat: 'Analytics', icon: '📈', priority: 0.7 },- 'tweet-ab-tester': { cat: 'Analytics', icon: '🧪', priority: 0.7 },- 'tweet-performance': { cat: 'Analytics', icon: '📊', priority: 0.7 },- 'tweet-schedule-optimizer': { cat: 'Analytics', icon: '⏰', priority: 0.7 },- 'unfollow-wdfb-log': { cat: 'Unfollow Tools', icon: '📋', priority: 0.7 },- 'viral-tweet-detector': { cat: 'Analytics', icon: '🔥', priority: 0.7 },- 'welcome-new-followers': { cat: 'Engagement', icon: '👋', priority: 0.7 },- // ── New: scripts/-only ──- 'scrape-profile-with-replies': { cat: 'Scrapers', icon: '👤', priority: 0.7 },- 'scrape-analytics': { cat: 'Scrapers', icon: '📊', priority: 0.7 },- 'scrape-bookmarks': { cat: 'Scrapers', icon: '🔖', priority: 0.7 },- 'scrape-cashtag-search': { cat: 'Scrapers', icon: '💲', priority: 0.7 },- 'scrape-dms': { cat: 'Scrapers', icon: '✉️', priority: 0.7 },- 'scrape-explore': { cat: 'Scrapers', icon: '🔍', priority: 0.7 },- 'scrape-followers': { cat: 'Scrapers', icon: '👥', priority: 0.7 },- 'scrape-following': { cat: 'Scrapers', icon: '👥', priority: 0.7 },- 'scrape-hashtag': { cat: 'Scrapers', icon: '#️⃣', priority: 0.7 },- 'scrape-likers': { cat: 'Scrapers', icon: '❤️', priority: 0.7 },- 'scrape-likes': { cat: 'Scrapers', icon: '❤️', priority: 0.7 },- 'scrape-list': { cat: 'Scrapers', icon: '📝', priority: 0.7 },- 'scrape-media': { cat: 'Scrapers', icon: '🖼️', priority: 0.7 },- 'scrape-notifications': { cat: 'Scrapers', icon: '🔔', priority: 0.7 },- 'scrape-profile': { cat: 'Scrapers', icon: '👤', priority: 0.7 },- 'scrape-quote-retweets': { cat: 'Scrapers', icon: '🔁', priority: 0.7 },- 'scrape-replies': { cat: 'Scrapers', icon: '💬', priority: 0.7 },- 'scrape-search': { cat: 'Scrapers', icon: '🔍', priority: 0.7 },- 'export-to-csv': { cat: 'Content Tools', icon: '📄', priority: 0.6 },- 'dm-exporter': { cat: 'Messaging', icon: '📤', priority: 0.6 },- 'manage-bookmarks': { cat: 'Content Tools', icon: '📑', priority: 0.6 },- 'manage-lists': { cat: 'Lists & Communities', icon: '📝', priority: 0.6 },- 'manage-notifications': { cat: 'Analytics', icon: '🔔', priority: 0.6 },- 'manage-settings': { cat: 'Account Management', icon: '⚙️', priority: 0.6 },- 'publish-article': { cat: 'Posting', icon: '📰', priority: 0.5 },- 'edit-profile': { cat: 'Account Management', icon: '✏️', priority: 0.6 },- 'business-analytics': { cat: 'Business', icon: '💼', priority: 0.6 },- 'keyword-liker': { cat: 'Engagement', icon: '❤️', priority: 0.7 },- 'multi-account-timeline-liker': { cat: 'Engagement', icon: '❤️', priority: 0.6 },- 'tweet-price-correlation': { cat: 'Analytics', icon: '💹', priority: 0.6 },- 'thought-leader-cultivator': { cat: 'Growth', icon: '🧠', priority: 0.7 },- 'viral-tweets-scraper': { cat: 'Scrapers', icon: '🔥', priority: 0.7 },- 'auto-engage': { cat: 'Engagement', icon: '⚡', priority: 0.7 },-};--function slugToTitle(slug) {- return slug.replace(/-/g, ' ').replace(/\b\w/g, c => c.toUpperCase());-}--function extractTitle(markdown) {- const match = markdown.match(/^#\s+(.+)$/m);- if (match) return match[1].replace(/[🧠🔍❤️🎬📋👋🧹🔔📊🚫🎯🔑🚀🌊📝🧵🖼️🔗📈⚙️🔌📚📂🗑️💔⏰✉️📬📡🤖🚫🔊🔇⚠️🔒💾📥👤✏️👥📱📝🏘️🚪🎙️⭐📰💼💰🔍💬🔁📊]/g, '').trim();- return null;-}--function extractDescription(markdown) {- // Try to find a blockquote or first paragraph after title- const lines = markdown.split('\n');- for (let i = 0; i < Math.min(lines.length, 15); i++) {- const line = lines[i].trim();- if (line.startsWith('> ')) return line.slice(2).trim();- if (line && !line.startsWith('#') && !line.startsWith('*') && !line.startsWith('-') && !line.startsWith('---') && line.length > 20) {- return line.replace(/\*\*/g, '').replace(/\[([^\]]+)\]\([^)]+\)/g, '$1').trim();- }- }- return null;-}--function buildKeywords(slug, title, category) {- const base = ['xactions', 'twitter automation', 'x automation', 'free'];- const fromSlug = slug.split('-').filter(w => w.length > 2);- const fromTitle = title.toLowerCase().split(/\s+/).filter(w => w.length > 3 && !['with', 'from', 'your', 'this', 'that', 'what'].includes(w));- const keywords = [...new Set([...base, ...fromSlug, ...fromTitle, category.toLowerCase(), `${slug.replace(/-/g, ' ')} twitter`, `twitter ${slug.replace(/-/g, ' ')}`])];- return keywords.slice(0, 15).join(', ');-}--function generateHTML(slug, markdown) {- const info = CATEGORIES[slug] || { cat: 'Tools', icon: '⚡', priority: 0.6 };- const rawTitle = extractTitle(markdown) || slugToTitle(slug);- const title = rawTitle.replace(/^X\/Twitter\s*/i, '').trim();- const description = extractDescription(markdown) || `${title} — Free X/Twitter automation tool. No API keys, no fees. Open-source browser script by XActions.`;- const keywords = buildKeywords(slug, title, info.cat);- const pageTitle = `${title} — Free X/Twitter ${info.cat} Tool | XActions`;- const canonicalUrl = `${SITE_URL}/docs/${slug}`;- const seoDescription = description.length > 160 ? description.slice(0, 157) + '...' : description;-- // Configure marked- marked.setOptions({- breaks: true,- gfm: true,- });- const htmlContent = marked.parse(markdown);-- return `<!DOCTYPE html>-<html lang="en">-<head>- <meta charset="UTF-8">- <meta name="viewport" content="width=device-width, initial-scale=1.0">- <title>${escapeHtml(pageTitle)}</title>- <meta name="description" content="${escapeHtml(seoDescription)}">- <meta name="keywords" content="${escapeHtml(keywords)}">- <meta name="author" content="nich (@nichxbt)">- <meta name="robots" content="index, follow">-- <!-- Open Graph -->- <meta property="og:type" content="article">- <meta property="og:title" content="${escapeHtml(title)} — XActions">- <meta property="og:description" content="${escapeHtml(seoDescription)}">- <meta property="og:url" content="${canonicalUrl}">- <meta property="og:site_name" content="XActions">-- <!-- Twitter Card -->- <meta name="twitter:card" content="summary_large_image">- <meta name="twitter:site" content="@nichxbt">- <meta name="twitter:title" content="${escapeHtml(title)} — Free X/Twitter Tool">- <meta name="twitter:description" content="${escapeHtml(seoDescription)}">-- <link rel="canonical" href="${canonicalUrl}">- <link rel="manifest" href="/manifest.json">- <link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>⚡</text></svg>">-- <!-- Structured Data - TechArticle -->- <script type="application/ld+json">- {- "@context": "https://schema.org",- "@type": "TechArticle",- "headline": ${JSON.stringify(pageTitle)},- "description": ${JSON.stringify(seoDescription)},- "url": "${canonicalUrl}",- "author": { "@type": "Person", "name": "nich", "url": "https://x.com/nichxbt" },- "publisher": { "@type": "Organization", "name": "XActions", "url": "${SITE_URL}" },- "datePublished": "2026-02-24",- "dateModified": "2026-02-24",- "mainEntityOfPage": "${canonicalUrl}",- "articleSection": ${JSON.stringify(info.cat)},- "keywords": ${JSON.stringify(keywords)}- }- </script>- <!-- Structured Data - BreadcrumbList -->- <script type="application/ld+json">- {- "@context": "https://schema.org",- "@type": "BreadcrumbList",- "itemListElement": [- { "@type": "ListItem", "position": 1, "name": "Home", "item": "${SITE_URL}" },- { "@type": "ListItem", "position": 2, "name": "Documentation", "item": "${SITE_URL}/docs" },- { "@type": "ListItem", "position": 3, "name": ${JSON.stringify(rawTitle)}, "item": "${canonicalUrl}" }- ]- }- </script>- <!-- Structured Data - HowTo (for automation guides) -->- <script type="application/ld+json">- {- "@context": "https://schema.org",- "@type": "HowTo",- "name": "How to use ${escapeHtml(title)}",- "description": ${JSON.stringify(seoDescription)},- "step": [- { "@type": "HowToStep", "name": "Open x.com", "text": "Navigate to x.com in your browser and log in to your account." },- { "@type": "HowToStep", "name": "Open DevTools Console", "text": "Press F12 or Ctrl+Shift+J to open the browser developer console." },- { "@type": "HowToStep", "name": "Paste the script", "text": "Copy the XActions ${escapeHtml(title)} script and paste it into the console." },- { "@type": "HowToStep", "name": "Run and monitor", "text": "Press Enter to run. The script shows real-time progress with emoji logs." }- ],- "tool": { "@type": "HowToTool", "name": "XActions" },- "totalTime": "PT2M"- }- </script>-- <style>- :root {- --bg-primary: #000000;- --bg-secondary: #16181c;- --bg-tertiary: #202327;- --accent: #1d9bf0;- --accent-hover: #1a8cd8;- --accent-light: rgba(29, 155, 240, 0.1);- --text-primary: #e7e9ea;- --text-secondary: #71767b;- --border: #2f3336;- --success: #00ba7c;- --warning: #ffad1f;- --error: #f4212e;- --purple: #a855f7;- }- * { margin: 0; padding: 0; box-sizing: border-box; }- body {- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;- background: var(--bg-primary);- color: var(--text-primary);- line-height: 1.6;- min-height: 100vh;- }- /* Layout */- .layout { display: flex; max-width: 1300px; margin: 0 auto; min-height: 100vh; }- .sidebar { width: 275px; padding: 0 12px; position: sticky; top: 0; height: 100vh; display: flex; flex-direction: column; border-right: 1px solid var(--border); }- .logo { padding: 12px; }- .logo a { display: flex; align-items: center; gap: 8px; text-decoration: none; color: var(--text-primary); font-size: 1.5rem; font-weight: 800; padding: 12px; border-radius: 9999px; transition: background .2s; }- .logo a:hover { background: var(--accent-light); }- nav { flex: 1; }- .nav-item { display: flex; align-items: center; gap: 20px; padding: 12px; border-radius: 9999px; font-size: 1.25rem; color: var(--text-primary); text-decoration: none; transition: background .2s; margin-bottom: 4px; }- .nav-item:hover { background: var(--bg-tertiary); }- .nav-item.active { font-weight: 700; }- .nav-icon { font-size: 1.5rem; width: 28px; text-align: center; }- .action-btn { width: 90%; padding: 16px; background: var(--accent); color: #fff; border: none; border-radius: 9999px; font-size: 1.0625rem; font-weight: 700; cursor: pointer; transition: background .2s; margin: 16px 0; text-decoration: none; display: block; text-align: center; }- .action-btn:hover { background: var(--accent-hover); }- /* Main */- .main-content { flex: 1; max-width: 800px; border-right: 1px solid var(--border); }- .main-header { position: sticky; top: 0; background: rgba(0,0,0,.65); backdrop-filter: blur(12px); border-bottom: 1px solid var(--border); padding: 16px 20px; z-index: 100; }- .main-header h1 { font-size: 1.25rem; font-weight: 700; }- .breadcrumb { font-size: 0.8125rem; color: var(--text-secondary); margin-top: 4px; }- .breadcrumb a { color: var(--accent); text-decoration: none; }- .breadcrumb a:hover { text-decoration: underline; }- /* Article */- .article { padding: 24px 20px; }- .article h1 { font-size: 1.75rem; font-weight: 800; margin-bottom: 8px; line-height: 1.2; }- .article h2 { font-size: 1.375rem; font-weight: 700; margin: 32px 0 12px; padding-top: 16px; border-top: 1px solid var(--border); }- .article h3 { font-size: 1.125rem; font-weight: 600; margin: 24px 0 8px; color: var(--accent); }- .article h4 { font-size: 1rem; font-weight: 600; margin: 16px 0 8px; }- .article p { color: var(--text-secondary); font-size: 0.9375rem; margin-bottom: 16px; }- .article ul, .article ol { margin-left: 24px; margin-bottom: 16px; }- .article li { color: var(--text-secondary); font-size: 0.9375rem; margin-bottom: 6px; }- .article a { color: var(--accent); text-decoration: none; }- .article a:hover { text-decoration: underline; }- .article strong { color: var(--text-primary); }- .article blockquote { border-left: 3px solid var(--accent); padding: 12px 16px; margin: 16px 0; background: var(--bg-secondary); border-radius: 0 8px 8px 0; }- .article blockquote p { margin: 0; color: var(--text-secondary); font-style: italic; }- .article code { background: var(--bg-tertiary); padding: 2px 6px; border-radius: 4px; font-family: 'Monaco', 'Menlo', 'Consolas', monospace; font-size: 0.875rem; color: var(--accent); }- .article pre { background: var(--bg-secondary); border: 1px solid var(--border); border-radius: 12px; padding: 16px; overflow-x: auto; margin: 16px 0; position: relative; }- .article pre code { background: none; padding: 0; color: var(--text-primary); font-size: 0.8125rem; display: block; }- .article table { width: 100%; border-collapse: collapse; margin: 16px 0; font-size: 0.875rem; }- .article th { background: var(--bg-secondary); padding: 10px 12px; text-align: left; border: 1px solid var(--border); font-weight: 600; }- .article td { padding: 10px 12px; border: 1px solid var(--border); color: var(--text-secondary); }- .article hr { border: none; border-top: 1px solid var(--border); margin: 24px 0; }- .article img { max-width: 100%; border-radius: 12px; }- /* Category badge */- .cat-badge { display: inline-block; background: var(--accent-light); color: var(--accent); padding: 4px 12px; border-radius: 9999px; font-size: 0.75rem; font-weight: 600; margin-bottom: 16px; }- /* CTA */- .cta-box { background: linear-gradient(135deg, var(--bg-secondary), var(--bg-tertiary)); border: 1px solid var(--border); border-radius: 16px; padding: 24px; margin: 32px 0; text-align: center; }- .cta-box h3 { font-size: 1.25rem; margin-bottom: 8px; color: var(--text-primary); }- .cta-box p { color: var(--text-secondary); margin-bottom: 16px; }- .cta-box a { display: inline-block; padding: 12px 24px; background: var(--accent); color: #fff; border-radius: 9999px; text-decoration: none; font-weight: 700; transition: background .2s; }- .cta-box a:hover { background: var(--accent-hover); }- /* Sidebar Right */- .sidebar-right { width: 350px; padding: 16px 24px; position: sticky; top: 0; height: 100vh; overflow-y: auto; }- .sidebar-card { background: var(--bg-secondary); border-radius: 16px; padding: 16px; margin-bottom: 16px; }- .sidebar-card h3 { font-size: 1rem; font-weight: 700; margin-bottom: 12px; }- .sidebar-card a { display: block; color: var(--text-secondary); text-decoration: none; font-size: 0.875rem; padding: 6px 0; border-bottom: 1px solid var(--border); transition: color .2s; }- .sidebar-card a:last-child { border-bottom: none; }- .sidebar-card a:hover { color: var(--accent); }- /* Footer */- .site-footer { border-top: 1px solid var(--border); padding: 32px 24px; }- .footer-content { max-width: 1200px; margin: 0 auto; display: grid; grid-template-columns: 2fr 1fr 1fr 1fr; gap: 24px; }- .footer-section h4 { font-size: 0.875rem; font-weight: 700; margin-bottom: 8px; }- .footer-section p, .footer-section a { color: var(--text-secondary); font-size: 0.8125rem; text-decoration: none; display: block; padding: 3px 0; }- .footer-section a:hover { color: var(--accent); }- .footer-bottom { max-width: 1200px; margin: 16px auto 0; padding-top: 16px; border-top: 1px solid var(--border); text-align: center; color: var(--text-secondary); font-size: 0.75rem; }- /* Responsive */- @media (max-width: 1024px) { .sidebar-right { display: none; } }- @media (max-width: 768px) {- .layout { flex-direction: column; }- .sidebar { display: none; }- .main-content { max-width: 100%; border-right: none; }- .footer-content { grid-template-columns: 1fr 1fr; }- .article pre { font-size: 0.75rem; }- }- </style>-</head>-<body>- <div class="layout">- <!-- Sidebar -->- <aside class="sidebar">- <div class="logo"><a href="/">⚡ XActions</a></div>- <nav>- <a href="/features" class="nav-item"><span class="nav-icon">⚡</span><span>All Scripts</span></a>- <a href="/tutorials" class="nav-item"><span class="nav-icon">📚</span><span>Tutorials</span></a>- <a href="/docs" class="nav-item active"><span class="nav-icon">📖</span><span>Documentation</span></a>- <a href="/ai" class="nav-item"><span class="nav-icon">🤖</span><span>AI/MCP</span></a>- <a href="/pricing" class="nav-item"><span class="nav-icon">💰</span><span>Pricing</span></a>- <a href="/about" class="nav-item"><span class="nav-icon">ℹ️</span><span>About</span></a>- <a href="https://github.com/nirholas/XActions" class="nav-item" target="_blank" rel="noopener"><span class="nav-icon">⭐</span><span>GitHub</span></a>- </nav>- <a href="/dashboard" class="action-btn">Open Dashboard</a>- </aside>-- <!-- Main Content -->- <main class="main-content">- <header class="main-header">- <h1>${info.icon} ${escapeHtml(rawTitle)}</h1>- <div class="breadcrumb">- <a href="/">Home</a> › <a href="/docs">Docs</a> › ${escapeHtml(rawTitle)}- </div>- </header>-- <article class="article">- <span class="cat-badge">${escapeHtml(info.cat)}</span>- ${htmlContent}-- <div class="cta-box">- <h3>⚡ Ready to try ${escapeHtml(title)}?</h3>- <p>XActions is 100% free and open-source. No API keys, no fees, no signup.</p>- <a href="/features">Browse All Scripts</a>- </div>- </article>- </main>-- <!-- Sidebar Right -->- <aside class="sidebar-right">- <div class="sidebar-card">- <h3>📖 Related Docs</h3>- RELATED_LINKS_PLACEHOLDER- </div>- <div class="sidebar-card">- <h3>🔗 Quick Links</h3>- <a href="/features">All 43+ Features</a>- <a href="/tutorials">Tutorials</a>- <a href="/ai">AI Integration</a>- <a href="/mcp">MCP Server</a>- <a href="/docs">Documentation Hub</a>- <a href="https://github.com/nirholas/XActions" rel="noopener">GitHub Repository</a>- </div>- </aside>- </div>-- <!-- Footer -->- <footer class="site-footer">- <div class="footer-content">- <div class="footer-section">- <h4>XActions</h4>- <p>100% Free & Open Source X/Twitter Automation</p>- <p>Created by <a href="https://x.com/nichxbt" rel="noopener">@nichxbt</a></p>- </div>- <div class="footer-section">- <h4>Product</h4>- <a href="/features">Features</a>- <a href="/pricing">Pricing</a>- <a href="/run">Run Scripts</a>- <a href="/dashboard">Dashboard</a>- <a href="/automations">Automations</a>- <a href="/analytics">Analytics</a>- </div>- <div class="footer-section">- <h4>AI & Developers</h4>- <a href="/ai">AI Integration</a>- <a href="/ai-api">AI API (x402)</a>- <a href="/mcp">MCP Server</a>- <a href="/docs">Documentation</a>- <a href="/tutorials">Tutorials</a>- </div>- <div class="footer-section">- <h4>Community</h4>- <a href="https://github.com/nirholas/XActions" rel="noopener">GitHub</a>- <a href="/about">About</a>- <a href="/terms">Terms</a>- <a href="/privacy">Privacy</a>- </div>- </div>- <div class="footer-bottom">- <p>© 2024-2026 XActions. MIT License. No API fees. No limits.</p>- </div>- </footer>-</body>-</html>`;-}--function escapeHtml(str) {- return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');-}--function getRelatedPages(slug, allSlugs) {- const info = CATEGORIES[slug] || { cat: 'Tools' };- const related = allSlugs- .filter(s => s !== slug && CATEGORIES[s]?.cat === info.cat)- .slice(0, 5);- // If fewer than 5, add popular pages- const popular = ['smart-unfollow', 'detect-unfollowers', 'video-downloader', 'followers-scraping', 'auto-liker', 'growth-suite'];- for (const p of popular) {- if (related.length >= 5) break;- if (p !== slug && !related.includes(p) && allSlugs.includes(p)) related.push(p);- }- return related.slice(0, 6);-}--// Tutorials subdirectory category mappings-const TUTORIAL_CATEGORIES = {- 'auto-commenter-tutorial': { cat: 'Step-by-Step Tutorials', icon: '📝', priority: 0.8 },- 'auto-liker-tutorial': { cat: 'Step-by-Step Tutorials', icon: '📝', priority: 0.8 },- 'bookmark-exporter-tutorial': { cat: 'Step-by-Step Tutorials', icon: '📝', priority: 0.7 },- 'detect-unfollowers-tutorial': { cat: 'Step-by-Step Tutorials', icon: '📝', priority: 0.8 },- 'follow-target-followers-tutorial': { cat: 'Step-by-Step Tutorials', icon: '📝', priority: 0.7 },- 'followers-scraping-tutorial': { cat: 'Step-by-Step Tutorials', icon: '📝', priority: 0.8 },- 'following-scraping-tutorial': { cat: 'Step-by-Step Tutorials', icon: '📝', priority: 0.7 },- 'growth-suite-tutorial': { cat: 'Step-by-Step Tutorials', icon: '📝', priority: 0.8 },- 'hashtag-scraping-tutorial': { cat: 'Step-by-Step Tutorials', icon: '📝', priority: 0.7 },- 'keyword-follow-tutorial': { cat: 'Step-by-Step Tutorials', icon: '📝', priority: 0.7 },- 'natural-flow-tutorial': { cat: 'Step-by-Step Tutorials', icon: '📝', priority: 0.7 },- 'profile-scraping-tutorial': { cat: 'Step-by-Step Tutorials', icon: '📝', priority: 0.8 },- 'smart-unfollow-tutorial': { cat: 'Step-by-Step Tutorials', icon: '📝', priority: 0.8 },- 'tweet-scraping-tutorial': { cat: 'Step-by-Step Tutorials', icon: '📝', priority: 0.8 },- 'unfollow-everyone-tutorial': { cat: 'Step-by-Step Tutorials', icon: '📝', priority: 0.8 },- 'unfollow-non-followers-tutorial': { cat: 'Step-by-Step Tutorials', icon: '📝', priority: 0.8 },- 'video-downloader-tutorial': { cat: 'Step-by-Step Tutorials', icon: '📝', priority: 0.8 },-};--function stripFrontmatter(markdown) {- return markdown.replace(/^---[\s\S]*?---\n*/m, '');-}--function extractFrontmatterField(markdown, field) {- const fmMatch = markdown.match(/^---\n([\s\S]*?)\n---/);- if (!fmMatch) return null;- const fm = fmMatch[1];- const fieldMatch = fm.match(new RegExp(`^${field}:\\s*["']?(.+?)["']?\\s*$`, 'm'));- return fieldMatch ? fieldMatch[1].trim() : null;-}--// Main build-async function build() {- console.log('🔨 Building SEO doc pages...\n');-- // Ensure output directories exist- if (!fs.existsSync(OUT_DIR)) fs.mkdirSync(OUT_DIR, { recursive: true });- const tutorialOutDir = path.join(OUT_DIR, 'step-by-step');- if (!fs.existsSync(tutorialOutDir)) fs.mkdirSync(tutorialOutDir, { recursive: true });-- // ─── Phase 2a: Process docs/examples/*.md (flat) ───- const files = fs.readdirSync(DOCS_DIR)- .filter(f => f.endsWith('.md') && f !== 'README.md');-- const allSlugs = files.map(f => f.replace('.md', ''));- const sitemapEntries = [];- let count = 0;-- for (const file of files) {- const slug = file.replace('.md', '');- const mdPath = path.join(DOCS_DIR, file);- const markdown = fs.readFileSync(mdPath, 'utf-8');-- let html = generateHTML(slug, markdown);-- const related = getRelatedPages(slug, allSlugs);- const relatedHtml = related.map(r => {- const rInfo = CATEGORIES[r] || { icon: '📄' };- const rTitle = slugToTitle(r);- return ` <a href="/docs/${r}">${rInfo.icon} ${rTitle}</a>`;- }).join('\n');- html = html.replace('RELATED_LINKS_PLACEHOLDER', relatedHtml);-- const outPath = path.join(OUT_DIR, `${slug}.html`);- fs.writeFileSync(outPath, html);-- const info = CATEGORIES[slug] || { priority: 0.6 };- sitemapEntries.push({ slug, urlPath: `/docs/${slug}`, priority: info.priority });- count++;- console.log(` ✅ ${slug}.html`);- }-- // ─── Phase 2b: Process docs/examples/tutorials/*.md ───- const tutorialDir = path.join(DOCS_DIR, 'tutorials');- if (fs.existsSync(tutorialDir)) {- const tutorialFiles = fs.readdirSync(tutorialDir)- .filter(f => f.endsWith('.md'));-- console.log(`\n📝 Building step-by-step tutorials...\n`);-- for (const file of tutorialFiles) {- const slug = file.replace('.md', '');- const mdPath = path.join(tutorialDir, file);- const rawMarkdown = fs.readFileSync(mdPath, 'utf-8');-- // Extract frontmatter fields if present- const fmTitle = extractFrontmatterField(rawMarkdown, 'title');- const fmDesc = extractFrontmatterField(rawMarkdown, 'description');- const markdown = stripFrontmatter(rawMarkdown);- const info = TUTORIAL_CATEGORIES[slug] || { cat: 'Step-by-Step Tutorials', icon: '📝', priority: 0.7 };-- // Use frontmatter title/desc or fall back to extraction- const rawTitle = fmTitle || extractTitle(markdown) || slugToTitle(slug);- const title = rawTitle.replace(/^X\/Twitter\s*/i, '').trim();- const description = fmDesc || extractDescription(markdown) || `${title} — Step-by-step tutorial for XActions.`;- const keywords = buildKeywords(slug, title, info.cat);- const pageTitle = `${title} | XActions Tutorial`;- const canonicalUrl = `${SITE_URL}/docs/step-by-step/${slug}`;- const seoDescription = description.length > 160 ? description.slice(0, 157) + '...' : description;-- marked.setOptions({ breaks: true, gfm: true });- const htmlContent = marked.parse(markdown);-- // Build the same template but with tutorial-specific paths- let html = generateHTML(slug, markdown);- // Fix canonical URL for tutorial path- html = html.replace(- `<link rel="canonical" href="${SITE_URL}/docs/${slug}">`,- `<link rel="canonical" href="${canonicalUrl}">`- );- html = html.replace(- `<meta property="og:url" content="${SITE_URL}/docs/${slug}">`,- `<meta property="og:url" content="${canonicalUrl}">`- );- html = html.replace(- `"url": "${SITE_URL}/docs/${slug}"`,- `"url": "${canonicalUrl}"`- );- // Fix breadcrumb- html = html.replace(- `<a href="/docs">Documentation</a>`,- `<a href="/docs">Documentation</a> / <a href="/docs#step-by-step">Tutorials</a>`- );-- // Related links — other tutorials- const tutSlugs = tutorialFiles.map(f => f.replace('.md', ''));- const related = tutSlugs.filter(s => s !== slug).slice(0, 5);- const relatedHtml = related.map(r => {- return ` <a href="/docs/step-by-step/${r}">📝 ${slugToTitle(r)}</a>`;- }).join('\n');- html = html.replace('RELATED_LINKS_PLACEHOLDER', relatedHtml);-- const outPath = path.join(tutorialOutDir, `${slug}.html`);- fs.writeFileSync(outPath, html);-- sitemapEntries.push({ slug, urlPath: `/docs/step-by-step/${slug}`, priority: info.priority });- count++;- console.log(` ✅ step-by-step/${slug}.html`);- }- }-- // Generate sitemap entries- const sitemapXml = sitemapEntries.map(e => ` <url>- <loc>https://xactions.app${e.urlPath}</loc>- <lastmod>${new Date().toISOString().split('T')[0]}</lastmod>- <changefreq>monthly</changefreq>- <priority>${e.priority}</priority>- </url>`).join('\n');-- fs.writeFileSync(path.join(OUT_DIR, '_sitemap-entries.xml'), sitemapXml);-- console.log(`\n✅ Generated ${count} HTML pages in dashboard/docs/`);- console.log(`📋 Sitemap entries saved to dashboard/docs/_sitemap-entries.xml`);-}--build().catch(console.error);diff --git a/xactions/scripts/build-script-pages.js b/xactions/scripts/build-script-pages.jsdeleted file mode 100644index a84623e3f..000000000--- a/xactions/scripts/build-script-pages.js+++ /dev/null@@ -1,946 +0,0 @@-#!/usr/bin/env node-// Copyright (c) 2024-2026 nich (@nichxbt). Business Source License 1.1.-/**- * Build Individual HTML Pages for Every Browser Console Script- * Scans: src/*.js, src/automation/*.js, scripts/*.js, scripts/twitter/*.js- * Outputs to: dashboard/scripts/<slug>.html + dashboard/scripts/index.html- * by nichxbt- */--import fs from 'fs';-import path from 'path';-import { fileURLToPath } from 'url';--const __filename = fileURLToPath(import.meta.url);-const __dirname = path.dirname(__filename);-const ROOT = path.join(__dirname, '..');-const OUT_DIR = path.join(ROOT, 'dashboard', 'scripts');-const SITE_URL = 'https://xactions.app';--// ─── Category Mappings ─────────────────────────────────────────────-const CATEGORIES = {- // Unfollow- 'unfollow-everyone': { cat: 'Unfollow Tools', icon: '👋', priority: 0.8 },- 'unfollowback': { cat: 'Unfollow Tools', icon: '🧹', priority: 0.8 },- 'unfollow-non-followers': { cat: 'Unfollow Tools', icon: '🧹', priority: 0.8 },- 'unfollow-wdfb-log': { cat: 'Unfollow Tools', icon: '📋', priority: 0.7 },- 'unfollow-with-log': { cat: 'Unfollow Tools', icon: '📋', priority: 0.7 },- 'smart-unfollow': { cat: 'Unfollow Tools', icon: '🧠', priority: 0.8 },- 'follow-ratio-manager': { cat: 'Unfollow Tools', icon: '⚖️', priority: 0.7 },- // Follower Monitoring- 'detect-unfollowers': { cat: 'Follower Monitoring', icon: '🔍', priority: 0.8 },- 'new-followers-alert': { cat: 'Follower Monitoring', icon: '🔔', priority: 0.7 },- 'audit-followers': { cat: 'Follower Monitoring', icon: '📊', priority: 0.7 },- 'remove-followers': { cat: 'Follower Monitoring', icon: '🚫', priority: 0.7 },- 'continuous-monitor': { cat: 'Follower Monitoring', icon: '🔄', priority: 0.7 },- 'monitor-account': { cat: 'Follower Monitoring', icon: '📊', priority: 0.7 },- 'follower-growth-tracker': { cat: 'Follower Monitoring', icon: '📈', priority: 0.7 },- 'follower-tools': { cat: 'Follower Monitoring', icon: '👥', priority: 0.7 },- 'followers-growth-tracker': { cat: 'Follower Monitoring', icon: '📈', priority: 0.7 },- 'find-fake-followers': { cat: 'Follower Monitoring', icon: '🤖', priority: 0.7 },- 'welcome-new-followers': { cat: 'Follower Monitoring', icon: '👋', priority: 0.7 },- // Engagement- 'auto-liker': { cat: 'Engagement', icon: '❤️', priority: 0.7 },- 'auto-commenter': { cat: 'Engagement', icon: '💬', priority: 0.7 },- 'auto-repost': { cat: 'Engagement', icon: '🔁', priority: 0.7 },- 'auto-reply': { cat: 'Engagement', icon: '💬', priority: 0.7 },- 'auto-plug-replies': { cat: 'Engagement', icon: '🔌', priority: 0.7 },- 'auto-engage': { cat: 'Engagement', icon: '⚡', priority: 0.7 },- 'engagement-booster': { cat: 'Engagement', icon: '🚀', priority: 0.7 },- 'engagement-manager': { cat: 'Engagement', icon: '⚡', priority: 0.7 },- 'engagement-leaderboard': { cat: 'Engagement', icon: '🏆', priority: 0.7 },- 'quote-tweet-automation': { cat: 'Engagement', icon: '🔁', priority: 0.7 },- 'keyword-liker': { cat: 'Engagement', icon: '❤️', priority: 0.7 },- 'multi-account-timeline-liker': { cat: 'Engagement', icon: '❤️', priority: 0.6 },- 'like-post': { cat: 'Engagement', icon: '❤️', priority: 0.6 },- 'repost-post': { cat: 'Engagement', icon: '🔁', priority: 0.6 },- 'post-interactions': { cat: 'Engagement', icon: '💬', priority: 0.6 },- 'like-by-feed': { cat: 'Engagement', icon: '❤️', priority: 0.6 },- 'like-by-hashtag': { cat: 'Engagement', icon: '❤️', priority: 0.6 },- 'like-by-location': { cat: 'Engagement', icon: '❤️', priority: 0.6 },- 'like-by-user': { cat: 'Engagement', icon: '❤️', priority: 0.6 },- 'like-user-replies': { cat: 'Engagement', icon: '❤️', priority: 0.6 },- 'interact-by-hashtag': { cat: 'Engagement', icon: '💬', priority: 0.6 },- 'interact-by-place': { cat: 'Engagement', icon: '💬', priority: 0.6 },- 'interact-by-users': { cat: 'Engagement', icon: '💬', priority: 0.6 },- 'interact-with-likers': { cat: 'Engagement', icon: '💬', priority: 0.6 },- 'comment-by-hashtag': { cat: 'Engagement', icon: '💬', priority: 0.6 },- 'comment-by-location': { cat: 'Engagement', icon: '💬', priority: 0.6 },- 'mention-users': { cat: 'Engagement', icon: '💬', priority: 0.6 },- // Growth- 'follow-engagers': { cat: 'Growth', icon: '🎯', priority: 0.7 },- 'follow-target-users': { cat: 'Growth', icon: '🎯', priority: 0.7 },- 'keyword-follow': { cat: 'Growth', icon: '🔑', priority: 0.7 },- 'growth-suite': { cat: 'Growth', icon: '🚀', priority: 0.8 },- 'natural-flow': { cat: 'Growth', icon: '🌊', priority: 0.7 },- 'algorithm-builder': { cat: 'Growth', icon: '🧠', priority: 0.8 },- 'algorithm-trainer': { cat: 'Growth', icon: '🧠', priority: 0.8 },- 'persona-engine': { cat: 'Growth', icon: '🎭', priority: 0.7 },- 'thought-leader-cultivator': { cat: 'Growth', icon: '🧠', priority: 0.7 },- 'follow-account': { cat: 'Growth', icon: '➕', priority: 0.6 },- 'follow-list': { cat: 'Growth', icon: '📋', priority: 0.6 },- // Scrapers- 'scrape-followers': { cat: 'Scrapers', icon: '👥', priority: 0.7 },- 'scrape-following': { cat: 'Scrapers', icon: '👥', priority: 0.7 },- 'scrape-likes': { cat: 'Scrapers', icon: '❤️', priority: 0.7 },- 'scrape-likers': { cat: 'Scrapers', icon: '❤️', priority: 0.7 },- 'scrape-profile': { cat: 'Scrapers', icon: '👤', priority: 0.7 },- 'scrape-profile-posts': { cat: 'Scrapers', icon: '👤', priority: 0.7 },- 'scrape-profile-with-replies': { cat: 'Scrapers', icon: '👤', priority: 0.7 },- 'scrape-hashtag': { cat: 'Scrapers', icon: '#️⃣', priority: 0.7 },- 'scrape-search': { cat: 'Scrapers', icon: '🔍', priority: 0.7 },- 'scrape-media': { cat: 'Scrapers', icon: '🖼️', priority: 0.7 },- 'scrape-list': { cat: 'Scrapers', icon: '📝', priority: 0.7 },- 'scrape-bookmarks': { cat: 'Scrapers', icon: '🔖', priority: 0.7 },- 'scrape-dms': { cat: 'Scrapers', icon: '✉️', priority: 0.7 },- 'scrape-explore': { cat: 'Scrapers', icon: '🔍', priority: 0.7 },- 'scrape-notifications': { cat: 'Scrapers', icon: '🔔', priority: 0.7 },- 'scrape-quote-retweets': { cat: 'Scrapers', icon: '🔁', priority: 0.7 },- 'scrape-replies': { cat: 'Scrapers', icon: '💬', priority: 0.7 },- 'scrape-spaces': { cat: 'Scrapers', icon: '🎙️', priority: 0.7 },- 'scrape-analytics': { cat: 'Scrapers', icon: '📊', priority: 0.7 },- 'scrape-cashtag-search': { cat: 'Scrapers', icon: '💲', priority: 0.7 },- 'link-scraper': { cat: 'Scrapers', icon: '🔗', priority: 0.7 },- 'viral-tweets-scraper': { cat: 'Scrapers', icon: '🔥', priority: 0.7 },- 'export-to-csv': { cat: 'Scrapers', icon: '📄', priority: 0.6 },- // Content Tools- 'video-downloader': { cat: 'Content Tools', icon: '🎬', priority: 0.8 },- 'thread-unroller': { cat: 'Content Tools', icon: '🧵', priority: 0.7 },- 'bookmark-exporter': { cat: 'Content Tools', icon: '📚', priority: 0.7 },- 'bookmark-organizer': { cat: 'Content Tools', icon: '📂', priority: 0.7 },- 'bookmark-manager': { cat: 'Content Tools', icon: '📚', priority: 0.7 },- 'manage-bookmarks': { cat: 'Content Tools', icon: '📑', priority: 0.6 },- 'clear-all-bookmarks': { cat: 'Content Tools', icon: '🗑️', priority: 0.6 },- 'clear-all-reposts': { cat: 'Content Tools', icon: '🗑️', priority: 0.6 },- 'clear-all-retweets': { cat: 'Content Tools', icon: '🗑️', priority: 0.6 },- 'clear-all-likes': { cat: 'Content Tools', icon: '🗑️', priority: 0.6 },- 'unlike-all-posts': { cat: 'Content Tools', icon: '💔', priority: 0.6 },- 'unlike-all': { cat: 'Content Tools', icon: '💔', priority: 0.6 },- 'unlike-old': { cat: 'Content Tools', icon: '💔', priority: 0.6 },- 'bulk-delete-tweets': { cat: 'Content Tools', icon: '🗑️', priority: 0.7 },- 'content-repurposer': { cat: 'Content Tools', icon: '♻️', priority: 0.7 },- 'text-formatting': { cat: 'Content Tools', icon: '✏️', priority: 0.5 },- 'share-embed': { cat: 'Content Tools', icon: '🔗', priority: 0.5 },- 'video-captions': { cat: 'Content Tools', icon: '📝', priority: 0.6 },- // Posting- 'post-thread': { cat: 'Posting', icon: '🧵', priority: 0.7 },- 'post-composer': { cat: 'Posting', icon: '✏️', priority: 0.7 },- 'post-advanced': { cat: 'Posting', icon: '✏️', priority: 0.7 },- 'schedule-posts': { cat: 'Posting', icon: '⏰', priority: 0.7 },- 'create-poll': { cat: 'Posting', icon: '📊', priority: 0.6 },- 'poll-creator': { cat: 'Posting', icon: '📊', priority: 0.6 },- 'thread-composer': { cat: 'Posting', icon: '🧵', priority: 0.7 },- 'content-calendar': { cat: 'Posting', icon: '📅', priority: 0.7 },- 'pin-tweet-manager': { cat: 'Posting', icon: '📌', priority: 0.6 },- 'publish-article': { cat: 'Posting', icon: '📰', priority: 0.5 },- 'article-publisher': { cat: 'Posting', icon: '📰', priority: 0.6 },- 'edit-post': { cat: 'Posting', icon: '✏️', priority: 0.6 },- 'tweet-ab-tester': { cat: 'Posting', icon: '🧪', priority: 0.7 },- 'evergeen-recycler': { cat: 'Posting', icon: '♻️', priority: 0.6 },- // Messaging- 'send-direct-message': { cat: 'Messaging', icon: '📬', priority: 0.6 },- 'dm-manager': { cat: 'Messaging', icon: '✉️', priority: 0.7 },- 'dm-exporter': { cat: 'Messaging', icon: '📤', priority: 0.6 },- 'dm-calls': { cat: 'Messaging', icon: '📞', priority: 0.6 },- 'group-dm': { cat: 'Messaging', icon: '👥', priority: 0.6 },- 'encrypted-dm': { cat: 'Messaging', icon: '🔒', priority: 0.6 },- // Analytics- 'engagement-analytics': { cat: 'Analytics', icon: '📈', priority: 0.7 },- 'hashtag-analytics': { cat: 'Analytics', icon: '#️⃣', priority: 0.7 },- 'best-time-to-post': { cat: 'Analytics', icon: '⏰', priority: 0.7 },- 'competitor-analysis': { cat: 'Analytics', icon: '🔍', priority: 0.7 },- 'account-health-monitor': { cat: 'Analytics', icon: '🏥', priority: 0.7 },- 'audience-demographics': { cat: 'Analytics', icon: '📊', priority: 0.7 },- 'audience-overlap': { cat: 'Analytics', icon: '🔗', priority: 0.7 },- 'sentiment-analyzer': { cat: 'Analytics', icon: '🧠', priority: 0.7 },- 'shadowban-checker': { cat: 'Analytics', icon: '👻', priority: 0.7 },- 'trending-topic-monitor': { cat: 'Analytics', icon: '📈', priority: 0.7 },- 'tweet-performance': { cat: 'Analytics', icon: '📊', priority: 0.7 },- 'tweet-schedule-optimizer': { cat: 'Analytics', icon: '⏰', priority: 0.7 },- 'viral-tweet-detector': { cat: 'Analytics', icon: '🔥', priority: 0.7 },- 'keyword-monitor': { cat: 'Analytics', icon: '🔑', priority: 0.7 },- 'notification-manager': { cat: 'Analytics', icon: '🔔', priority: 0.6 },- 'manage-notifications': { cat: 'Analytics', icon: '🔔', priority: 0.6 },- 'view-analytics': { cat: 'Analytics', icon: '📊', priority: 0.7 },- 'tweet-price-correlation': { cat: 'Analytics', icon: '💹', priority: 0.6 },- 'profile-stats': { cat: 'Analytics', icon: '📊', priority: 0.6 },- 'timeline-viewer': { cat: 'Analytics', icon: '📊', priority: 0.6 },- // Safety & Privacy- 'block-bots': { cat: 'Safety & Privacy', icon: '🤖', priority: 0.7 },- 'mass-block': { cat: 'Safety & Privacy', icon: '🚫', priority: 0.7 },- 'mass-unblock': { cat: 'Safety & Privacy', icon: '🔓', priority: 0.6 },- 'mass-unmute': { cat: 'Safety & Privacy', icon: '🔊', priority: 0.6 },- 'mute-by-keywords': { cat: 'Safety & Privacy', icon: '🔕', priority: 0.6 },- 'manage-muted-words': { cat: 'Safety & Privacy', icon: '🔇', priority: 0.6 },- 'report-spam': { cat: 'Safety & Privacy', icon: '⚠️', priority: 0.6 },- 'settings-manager': { cat: 'Safety & Privacy', icon: '⚙️', priority: 0.6 },- 'manage-settings': { cat: 'Safety & Privacy', icon: '⚙️', priority: 0.6 },- 'block-by-keywords': { cat: 'Safety & Privacy', icon: '🚫', priority: 0.6 },- 'block-by-ratio': { cat: 'Safety & Privacy', icon: '🚫', priority: 0.6 },- 'blacklist': { cat: 'Safety & Privacy', icon: '🚫', priority: 0.6 },- 'whitelist': { cat: 'Safety & Privacy', icon: '✅', priority: 0.6 },- 'filter-manager': { cat: 'Safety & Privacy', icon: '🔍', priority: 0.6 },- 'verified-only': { cat: 'Safety & Privacy', icon: '✅', priority: 0.5 },- 'id-verification': { cat: 'Safety & Privacy', icon: '🪪', priority: 0.5 },- // Account Management- 'backup-account': { cat: 'Account Management', icon: '💾', priority: 0.7 },- 'download-account-data': { cat: 'Account Management', icon: '📥', priority: 0.7 },- 'profile-manager': { cat: 'Account Management', icon: '👤', priority: 0.6 },- 'update-profile': { cat: 'Account Management', icon: '✏️', priority: 0.6 },- 'edit-profile': { cat: 'Account Management', icon: '✏️', priority: 0.6 },- 'multi-account': { cat: 'Account Management', icon: '👥', priority: 0.6 },- 'qr-code-sharing': { cat: 'Account Management', icon: '📱', priority: 0.5 },- 'delegate-access': { cat: 'Account Management', icon: '🔑', priority: 0.6 },- 'upload-contacts': { cat: 'Account Management', icon: '📇', priority: 0.5 },- 'update-banner': { cat: 'Account Management', icon: '🖼️', priority: 0.5 },- 'update-bio': { cat: 'Account Management', icon: '✏️', priority: 0.5 },- 'update-profile-picture': { cat: 'Account Management', icon: '🖼️', priority: 0.5 },- 'subscribe-premium': { cat: 'Account Management', icon: '⭐', priority: 0.5 },- // Lists & Communities- 'list-manager': { cat: 'Lists & Communities', icon: '📝', priority: 0.6 },- 'advanced-lists': { cat: 'Lists & Communities', icon: '📝', priority: 0.6 },- 'manage-lists': { cat: 'Lists & Communities', icon: '📝', priority: 0.6 },- 'join-communities': { cat: 'Lists & Communities', icon: '🏘️', priority: 0.6 },- 'leave-all-communities': { cat: 'Lists & Communities', icon: '🚪', priority: 0.6 },- 'leave-community': { cat: 'Lists & Communities', icon: '🚪', priority: 0.6 },- 'create-community': { cat: 'Lists & Communities', icon: '🏘️', priority: 0.6 },- 'manage-community': { cat: 'Lists & Communities', icon: '🏘️', priority: 0.6 },- // AI & Developer- 'grok-integration': { cat: 'AI & Developer', icon: '🧠', priority: 0.7 },- // Spaces & Live- 'spaces-manager': { cat: 'Spaces & Live', icon: '🎙️', priority: 0.6 },- 'host-space': { cat: 'Spaces & Live', icon: '🎙️', priority: 0.6 },- 'join-space': { cat: 'Spaces & Live', icon: '🎙️', priority: 0.6 },- // Premium- 'premium-manager': { cat: 'Premium', icon: '⭐', priority: 0.5 },- 'premium-features': { cat: 'Premium', icon: '⭐', priority: 0.5 },- 'premium-gifting': { cat: 'Premium', icon: '🎁', priority: 0.5 },- 'creator-subscriptions': { cat: 'Premium', icon: '💰', priority: 0.5 },- // Business- 'business-tools': { cat: 'Business', icon: '💼', priority: 0.6 },- 'business-analytics': { cat: 'Business', icon: '💼', priority: 0.6 },- 'creator-studio': { cat: 'Business', icon: '🎨', priority: 0.6 },- 'ads-manager': { cat: 'Business', icon: '📢', priority: 0.6 },- 'media-studio': { cat: 'Business', icon: '🖼️', priority: 0.6 },- // Discovery- 'discovery-explore': { cat: 'Discovery', icon: '🔍', priority: 0.5 },- 'topic-manager': { cat: 'Discovery', icon: '🏷️', priority: 0.5 },- 'save-search': { cat: 'Discovery', icon: '🔍', priority: 0.5 },- 'x-pro': { cat: 'Discovery', icon: '⚡', priority: 0.5 },- // Automation- 'control-panel': { cat: 'Automation', icon: '🎛️', priority: 0.7 },- 'actions': { cat: 'Automation', icon: '⚡', priority: 0.7 },- 'core': { cat: 'Automation', icon: '⚙️', priority: 0.8 },- 'session-logger': { cat: 'Automation', icon: '📋', priority: 0.6 },- 'quota-supervisor': { cat: 'Automation', icon: '⚠️', priority: 0.6 },- 'protect-active-users': { cat: 'Automation', icon: '🛡️', priority: 0.6 },- 'rate-limiter': { cat: 'Automation', icon: '⏱️', priority: 0.6 },- 'customer-service': { cat: 'Automation', icon: '🤝', priority: 0.6 },- 'rss-monitor': { cat: 'Automation', icon: '📡', priority: 0.6 },-};--// ─── Script Sources ────────────────────────────────────────────────-const SCRIPT_DIRS = [- { dir: 'src', label: 'Core Library', context: 'browser' },- { dir: 'src/automation', label: 'Automation Suite', context: 'browser', requiresCore: true },- { dir: 'scripts', label: 'Standalone Scripts', context: 'browser' },- { dir: 'scripts/twitter', label: 'Twitter Scripts', context: 'browser' },-];--// Files to skip (not user-facing scripts)-const SKIP_FILES = new Set([- 'index.js', 'build-docs-pages.js', 'build-all-docs.js', 'build-script-pages.js',- 'generate-license.js', 'generate-missing-docs.js', 'test-x402-payment.js',- 'verify-x402.js', 'script-template.js',-]);--const SKIP_DIRS_IN_SRC = new Set([- 'cli', 'mcp', 'scrapers', 'client', 'agents', 'analytics', 'streaming',- 'plugins', 'ai', 'a2a', 'workflows', 'utils', 'automation',-]);--// ─── Helpers ────────────────────────────────────────────────────────--function escapeHtml(str) {- return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');-}--function slugify(filename) {- return filename- .replace(/\.js$/, '')- .replace(/([a-z])([A-Z])/g, '$1-$2') // camelCase → kebab-case- .toLowerCase()- .replace(/[^\w-]/g, '-')- .replace(/-+/g, '-')- .replace(/^-|-$/g, '');-}--function slugToTitle(slug) {- const acronyms = new Set(['dm', 'dms', 'csv', 'qr', 'ab', 'rss', 'ai', 'id', 'x']);- return slug- .split('-')- .map(w => acronyms.has(w) ? w.toUpperCase() : w.charAt(0).toUpperCase() + w.slice(1))- .join(' ');-}--function getCategoryInfo(slug) {- if (CATEGORIES[slug]) return CATEGORIES[slug];- // Try partial matching- for (const [key, val] of Object.entries(CATEGORIES)) {- if (slug.includes(key) || key.includes(slug)) return val;- }- return { cat: 'Other Tools', icon: '⚡', priority: 0.5 };-}--// ─── JS File Parser ─────────────────────────────────────────────────--function parseScriptFile(filePath) {- const code = fs.readFileSync(filePath, 'utf-8');- const result = {- name: '',- description: '',- author: '',- version: '',- date: '',- usage: [],- warnings: [],- controls: [],- configBlock: '',- configComments: [],- fullCode: code,- lineCount: code.split('\n').length,- };-- // Extract JSDoc-style header- const jsdocMatch = code.match(/\/\*\*[\s\S]*?\*\//);- const headerComment = jsdocMatch ? jsdocMatch[0] : '';-- // Also try line comments at top- const lineComments = [];- for (const line of code.split('\n')) {- if (line.trim().startsWith('//')) lineComments.push(line.trim().replace(/^\/\/\s?/, ''));- else if (line.trim() === '') continue;- else break;- }-- // Extract @tags from JSDoc- const tagPattern = /@(\w+)\s+(.+)/g;- let tagMatch;- while ((tagMatch = tagPattern.exec(headerComment)) !== null) {- const [, tag, value] = tagMatch;- if (tag === 'name') result.fileName = value.trim();- if (tag === 'description') result.description = value.trim();- if (tag === 'author') result.author = value.trim();- if (tag === 'version') result.version = value.trim();- if (tag === 'date') result.date = value.trim();- }-- // Extract title from emoji headers like "🚫 Unfollow Everyone — Production Grade"- const titleMatch = headerComment.match(/\*\s+[^\n]*?([A-Z][\w\s/&—–-]+(?:—[^*\n]+)?)/);- if (titleMatch) {- result.name = titleMatch[1].replace(/\s*—[\s\S]*$/, '').replace(/Production Grade/i, '').replace(/\s+/g, ' ').trim();- }-- // Extract description from header comment if not found via @tag- if (!result.description) {- // Try first meaningful line comment- const descLine = lineComments.find(l =>- l.length > 15 && !l.startsWith('==') && !l.startsWith('http') &&- !l.startsWith('REQUIRES') && !l.startsWith('HOW TO') &&- !l.match(/^\d+\./) && !l.startsWith('Last Updated')- );- if (descLine) result.description = descLine;- }-- // Extract USAGE section- const usageMatch = headerComment.match(/USAGE[^:]*:\s*\n([\s\S]*?)(?:\n\s*\*\s*(?:CONTROLS|⚠️|===|\*\/))/i) ||- code.match(/\/\/\s*HOW TO USE:\s*\n([\s\S]*?)(?:\n\s*(?:\/\/\s*$|\(\(\)|const ))/im);- if (usageMatch) {- result.usage = usageMatch[1]- .split('\n')- .map(l => l.replace(/^\s*\*\s?/, '').replace(/^\/\/\s?/, '').trim())- .filter(l => l && !l.startsWith('==='));- }-- // Extract CONTROLS section- const controlsMatch = headerComment.match(/CONTROLS[^:]*:\s*\n([\s\S]*?)(?:\n\s*\*\s*(?:===|\*\/))/i);- if (controlsMatch) {- result.controls = controlsMatch[1]- .split('\n')- .map(l => l.replace(/^\s*\*\s?/, '').trim())- .filter(l => l);- }-- // Extract warnings- const warningMatch = headerComment.match(/⚠️[^\n]*/g);- if (warningMatch) {- result.warnings = warningMatch.map(w => w.replace(/^\s*\*\s?/, '').trim());- }-- // Extract CONFIG/OPTIONS block- const configMatch = code.match(/(?:const|let)\s+(?:CONFIG|OPTIONS)\s*=\s*\{([\s\S]*?)^\s*\};/m);- if (configMatch) {- result.configBlock = configMatch[0];- // Parse inline comments as config docs- const configLines = configMatch[1].split('\n');- for (const line of configLines) {- const commentMatch = line.match(/(\w+)\s*:\s*([^,]+),?\s*\/\/\s*(.+)/);- if (commentMatch) {- result.configComments.push({- key: commentMatch[1].trim(),- default: commentMatch[2].trim(),- description: commentMatch[3].trim(),- });- }- }- }-- return result;-}--// ─── HTML Generator ─────────────────────────────────────────────────--function generateScriptPage({ slug, title, description, category, icon, sourceDir, parsed, requiresCore, relatedPages }) {- const seoTitle = `${title} — Free X/Twitter Script | XActions`;- const seoDesc = (description || `${title} — Free browser console script for X/Twitter automation. No API keys needed.`).slice(0, 160);- const canonicalUrl = `${SITE_URL}/scripts/${slug}`;- const keywords = ['xactions', 'twitter automation', 'x automation', 'browser script', 'devtools console', 'free', 'open source',- ...slug.split('-').filter(w => w.length > 2), category.toLowerCase()].join(', ');-- const usageHtml = parsed.usage.length > 0- ? `<ol class="usage-steps">${parsed.usage- .filter(l => l.match(/^\d+\./))- .map(l => `<li>${escapeHtml(l.replace(/^\d+\.\s*/, ''))}</li>`)- .join('\n')}</ol>`- : `<ol class="usage-steps">- <li>Navigate to <a href="https://x.com" rel="noopener">x.com</a> and log in</li>- <li>Open DevTools Console (F12 or Cmd+Option+I)</li>- ${requiresCore ? '<li>Paste <code>src/automation/core.js</code> first</li>' : ''}- <li>Paste the script below and press Enter</li>- </ol>`;-- const warningsHtml = parsed.warnings.length > 0- ? `<div class="warning-box">${parsed.warnings.map(w => `<p>${escapeHtml(w)}</p>`).join('')}</div>`- : '';-- const controlsHtml = parsed.controls.length > 0- ? `<div class="controls-box">- <h3>Runtime Controls</h3>- <pre><code>${parsed.controls.map(c => escapeHtml(c)).join('\n')}</code></pre>- </div>`- : '';-- const configHtml = parsed.configComments.length > 0- ? `<section class="config-section">- <h2>Configuration Options</h2>- <table>- <thead><tr><th>Option</th><th>Default</th><th>Description</th></tr></thead>- <tbody>- ${parsed.configComments.map(c => `<tr><td><code>${escapeHtml(c.key)}</code></td><td><code>${escapeHtml(c.default)}</code></td><td>${escapeHtml(c.description)}</td></tr>`).join('\n')}- </tbody>- </table>- </section>`- : '';-- const configBlockHtml = parsed.configBlock- ? `<section class="config-code">- <h2>Default Configuration</h2>- <div class="code-block">- <button class="copy-btn" onclick="navigator.clipboard.writeText(this.nextElementSibling.querySelector('code').textContent).then(()=>{this.textContent='Copied!';setTimeout(()=>this.textContent='Copy',2000)})">Copy</button>- <pre><code>${escapeHtml(parsed.configBlock)}</code></pre>- </div>- </section>`- : '';-- const relatedHtml = relatedPages- .filter(p => p.slug !== slug)- .slice(0, 10)- .map(p => `<a href="/scripts/${p.slug}">${p.icon} ${escapeHtml(p.title)}</a>`)- .join('\n');-- return `<!DOCTYPE html>-<html lang="en">-<head>- <meta charset="UTF-8">- <meta name="viewport" content="width=device-width, initial-scale=1.0">- <title>${escapeHtml(seoTitle)}</title>- <meta name="description" content="${escapeHtml(seoDesc)}">- <meta name="keywords" content="${escapeHtml(keywords)}">- <meta name="author" content="nich (@nichxbt)">- <meta name="robots" content="index, follow">-- <meta property="og:type" content="article">- <meta property="og:title" content="${escapeHtml(title)} — XActions">- <meta property="og:description" content="${escapeHtml(seoDesc)}">- <meta property="og:url" content="${canonicalUrl}">- <meta property="og:site_name" content="XActions">- <meta property="og:image" content="${SITE_URL}/og-image.png">-- <meta name="twitter:card" content="summary_large_image">- <meta name="twitter:site" content="@nichxbt">- <meta name="twitter:title" content="${escapeHtml(title)} — XActions">- <meta name="twitter:description" content="${escapeHtml(seoDesc)}">-- <link rel="canonical" href="${canonicalUrl}">- <link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>⚡</text></svg>">-- <script type="application/ld+json">- {- "@context": "https://schema.org",- "@type": "TechArticle",- "headline": ${JSON.stringify(seoTitle)},- "description": ${JSON.stringify(seoDesc)},- "url": "${canonicalUrl}",- "author": { "@type": "Person", "name": "nich", "url": "https://x.com/nichxbt" },- "publisher": { "@type": "Organization", "name": "XActions", "url": "${SITE_URL}" },- "datePublished": "2026-03-30",- "dateModified": "2026-03-30",- "articleSection": ${JSON.stringify(category)},- "keywords": ${JSON.stringify(keywords)}- }- </script>- <script type="application/ld+json">- {- "@context": "https://schema.org",- "@type": "BreadcrumbList",- "itemListElement": [- { "@type": "ListItem", "position": 1, "name": "Home", "item": "${SITE_URL}" },- { "@type": "ListItem", "position": 2, "name": "Scripts", "item": "${SITE_URL}/scripts" },- { "@type": "ListItem", "position": 3, "name": ${JSON.stringify(category)}, "item": "${SITE_URL}/scripts#${slugify(category)}" },- { "@type": "ListItem", "position": 4, "name": ${JSON.stringify(title)}, "item": "${canonicalUrl}" }- ]- }- </script>-- <link rel="stylesheet" href="/css/common.css">- <style>- .article { padding: 24px 20px; }- .article h1 { font-size: 1.75rem; font-weight: 800; margin-bottom: 8px; line-height: 1.2; }- .article h2 { font-size: 1.375rem; font-weight: 700; margin: 32px 0 12px; padding-top: 16px; border-top: 1px solid var(--border); }- .article h3 { font-size: 1.125rem; font-weight: 600; margin: 24px 0 8px; color: var(--accent); }- .article p { color: var(--text-secondary); font-size: 0.9375rem; margin-bottom: 16px; }- .article a { color: var(--accent); text-decoration: none; }- .article a:hover { text-decoration: underline; }- .article strong { color: var(--text-primary); }- .article code { background: var(--bg-tertiary); padding: 2px 6px; border-radius: 4px; font-family: 'Monaco','Menlo','Consolas', monospace; font-size: 0.875rem; color: var(--accent); }- .article pre { background: var(--bg-secondary); border: 1px solid var(--border); border-radius: 12px; padding: 16px; overflow-x: auto; margin: 16px 0; }- .article pre code { background: none; padding: 0; color: var(--text-primary); font-size: 0.8125rem; display: block; }- .article table { width: 100%; border-collapse: collapse; margin: 16px 0; font-size: 0.875rem; }- .article th { background: var(--bg-secondary); padding: 10px 12px; text-align: left; border: 1px solid var(--border); font-weight: 600; }- .article td { padding: 10px 12px; border: 1px solid var(--border); color: var(--text-secondary); }- .cat-badge { display: inline-block; background: var(--accent-light); color: var(--accent); padding: 4px 12px; border-radius: 9999px; font-size: 0.75rem; font-weight: 600; margin-bottom: 16px; }- .meta-row { display: flex; gap: 16px; flex-wrap: wrap; margin-bottom: 16px; font-size: 0.8125rem; color: var(--text-secondary); }- .meta-row span { display: flex; align-items: center; gap: 4px; }- .usage-steps { margin-left: 24px; margin-bottom: 16px; }- .usage-steps li { color: var(--text-secondary); font-size: 0.9375rem; margin-bottom: 8px; padding-left: 4px; }- .warning-box { background: rgba(244, 33, 46, 0.1); border: 1px solid var(--error); border-radius: 12px; padding: 16px; margin: 16px 0; }- .warning-box p { color: var(--error); margin: 0; font-size: 0.875rem; }- .controls-box { background: var(--bg-secondary); border: 1px solid var(--border); border-radius: 12px; padding: 16px; margin: 16px 0; }- .controls-box h3 { margin: 0 0 8px; font-size: 1rem; }- .code-block { position: relative; }- .copy-btn { position: absolute; top: 8px; right: 8px; background: var(--bg-tertiary); color: var(--text-secondary); border: 1px solid var(--border); border-radius: 8px; padding: 6px 12px; cursor: pointer; font-size: 0.75rem; z-index: 10; transition: all .2s; }- .copy-btn:hover { background: var(--accent); color: #fff; }- .full-code { margin-top: 32px; }- .full-code pre { max-height: 600px; overflow-y: auto; }- .cta-box { background: linear-gradient(135deg, var(--bg-secondary), var(--bg-tertiary)); border: 1px solid var(--border); border-radius: 16px; padding: 24px; margin: 32px 0; text-align: center; }- .cta-box h3 { font-size: 1.25rem; margin-bottom: 8px; color: var(--text-primary); }- .cta-box p { color: var(--text-secondary); margin-bottom: 16px; }- .cta-box a { display: inline-block; padding: 12px 24px; background: var(--accent); color: #fff; border-radius: 9999px; text-decoration: none; font-weight: 700; transition: background .2s; }- .cta-box a:hover { background: var(--accent-hover); }- .sidebar-right { width: 350px; padding: 16px 24px; position: sticky; top: 0; height: 100vh; overflow-y: auto; }- .sidebar-card { background: var(--bg-secondary); border-radius: 16px; padding: 16px; margin-bottom: 16px; }- .sidebar-card h3 { font-size: 1rem; font-weight: 700; margin-bottom: 12px; }- .sidebar-card a { display: block; color: var(--text-secondary); text-decoration: none; font-size: 0.875rem; padding: 6px 0; border-bottom: 1px solid var(--border); transition: color .2s; }- .sidebar-card a:last-child { border-bottom: none; }- .sidebar-card a:hover { color: var(--accent); }- .breadcrumb { font-size: 0.8125rem; color: var(--text-secondary); margin-top: 4px; }- .breadcrumb a { color: var(--accent); text-decoration: none; }- .breadcrumb a:hover { text-decoration: underline; }- .source-badge { display: inline-block; background: var(--bg-tertiary); color: var(--text-secondary); padding: 2px 8px; border-radius: 6px; font-size: 0.6875rem; margin-left: 8px; }- @media (max-width: 1024px) { .sidebar-right { display: none; } }- @media (max-width: 768px) {- .article pre { font-size: 0.75rem; }- .meta-row { flex-direction: column; gap: 4px; }- }- </style>-</head>-<body>- <a href="#main-content" class="skip-nav">Skip to main content</a>- <div class="layout">- <aside class="sidebar-left" aria-label="Main navigation"></aside>- <script src="/js/sidebar.js"></script>-- <main class="main-content" id="main-content">- <header class="main-header">- <h1>${icon} ${escapeHtml(title)}</h1>- <div class="breadcrumb">- <a href="/">Home</a> › <a href="/scripts">Scripts</a> › <a href="/scripts#${slugify(category)}">${escapeHtml(category)}</a> › ${escapeHtml(title)}- </div>- </header>-- <article class="article">- <span class="cat-badge">${escapeHtml(category)}</span>- <span class="source-badge">${escapeHtml(sourceDir)}</span>-- <div class="meta-row">- ${parsed.version ? `<span>v${escapeHtml(parsed.version)}</span>` : ''}- ${parsed.date ? `<span>Updated: ${escapeHtml(parsed.date)}</span>` : ''}- <span>${parsed.lineCount} lines</span>- <span>by <a href="https://x.com/nichxbt" rel="noopener">@nichxbt</a></span>- </div>-- <p>${escapeHtml(description || `${title} — a free, open-source browser console script for X/Twitter automation. No API keys or fees required.`)}</p>-- ${warningsHtml}-- <h2>How to Use</h2>- ${usageHtml}- ${requiresCore ? '<p><strong>Note:</strong> This script requires pasting <code>src/automation/core.js</code> first for shared utilities.</p>' : ''}-- ${controlsHtml}- ${configHtml}- ${configBlockHtml}-- <section class="full-code">- <h2>Full Script</h2>- <p>Copy and paste this entire script into your browser DevTools console on <a href="https://x.com" rel="noopener">x.com</a>.</p>- <div class="code-block">- <button class="copy-btn" onclick="navigator.clipboard.writeText(this.nextElementSibling.querySelector('code').textContent).then(()=>{this.textContent='Copied!';setTimeout(()=>this.textContent='Copy Script',2000)})">Copy Script</button>- <pre><code>${escapeHtml(parsed.fullCode)}</code></pre>- </div>- </section>-- <div class="cta-box">- <h3>⚡ More XActions Scripts</h3>- <p>Browse 300+ free browser scripts for X/Twitter automation. No API keys, no fees.</p>- <a href="/scripts">Browse All Scripts</a>- </div>- </article>- </main>-- <aside class="sidebar-right">- <div class="sidebar-card">- <h3>${icon} ${escapeHtml(category)}</h3>- ${relatedHtml || '<a href="/scripts">Browse all scripts</a>'}- </div>- <div class="sidebar-card">- <h3>🔗 Quick Links</h3>- <a href="/scripts">All Scripts</a>- <a href="/features">Features</a>- <a href="/docs">Documentation</a>- <a href="/tutorials">Tutorials</a>- <a href="/mcp">MCP Server</a>- <a href="https://github.com/nirholas/XActions" rel="noopener">GitHub</a>- </div>- </aside>- </div>-</body>-</html>`;-}--// ─── Index Page Generator ───────────────────────────────────────────--function generateIndexPage(allPages) {- const byCategory = {};- for (const page of allPages) {- if (!byCategory[page.category]) byCategory[page.category] = [];- byCategory[page.category].push(page);- }-- // Sort categories- const catOrder = [- 'Unfollow Tools', 'Follower Monitoring', 'Engagement', 'Growth',- 'Scrapers', 'Content Tools', 'Posting', 'Messaging', 'Analytics',- 'Safety & Privacy', 'Account Management', 'Lists & Communities',- 'Automation', 'AI & Developer', 'Spaces & Live', 'Premium',- 'Business', 'Discovery', 'Other Tools'- ];-- const sortedCats = catOrder.filter(c => byCategory[c]);- // Add any missing categories- for (const c of Object.keys(byCategory)) {- if (!sortedCats.includes(c)) sortedCats.push(c);- }-- const categoryCardsHtml = sortedCats.map(cat => {- const pages = byCategory[cat].sort((a, b) => a.title.localeCompare(b.title));- const catSlug = slugify(cat);- return `- <section class="cat-section" id="${catSlug}">- <h2>${pages[0].icon} ${escapeHtml(cat)} <span class="count">(${pages.length})</span></h2>- <div class="script-grid">- ${pages.map(p => `- <a href="/scripts/${p.slug}" class="script-card" data-cat="${catSlug}" data-name="${escapeHtml(p.title.toLowerCase())}">- <span class="script-icon">${p.icon}</span>- <div class="script-info">- <strong>${escapeHtml(p.title)}</strong>- <span>${escapeHtml((p.description || '').slice(0, 80))}</span>- </div>- </a>`).join('')}- </div>- </section>`;- }).join('\n');-- const catNavHtml = sortedCats.map(cat => {- const pages = byCategory[cat];- return `<a href="#${slugify(cat)}">${pages[0].icon} ${escapeHtml(cat)} (${pages.length})</a>`;- }).join('\n');-- return `<!DOCTYPE html>-<html lang="en">-<head>- <meta charset="UTF-8">- <meta name="viewport" content="width=device-width, initial-scale=1.0">- <title>All ${allPages.length} Scripts — Free X/Twitter Automation | XActions</title>- <meta name="description" content="Browse ${allPages.length}+ free browser console scripts for X/Twitter automation. Unfollow, scrape, engage, grow, and more. No API keys needed.">- <meta name="keywords" content="xactions, twitter automation, x automation, browser scripts, devtools console, free, open source, unfollow, scraper, engagement">- <meta name="author" content="nich (@nichxbt)">- <meta name="robots" content="index, follow">-- <meta property="og:type" content="website">- <meta property="og:title" content="All ${allPages.length} Scripts — XActions">- <meta property="og:description" content="${allPages.length}+ free browser scripts for X/Twitter automation.">- <meta property="og:url" content="${SITE_URL}/scripts">- <meta property="og:site_name" content="XActions">-- <meta name="twitter:card" content="summary_large_image">- <meta name="twitter:site" content="@nichxbt">- <meta name="twitter:title" content="All ${allPages.length} Scripts — XActions">-- <link rel="canonical" href="${SITE_URL}/scripts">- <link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>⚡</text></svg>">-- <script type="application/ld+json">- {- "@context": "https://schema.org",- "@type": "CollectionPage",- "name": "XActions Scripts — ${allPages.length}+ Free X/Twitter Automation Scripts",- "description": "Complete collection of free browser console scripts for X/Twitter automation.",- "url": "${SITE_URL}/scripts",- "author": { "@type": "Person", "name": "nich", "url": "https://x.com/nichxbt" },- "publisher": { "@type": "Organization", "name": "XActions", "url": "${SITE_URL}" }- }- </script>-- <link rel="stylesheet" href="/css/common.css">- <style>- .hero { padding: 32px 20px; border-bottom: 1px solid var(--border); }- .hero h1 { font-size: 1.75rem; font-weight: 800; margin-bottom: 8px; }- .hero p { color: var(--text-secondary); font-size: 0.9375rem; }- .search-box { margin: 16px 20px; position: sticky; top: 60px; z-index: 50; background: var(--bg-primary); padding: 8px 0; }- .search-box input { width: 100%; padding: 12px 16px; background: var(--bg-secondary); border: 1px solid var(--border); border-radius: 9999px; color: var(--text-primary); font-size: 0.9375rem; outline: none; transition: border-color .2s; }- .search-box input:focus { border-color: var(--accent); }- .search-box input::placeholder { color: var(--text-secondary); }- .cat-section { padding: 0 20px; margin-bottom: 32px; }- .cat-section h2 { font-size: 1.25rem; font-weight: 700; margin-bottom: 16px; padding-top: 16px; border-top: 1px solid var(--border); }- .cat-section h2 .count { color: var(--text-secondary); font-weight: 400; font-size: 0.875rem; }- .script-grid { display: grid; gap: 8px; }- .script-card { display: flex; align-items: center; gap: 12px; padding: 12px 16px; border-radius: 12px; text-decoration: none; color: var(--text-primary); transition: background .2s; }- .script-card:hover { background: var(--bg-secondary); }- .script-icon { font-size: 1.5rem; width: 36px; text-align: center; flex-shrink: 0; }- .script-info { display: flex; flex-direction: column; min-width: 0; }- .script-info strong { font-size: 0.9375rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }- .script-info span { font-size: 0.8125rem; color: var(--text-secondary); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }- .stats-bar { display: flex; gap: 24px; padding: 16px 20px; border-bottom: 1px solid var(--border); flex-wrap: wrap; }- .stat { text-align: center; }- .stat-num { font-size: 1.5rem; font-weight: 800; color: var(--accent); display: block; }- .stat-label { font-size: 0.75rem; color: var(--text-secondary); }- .sidebar-right { width: 350px; padding: 16px 24px; position: sticky; top: 0; height: 100vh; overflow-y: auto; }- .sidebar-card { background: var(--bg-secondary); border-radius: 16px; padding: 16px; margin-bottom: 16px; }- .sidebar-card h3 { font-size: 1rem; font-weight: 700; margin-bottom: 12px; }- .sidebar-card a { display: block; color: var(--text-secondary); text-decoration: none; font-size: 0.8125rem; padding: 4px 0; border-bottom: 1px solid var(--border); transition: color .2s; }- .sidebar-card a:last-child { border-bottom: none; }- .sidebar-card a:hover { color: var(--accent); }- .no-results { display: none; padding: 48px 20px; text-align: center; color: var(--text-secondary); }- .no-results.visible { display: block; }- @media (max-width: 1024px) { .sidebar-right { display: none; } }- @media (max-width: 768px) {- .stats-bar { gap: 16px; }- .stat-num { font-size: 1.25rem; }- }- </style>-</head>-<body>- <a href="#main-content" class="skip-nav">Skip to main content</a>- <div class="layout">- <aside class="sidebar-left" aria-label="Main navigation"></aside>- <script src="/js/sidebar.js"></script>-- <main class="main-content" id="main-content">- <header class="main-header">- <h1>⚡ All Scripts</h1>- </header>-- <div class="hero">- <h1>⚡ ${allPages.length} Free X/Twitter Scripts</h1>- <p>Browser console scripts for X/Twitter automation. No API keys, no fees, no signup. Just paste and run.</p>- </div>-- <div class="stats-bar">- <div class="stat"><span class="stat-num">${allPages.length}</span><span class="stat-label">Total Scripts</span></div>- <div class="stat"><span class="stat-num">${sortedCats.length}</span><span class="stat-label">Categories</span></div>- <div class="stat"><span class="stat-num">100%</span><span class="stat-label">Free</span></div>- <div class="stat"><span class="stat-num">0</span><span class="stat-label">API Keys Needed</span></div>- </div>-- <div class="search-box">- <input type="text" id="scriptSearch" placeholder="Search ${allPages.length} scripts..." autocomplete="off">- </div>-- <div id="scriptResults">- ${categoryCardsHtml}- </div>- <div class="no-results" id="noResults">- <h2>No scripts found</h2>- <p>Try a different search term</p>- </div>- </main>-- <aside class="sidebar-right">- <div class="sidebar-card">- <h3>📂 Categories</h3>- ${catNavHtml}- </div>- <div class="sidebar-card">- <h3>🔗 Quick Links</h3>- <a href="/features">Features Overview</a>- <a href="/docs">Documentation</a>- <a href="/tutorials">Tutorials</a>- <a href="/mcp">MCP Server</a>- <a href="https://github.com/nirholas/XActions" rel="noopener">GitHub</a>- </div>- </aside>- </div>-- <script>- const search = document.getElementById('scriptSearch');- const results = document.getElementById('scriptResults');- const noResults = document.getElementById('noResults');- search.addEventListener('input', () => {- const q = search.value.toLowerCase().trim();- const cards = results.querySelectorAll('.script-card');- const sections = results.querySelectorAll('.cat-section');- let visible = 0;- cards.forEach(card => {- const match = !q || card.dataset.name.includes(q) || card.dataset.cat.includes(q);- card.style.display = match ? '' : 'none';- if (match) visible++;- });- sections.forEach(section => {- const hasVisible = [...section.querySelectorAll('.script-card')].some(c => c.style.display !== 'none');- section.style.display = hasVisible ? '' : 'none';- });- noResults.classList.toggle('visible', visible === 0);- });- </script>-</body>-</html>`;-}--// ─── Main Build ─────────────────────────────────────────────────────--function build() {- console.log('⚡ Building script pages...\n');-- if (!fs.existsSync(OUT_DIR)) fs.mkdirSync(OUT_DIR, { recursive: true });-- const allPages = [];- const seen = new Set(); // Deduplicate by slug-- for (const source of SCRIPT_DIRS) {- const dir = path.join(ROOT, source.dir);- if (!fs.existsSync(dir)) continue;-- const files = fs.readdirSync(dir).filter(f => {- if (!f.endsWith('.js')) return false;- if (SKIP_FILES.has(f)) return false;- // For src/, skip subdirectories' files- if (source.dir === 'src') {- const stat = fs.statSync(path.join(dir, f));- if (!stat.isFile()) return false;- }- return true;- });-- console.log(`📂 ${source.label} (${source.dir}/) — ${files.length} files`);-- for (const file of files) {- const slug = slugify(file);- if (seen.has(slug)) continue; // Skip duplicates (prefer first source = src/)- seen.add(slug);-- const filePath = path.join(dir, file);- const parsed = parseScriptFile(filePath);- const catInfo = getCategoryInfo(slug);-- const title = parsed.name || slugToTitle(slug);-- allPages.push({- slug,- title,- description: parsed.description,- category: catInfo.cat,- icon: catInfo.icon,- priority: catInfo.priority,- sourceDir: source.dir,- requiresCore: source.requiresCore || false,- parsed,- });- }- }-- // Sort within categories- allPages.sort((a, b) => a.title.localeCompare(b.title));-- // Group by category for related links- const byCategory = {};- for (const page of allPages) {- if (!byCategory[page.category]) byCategory[page.category] = [];- byCategory[page.category].push(page);- }-- // Generate individual pages- let count = 0;- for (const page of allPages) {- const html = generateScriptPage({- ...page,- relatedPages: byCategory[page.category] || [],- });- const outFile = path.join(OUT_DIR, `${page.slug}.html`);- fs.writeFileSync(outFile, html);- count++;- }-- // Generate index page- const indexHtml = generateIndexPage(allPages);- fs.writeFileSync(path.join(OUT_DIR, 'index.html'), indexHtml);- count++;-- // Generate sitemap entries- const sitemapXml = allPages.map(p => ` <url>- <loc>${SITE_URL}/scripts/${p.slug}</loc>- <lastmod>2026-03-30</lastmod>- <changefreq>monthly</changefreq>- <priority>${p.priority}</priority>- </url>`).join('\n');- fs.writeFileSync(path.join(OUT_DIR, '_sitemap-entries.xml'), sitemapXml);-- // Generate manifest- const manifest = allPages.map(p => ({- slug: p.slug, title: p.title, description: p.description,- category: p.category, icon: p.icon, sourceDir: p.sourceDir,- }));- fs.writeFileSync(path.join(OUT_DIR, '_manifest.json'), JSON.stringify(manifest, null, 2));-- console.log(`\n✅ Generated ${count} pages (${allPages.length} scripts + 1 index)`);- console.log(`📋 Sitemap → dashboard/scripts/_sitemap-entries.xml`);- console.log(`📋 Manifest → dashboard/scripts/_manifest.json`);-- // Category breakdown- console.log('\n📊 Categories:');- for (const [cat, pages] of Object.entries(byCategory).sort((a, b) => b[1].length - a[1].length)) {- console.log(` ${pages[0].icon} ${cat}: ${pages.length}`);- }-}--build();diff --git a/xactions/scripts/deploy.sh b/xactions/scripts/deploy.shdeleted file mode 100755index 4386ebc7d..000000000--- a/xactions/scripts/deploy.sh+++ /dev/null@@ -1,148 +0,0 @@-#!/usr/bin/env bash-# ═══════════════════════════════════════════════════════════════════════════════-# XActions — Quick Deploy Script-# Detects available platforms and deploys accordingly-# Usage: ./scripts/deploy.sh [platform]-# Platforms: railway, cloudflare, fly, render, docker-# by nichxbt-# ═══════════════════════════════════════════════════════════════════════════════--set -e--PLATFORM="${1:-auto}"-GREEN='\033[0;32m'-YELLOW='\033[1;33m'-RED='\033[0;31m'-NC='\033[0m'--log() { echo -e "${GREEN}✅ $1${NC}"; }-warn() { echo -e "${YELLOW}⚠️ $1${NC}"; }-err() { echo -e "${RED}❌ $1${NC}"; exit 1; }--echo "🚀 XActions Deploy Script"-echo "───────────────────────────"--# ─────────────────────────────────────────────────────────────────────────────-# Auto-detect platform-# ─────────────────────────────────────────────────────────────────────────────-if [ "$PLATFORM" = "auto" ]; then- if command -v railway &> /dev/null && [ -n "$RAILWAY_TOKEN" ]; then- PLATFORM="railway"- elif command -v fly &> /dev/null; then- PLATFORM="fly"- elif command -v wrangler &> /dev/null; then- PLATFORM="cloudflare"- elif command -v docker &> /dev/null; then- PLATFORM="docker"- else- echo ""- echo "Available platforms:"- echo " railway — Railway.app (recommended, already configured)"- echo " cloudflare — Cloudflare Pages (static frontend only)"- echo " fly — Fly.io (full stack)"- echo " render — Render.com (full stack)"- echo " docker — Docker Compose (self-host)"- echo ""- echo "Usage: ./scripts/deploy.sh <platform>"- exit 1- fi- log "Auto-detected platform: $PLATFORM"-fi--# ─────────────────────────────────────────────────────────────────────────────-# Deploy functions-# ─────────────────────────────────────────────────────────────────────────────--deploy_railway() {- command -v railway &> /dev/null || err "Railway CLI not installed. Run: npm install -g @railway/cli"- echo "📦 Deploying API to Railway..."- railway up --service xactions-api- log "Railway deploy complete!"- echo ""- echo "📝 Don't forget to set these in Railway dashboard:"- echo " DATABASE_URL, JWT_SECRET, REDIS_HOST, REDIS_PORT"-}--deploy_cloudflare() {- command -v wrangler &> /dev/null || err "Wrangler CLI not installed. Run: npm install -g wrangler"- echo "📦 Deploying dashboard to Cloudflare Pages..."- wrangler pages deploy dashboard --project-name=xactions- log "Cloudflare Pages deploy complete!"-}--deploy_fly() {- command -v fly &> /dev/null || err "Fly CLI not installed. See: https://fly.io/docs/hands-on/install-flyctl/"-- # Check if app exists- if ! fly apps list 2>/dev/null | grep -q "xactions"; then- echo "📦 Creating Fly.io app..."- fly launch --no-deploy --name xactions- echo ""- echo "📝 Setting up Fly Postgres..."- fly postgres create --name xactions-db || warn "Postgres may already exist"- fly postgres attach xactions-db || warn "Postgres may already be attached"- fi-- echo "📦 Deploying to Fly.io..."- fly deploy- log "Fly.io deploy complete!"-}--deploy_render() {- echo "📦 Render.com deploys via GitHub integration."- echo ""- echo "Steps:"- echo " 1. Go to https://dashboard.render.com"- echo " 2. Click 'New' → 'Blueprint'"- echo " 3. Connect your GitHub repo (nirholas/XActions)"- echo " 4. Render auto-detects render.yaml"- echo " 5. Click 'Apply'"- echo ""- log "render.yaml is ready — just connect the repo!"-}--deploy_docker() {- command -v docker &> /dev/null || err "Docker not installed"-- if [ ! -f ".env" ]; then- warn "No .env file found. Copying from .env.example..."- cp .env.example .env- echo "📝 Edit .env with your production values before deploying!"- exit 1- fi-- echo "📦 Building and starting XActions stack..."- docker compose up -d --build-- echo ""- echo "Waiting for services to be healthy..."- sleep 10-- # Check health- if docker compose ps | grep -q "healthy"; then- log "Docker stack is running!"- echo ""- echo "🌐 API: http://localhost:3001"- echo "📊 Health: http://localhost:3001/api/health"- echo "🗄️ Postgres: localhost:5432"- echo "📮 Redis: localhost:6379"- else- warn "Some services may still be starting. Check: docker compose ps"- fi-}--# ─────────────────────────────────────────────────────────────────────────────-# Execute-# ─────────────────────────────────────────────────────────────────────────────-case "$PLATFORM" in- railway) deploy_railway ;;- cloudflare) deploy_cloudflare ;;- fly) deploy_fly ;;- render) deploy_render ;;- docker) deploy_docker ;;- *) err "Unknown platform: $PLATFORM" ;;-esac--echo ""-echo "───────────────────────────"-echo "🎉 Done! XActions deployed via $PLATFORM"diff --git a/xactions/scripts/generate-license.js b/xactions/scripts/generate-license.jsdeleted file mode 100644index 310536726..000000000--- a/xactions/scripts/generate-license.js+++ /dev/null@@ -1,164 +0,0 @@-#!/usr/bin/env node-// Copyright (c) 2024-2026 nich (@nichxbt). Business Source License 1.1.-/**- * License Key Generator CLI- *- * Usage:- * node scripts/generate-license.js --tier=business --customer="Acme Corp" --email="[email protected]"- * node scripts/generate-license.js --tier=enterprise --company="Big Tech Inc" --expires=365- */--import { createLicense, listLicenses, revokeLicense, TIER_FEATURES } from '../api/services/licenseManager.js';--// Parse command line arguments-const args = process.argv.slice(2);-const options = {};--args.forEach(arg => {- if (arg.startsWith('--')) {- const [key, ...valueParts] = arg.slice(2).split('=');- options[key] = valueParts.join('=') || true;- }-});--// Help-if (options.help || args.length === 0) {- console.log(`-⚡ XActions License Generator--Usage:- node scripts/generate-license.js [options]--Options:- --tier=<tier> License tier: starter, business, enterprise (default: starter)- --customer=<name> Customer name- --email=<email> Customer email- --company=<name> Company name- --expires=<days> Days until expiration (optional)- --instances=<n> Max instances (optional)- --notes=<text> Admin notes- --list List all licenses- --revoke=<key> Revoke a license key- --help Show this help--Examples:- node scripts/generate-license.js --tier=starter --customer="John Doe" --email="[email protected]"- node scripts/generate-license.js --tier=business --company="Acme Corp" --expires=365- node scripts/generate-license.js --tier=enterprise --company="Big Tech" --instances=10- node scripts/generate-license.js --list- node scripts/generate-license.js --revoke=XACT-XXXX-XXXX-XXXX-XXXX--Tiers:- starter - $49/mo - Branding shown, 500 users, 1 instance- business - $199/mo - No branding, 5000 users, 3 instances, API access- enterprise - Custom - No branding, unlimited users/instances, API access-`);- process.exit(0);-}--async function main() {- try {- // List licenses- if (options.list) {- console.log('\n📋 Listing all licenses...\n');- const { licenses, total } = await listLicenses({ limit: 50 });-- if (licenses.length === 0) {- console.log('No licenses found.');- } else {- console.log(`Found ${total} license(s):\n`);- licenses.forEach(lic => {- const status = lic.status === 'active' ? '✅' : '❌';- console.log(`${status} ${lic.key}`);- console.log(` Tier: ${lic.tier} | Customer: ${lic.customerName || lic.companyName || 'N/A'}`);- console.log(` Email: ${lic.customerEmail || 'N/A'}`);- console.log(` Status: ${lic.status} | Activations: ${lic.activations}`);- console.log(` Created: ${lic.createdAt.toISOString().split('T')[0]}`);- if (lic.expiresAt) {- console.log(` Expires: ${lic.expiresAt.toISOString().split('T')[0]}`);- }- console.log('');- });- }- process.exit(0);- }-- // Revoke license- if (options.revoke) {- console.log(`\n🚫 Revoking license: ${options.revoke}...\n`);- const license = await revokeLicense(options.revoke, 'Revoked via CLI');- console.log(`License ${license.key} has been revoked.`);- process.exit(0);- }-- // Generate new license- const tier = options.tier || 'starter';-- if (!['starter', 'business', 'enterprise'].includes(tier)) {- console.error('❌ Invalid tier. Use: starter, business, or enterprise');- process.exit(1);- }-- console.log('\n⚡ Generating new license key...\n');-- const license = await createLicense({- tier,- customerName: options.customer,- customerEmail: options.email,- companyName: options.company,- expiresInDays: options.expires ? parseInt(options.expires) : null,- maxInstances: options.instances ? parseInt(options.instances) : null,- notes: options.notes,- });-- console.log('✅ License created successfully!\n');- console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');- console.log(`🔑 License Key: ${license.key}`);- console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');- console.log(`Tier: ${license.tier}`);- console.log(`Max Users: ${license.maxUsers === -1 ? 'Unlimited' : license.maxUsers}`);- console.log(`Max Instances: ${license.maxInstances === -1 ? 'Unlimited' : license.maxInstances}`);- console.log(`White Label: ${license.whiteLabel ? 'Yes' : 'No'}`);- console.log(`Custom Domain: ${license.customDomain ? 'Yes' : 'No'}`);- console.log(`API Access: ${license.apiAccess ? 'Yes' : 'No'}`);- if (license.expiresAt) {- console.log(`Expires: ${license.expiresAt.toISOString().split('T')[0]}`);- } else {- console.log(`Expires: Never`);- }- if (license.customerName) console.log(`Customer: ${license.customerName}`);- if (license.customerEmail) console.log(`Email: ${license.customerEmail}`);- if (license.companyName) console.log(`Company: ${license.companyName}`);- console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');-- console.log('📧 Send this to your customer:');- console.log(`-Hi${license.customerName ? ` ${license.customerName.split(' ')[0]}` : ''},--Your XActions license key is:--${license.key}--To activate:-1. Add to your .env file: XACTIONS_LICENSE_KEY=${license.key}-2. Restart your XActions server--This key unlocks:-- ${license.tier.charAt(0).toUpperCase() + license.tier.slice(1)} tier features-- ${license.maxUsers === -1 ? 'Unlimited' : license.maxUsers} users-- ${license.maxInstances === -1 ? 'Unlimited' : license.maxInstances} instance(s)-${license.whiteLabel ? '- White-label (no branding)' : ''}-${license.apiAccess ? '- API access' : ''}--Questions? Reply to this email or DM @nichxbt on X.--Thanks for using XActions!-`);-- } catch (error) {- console.error('❌ Error:', error.message);- process.exit(1);- }-}--main();diff --git a/xactions/scripts/generate-missing-docs.js b/xactions/scripts/generate-missing-docs.jsdeleted file mode 100644index 8ce4fb01a..000000000--- a/xactions/scripts/generate-missing-docs.js+++ /dev/null@@ -1,479 +0,0 @@-#!/usr/bin/env node-// Copyright (c) 2024-2026 nich (@nichxbt). Business Source License 1.1.-/**- * Generate Missing Documentation- * Creates docs/examples/*.md for all undocumented browser scripts- * by nichxbt- */--import fs from 'fs';-import path from 'path';-import { fileURLToPath } from 'url';--const __filename = fileURLToPath(import.meta.url);-const __dirname = path.dirname(__filename);-const ROOT = path.join(__dirname, '..');--const DOCS_DIR = path.join(ROOT, 'docs', 'examples');--// ── Helpers ──────────────────────────────────────────────────--function camelToSlug(name) {- return name- .replace(/([a-z])([A-Z])/g, '$1-$2')- .replace(/([A-Z])([A-Z][a-z])/g, '$1-$2')- .toLowerCase();-}--function slugToTitle(slug) {- const titleMap = {- 'account-health-monitor': 'Account Health Monitor',- 'algorithm-builder': 'Algorithm Builder',- 'article-publisher': 'Article Publisher',- 'audience-demographics': 'Audience Demographics',- 'audience-overlap': 'Audience Overlap',- 'auto-plug-replies': 'Auto-Plug Replies',- 'auto-reply': 'Auto-Reply',- 'bookmark-manager': 'Bookmark Manager',- 'bulk-delete-tweets': 'Bulk Delete Tweets',- 'business-tools': 'Business Tools',- 'content-calendar': 'Content Calendar',- 'content-repurposer': 'Content Repurposer',- 'continuous-monitor': 'Continuous Monitor',- 'creator-studio': 'Creator Studio',- 'dm-manager': 'DM Manager',- 'engagement-booster': 'Engagement Booster',- 'engagement-leaderboard': 'Engagement Leaderboard',- 'engagement-manager': 'Engagement Manager',- 'follow-ratio-manager': 'Follow Ratio Manager',- 'follower-growth-tracker': 'Follower Growth Tracker',- 'grok-integration': 'Grok AI Integration',- 'keyword-monitor': 'Keyword Monitor',- 'manage-muted-words': 'Manage Muted Words',- 'mass-block': 'Mass Block',- 'mass-unblock': 'Mass Unblock',- 'mute-by-keywords': 'Mute by Keywords',- 'new-followers-alert': 'New Followers Alert',- 'notification-manager': 'Notification Manager',- 'persona-engine': 'Persona Engine',- 'pin-tweet-manager': 'Pin Tweet Manager',- 'poll-creator': 'Poll Creator',- 'post-composer': 'Post Composer',- 'premium-manager': 'Premium Manager',- 'profile-manager': 'Profile Manager',- 'quote-tweet-automation': 'Quote Tweet Automation',- 'sentiment-analyzer': 'Sentiment Analyzer',- 'settings-manager': 'Settings Manager',- 'shadowban-checker': 'Shadowban Checker',- 'spaces-manager': 'Spaces Manager',- 'thread-composer': 'Thread Composer',- 'trending-topic-monitor': 'Trending Topic Monitor',- 'tweet-ab-tester': 'Tweet A/B Tester',- 'tweet-performance': 'Tweet Performance',- 'tweet-schedule-optimizer': 'Tweet Schedule Optimizer',- 'unfollow-wdfb-log': 'Unfollow Non-Followers with Logging',- 'viral-tweet-detector': 'Viral Tweet Detector',- 'welcome-new-followers': 'Welcome New Followers',- // scripts-only- 'scrape-profile-with-replies': 'Scrape Profile with Replies',- 'scrape-analytics': 'Scrape Analytics',- 'scrape-bookmarks': 'Scrape Bookmarks',- 'scrape-cashtag-search': 'Scrape Cashtag Search',- 'scrape-dms': 'Scrape DMs',- 'scrape-explore': 'Scrape Explore',- 'scrape-followers': 'Scrape Followers',- 'scrape-following': 'Scrape Following',- 'scrape-hashtag': 'Scrape Hashtag',- 'scrape-likers': 'Scrape Likers',- 'scrape-likes': 'Scrape Likes',- 'scrape-list': 'Scrape List Members',- 'scrape-media': 'Scrape Media',- 'scrape-notifications': 'Scrape Notifications',- 'scrape-profile': 'Scrape Profile',- 'scrape-quote-retweets': 'Scrape Quote Retweets',- 'scrape-replies': 'Scrape Replies',- 'scrape-search': 'Scrape Search Results',- 'export-to-csv': 'Export to CSV',- 'dm-exporter': 'DM Exporter',- 'manage-bookmarks': 'Manage Bookmarks',- 'manage-lists': 'Manage Lists',- 'manage-notifications': 'Manage Notifications',- 'manage-settings': 'Manage Settings',- 'publish-article': 'Publish Article',- 'edit-profile': 'Edit Profile',- 'business-analytics': 'Business Analytics',- 'keyword-liker': 'Keyword Liker',- 'multi-account-timeline-liker': 'Multi-Account Timeline Liker',- 'tweet-price-correlation': 'Tweet Price Correlation',- 'thought-leader-cultivator': 'Thought Leader Cultivator',- 'viral-tweets-scraper': 'Viral Tweets Scraper',- 'auto-engage': 'Auto-Engage',- 'premium-features': 'Premium Features',- // automation framework- 'automation-actions': 'Automation Actions Library',- 'automation-algorithm-builder': 'Automation Algorithm Builder',- 'automation-algorithm-trainer': 'Automation Algorithm Trainer',- 'automation-auto-commenter': 'Automation Auto-Commenter',- 'automation-auto-liker': 'Automation Auto-Liker',- 'automation-control-panel': 'Automation Control Panel',- 'automation-customer-service': 'Automation Customer Service Bot',- 'automation-evergreen-recycler': 'Evergreen Content Recycler',- 'automation-follow-target-users': 'Automation Follow Target Users',- 'automation-protect-active-users': 'Protect Active Users',- 'automation-quota-supervisor': 'Rate Limit & Quota Supervisor',- 'automation-rss-monitor': 'RSS Monitor & Auto-Tweet',- 'automation-session-logger': 'Session Logger',- 'automation-smart-unfollow': 'Automation Smart Unfollow',- };- return titleMap[slug] || slug.replace(/-/g, ' ').replace(/\b\w/g, c => c.toUpperCase());-}--// Category + icon + page info for each script-const SCRIPT_META = {- // ── src/ scripts missing docs ──- 'account-health-monitor': { cat: 'Analytics', icon: '🏥', page: 'x.com/YOUR_USERNAME', desc: 'Comprehensive health check for your X/Twitter account. Generates a composite health score (0-100) across engagement, growth, content quality, and risk factors.', srcFile: 'src/accountHealthMonitor.js' },- 'algorithm-builder': { cat: 'Growth', icon: '🧠', page: 'x.com (any page)', desc: 'Automated account growth engine that trains the X algorithm for your niche. Likes, follows, engages, and browses to shape your For You feed over time.', srcFile: 'src/algorithmBuilder.js' },- 'article-publisher': { cat: 'Posting', icon: '📰', page: 'x.com/compose/article', desc: 'Publish long-form articles on X/Twitter (requires Premium+ subscription). Automates article creation, formatting, and publishing.', srcFile: 'src/articlePublisher.js' },- 'audience-demographics': { cat: 'Analytics', icon: '📊', page: 'x.com/YOUR_USERNAME/followers', desc: 'Analyze your follower demographics including bio keywords, locations, account age, and interests. Exports a demographic report.', srcFile: 'src/audienceDemographics.js' },- 'audience-overlap': { cat: 'Analytics', icon: '🔗', page: 'x.com (any profile)', desc: 'Compare the follower lists of two accounts to find audience overlap. Useful for finding collab partners and competitor analysis.', srcFile: 'src/audienceOverlap.js' },- 'auto-plug-replies': { cat: 'Engagement', icon: '🔌', page: 'x.com/search or timeline', desc: 'Automatically reply to viral tweets with your own content plug or CTA. Targets high-engagement tweets in your niche.', srcFile: 'src/autoPlugReplies.js' },- 'auto-reply': { cat: 'Engagement', icon: '💬', page: 'x.com/search or timeline', desc: 'Auto-reply to tweets matching your filters. Configure keywords, users, and reply templates for automated engagement.', srcFile: 'src/autoReply.js' },- 'bookmark-manager': { cat: 'Bookmarks', icon: '📚', page: 'x.com/i/bookmarks', desc: 'Full bookmark management: save, remove, organize, export, and search through your bookmarked tweets.', srcFile: 'src/bookmarkManager.js' },- 'bulk-delete-tweets': { cat: 'Content Cleanup', icon: '🗑️', page: 'x.com/YOUR_USERNAME', desc: 'Mass delete your tweets by age, keyword, engagement threshold, or date range. Keeps your profile clean.', srcFile: 'src/bulkDeleteTweets.js' },- 'business-tools': { cat: 'Business', icon: '💼', page: 'x.com (any page)', desc: 'Brand monitoring, competitor analysis, and audience insights for business accounts. Tracks mentions, sentiment, and share of voice.', srcFile: 'src/businessTools.js' },- 'content-calendar': { cat: 'Posting', icon: '📅', page: 'x.com (any page)', desc: 'Plan and visualize your posting schedule. Identifies content gaps, optimal posting times, and helps maintain consistency.', srcFile: 'src/contentCalendar.js' },- 'content-repurposer': { cat: 'Posting', icon: '♻️', page: 'x.com/YOUR_USERNAME', desc: 'Transform your existing content: turn single tweets into threads, threads into singles, add hooks, rewrite for different audiences.', srcFile: 'src/contentRepurposer.js' },- 'continuous-monitor': { cat: 'Monitoring', icon: '🔄', page: 'x.com/YOUR_USERNAME/followers', desc: 'Auto-refresh monitoring for follower/following changes. Runs continuously and alerts you to any changes in real-time.', srcFile: 'src/continuousMonitor.js' },- 'creator-studio': { cat: 'Business', icon: '🎨', page: 'x.com/settings/monetization', desc: 'Creator analytics dashboard: track subscriptions, tips, Super Follows revenue, and audience growth metrics.', srcFile: 'src/creatorStudio.js' },- 'dm-manager': { cat: 'Messaging', icon: '✉️', page: 'x.com/messages', desc: 'Full DM management: send messages, export conversations, manage message requests, and bulk operations.', srcFile: 'src/dmManager.js' },- 'engagement-booster': { cat: 'Engagement', icon: '🚀', page: 'x.com (target profile)', desc: 'Systematically engage with target accounts by liking, bookmarking, and retweeting their content to build relationships.', srcFile: 'src/engagementBooster.js' },- 'engagement-leaderboard': { cat: 'Analytics', icon: '🏆', page: 'x.com/YOUR_USERNAME', desc: 'Analyze who engages most with your tweets. Ranks your top supporters by likes, replies, retweets, and total interactions.', srcFile: 'src/engagementLeaderboard.js' },- 'engagement-manager': { cat: 'Engagement', icon: '⚡', page: 'x.com (any page)', desc: 'All-in-one engagement toolkit: like, unlike, reply, bookmark, and manage interactions from a single interface.', srcFile: 'src/engagementManager.js' },- 'follow-ratio-manager': { cat: 'Growth', icon: '⚖️', page: 'x.com/YOUR_USERNAME', desc: 'Monitor and optimize your follower/following ratio. Suggests accounts to unfollow to maintain a healthy ratio.', srcFile: 'src/followRatioManager.js' },- 'follower-growth-tracker': { cat: 'Analytics', icon: '📈', page: 'x.com/YOUR_USERNAME', desc: 'Track your follower count over time. Creates snapshots and shows growth rate, daily changes, and trend direction.', srcFile: 'src/followerGrowthTracker.js' },- 'grok-integration': { cat: 'AI', icon: '🧠', page: 'x.com/i/grok', desc: 'Interact with X\'s built-in Grok AI assistant programmatically. Send prompts, collect responses, and automate AI-powered analysis.', srcFile: 'src/grokIntegration.js' },- 'keyword-monitor': { cat: 'Monitoring', icon: '🔑', page: 'x.com/search', desc: 'Monitor search results and timelines for specific keyword mentions. Alerts you when target keywords appear in new tweets.', srcFile: 'src/keywordMonitor.js' },- 'manage-muted-words': { cat: 'Safety', icon: '🔇', page: 'x.com/settings/muted_keywords', desc: 'Bulk add, remove, and manage muted words and phrases. Filter out unwanted content from your timeline.', srcFile: 'src/manageMutedWords.js' },- 'mass-block': { cat: 'Safety', icon: '🚫', page: 'x.com (any page)', desc: 'Block multiple accounts at once from a list or timeline. Protect your account from spam, bots, and unwanted interactions.', srcFile: 'src/massBlock.js' },- 'mass-unblock': { cat: 'Safety', icon: '🔓', page: 'x.com/settings/blocked', desc: 'Unblock all or selected users from your block list. Clean up old blocks in bulk.', srcFile: 'src/massUnblock.js' },- 'mute-by-keywords': { cat: 'Safety', icon: '🔕', page: 'x.com (any page)', desc: 'Mute users whose posts contain specific keywords. Automatically filters noisy accounts from your timeline.', srcFile: 'src/muteByKeywords.js' },- 'notification-manager': { cat: 'Notifications', icon: '🔔', page: 'x.com/notifications', desc: 'Scrape, filter, and manage your notifications. Export notification history and set up custom filters.', srcFile: 'src/notificationManager.js' },- 'persona-engine': { cat: 'Growth', icon: '🎭', page: 'x.com (any page)', desc: 'Define and manage persona configurations for the algorithm builder. Create niche-specific engagement profiles.', srcFile: 'src/personaEngine.js' },- 'pin-tweet-manager': { cat: 'Posting', icon: '📌', page: 'x.com/YOUR_USERNAME', desc: 'Pin and unpin tweets programmatically. Auto-rotate your pinned tweet based on performance or schedule.', srcFile: 'src/pinTweetManager.js' },- 'poll-creator': { cat: 'Posting', icon: '📊', page: 'x.com/compose/post', desc: 'Create and manage poll tweets. Configure options, duration, and track poll results programmatically.', srcFile: 'src/pollCreator.js' },- 'post-composer': { cat: 'Posting', icon: '✏️', page: 'x.com/compose/post', desc: 'Full content creation suite: compose tweets, threads, polls, and articles with templates and scheduling.', srcFile: 'src/postComposer.js' },- 'premium-manager': { cat: 'Premium', icon: '⭐', page: 'x.com/settings/premium', desc: 'Check your Premium subscription tier and available features. Manage Premium-specific settings and capabilities.', srcFile: 'src/premiumManager.js' },- 'profile-manager': { cat: 'Account', icon: '👤', page: 'x.com/settings/profile', desc: 'Full profile management: update name, bio, avatar, header image, location, website, and verification settings.', srcFile: 'src/profileManager.js' },- 'quote-tweet-automation': { cat: 'Engagement', icon: '🔁', page: 'x.com/search or timeline', desc: 'Auto-retweet with quote-tweet templates. Add your commentary to trending content automatically.', srcFile: 'src/quoteTweetAutomation.js' },- 'sentiment-analyzer': { cat: 'Analytics', icon: '🧠', page: 'x.com (any timeline)', desc: 'Analyze tweet sentiment (positive/negative/neutral) using lexicon-based scoring. Shows trends, toxicity flags, and emotional distribution.', srcFile: 'src/sentimentAnalyzer.js' },- 'settings-manager': { cat: 'Account', icon: '⚙️', page: 'x.com/settings', desc: 'Manage account security, privacy, and preference settings. Bulk-update notification, display, and privacy options.', srcFile: 'src/settingsManager.js' },- 'shadowban-checker': { cat: 'Analytics', icon: '👻', page: 'x.com/YOUR_USERNAME', desc: 'Check if your account is shadowbanned. Tests search visibility, reply visibility, and ghost ban status.', srcFile: 'src/shadowbanChecker.js' },- 'spaces-manager': { cat: 'Spaces', icon: '🎙️', page: 'x.com/i/spaces', desc: 'Manage Twitter Spaces: find, join, schedule, and monitor live audio rooms and events.', srcFile: 'src/spacesManager.js' },- 'thread-composer': { cat: 'Posting', icon: '🧵', page: 'x.com/compose/post', desc: 'Compose and publish multi-tweet threads with draft support, character counting, and preview.', srcFile: 'src/threadComposer.js' },- 'trending-topic-monitor': { cat: 'Monitoring', icon: '📈', page: 'x.com/explore', desc: 'Monitor trending topics in real-time. Track topic velocity, tweet volume, and sentiment for any trend.', srcFile: 'src/trendingTopicMonitor.js' },- 'tweet-ab-tester': { cat: 'Analytics', icon: '🧪', page: 'x.com/YOUR_USERNAME', desc: 'A/B test tweet variations and track which performs best. Compare engagement rates across different wording, hashtags, and posting times.', srcFile: 'src/tweetABTester.js' },- 'tweet-performance': { cat: 'Analytics', icon: '📊', page: 'x.com/YOUR_USERNAME', desc: 'Compare your recent tweets side-by-side. Analyze engagement rates, impressions, and identify content patterns that work.', srcFile: 'src/tweetPerformance.js' },- 'tweet-schedule-optimizer': { cat: 'Analytics', icon: '⏰', page: 'x.com/YOUR_USERNAME', desc: 'Analyze your posting history to find optimal posting times. Shows engagement by day of week and hour.', srcFile: 'src/tweetScheduleOptimizer.js' },- 'unfollow-wdfb-log': { cat: 'Unfollow', icon: '📋', page: 'x.com/YOUR_USERNAME/following', desc: 'Unfollow non-followers with comprehensive logging. Exports a detailed report of who was unfollowed and why.', srcFile: 'src/unfollowWDFBLog.js' },- 'viral-tweet-detector': { cat: 'Analytics', icon: '🔥', page: 'x.com (any timeline)', desc: 'Scan your timeline to identify viral tweets. Detects high-engagement content based on likes, retweets, and reply ratios.', srcFile: 'src/viralTweetDetector.js' },- 'welcome-new-followers': { cat: 'Engagement', icon: '👋', page: 'x.com/YOUR_USERNAME/followers', desc: 'Auto-send welcome DMs to new followers. Customizable templates with personalization tokens.', srcFile: 'src/welcomeNewFollowers.js' },-- // ── scripts/-only (not in src/) ──- 'scrape-profile-with-replies': { cat: 'Scrapers', icon: '👤', page: 'x.com/USERNAME/with_replies', desc: 'Scrape a profile\'s tweets AND replies. Exports full conversation history including quoted tweets.', srcFile: 'scripts/scrape-profile-with-replies.js' },- 'scrape-analytics': { cat: 'Scrapers', icon: '📊', page: 'x.com/YOUR_USERNAME', desc: 'Scrape your account and post analytics. Extracts impressions, engagement rates, and audience data.', srcFile: 'scripts/scrapeAnalytics.js' },- 'scrape-bookmarks': { cat: 'Scrapers', icon: '🔖', page: 'x.com/i/bookmarks', desc: 'Scrape all your bookmarked tweets. Exports bookmarks with full metadata to JSON/CSV.', srcFile: 'scripts/scrapeBookmarks.js' },- 'scrape-cashtag-search': { cat: 'Scrapers', icon: '💲', page: 'x.com/search?q=$TICKER', desc: 'Scrape cashtag search results with sentiment analysis. Track stock/crypto ticker mentions and market sentiment.', srcFile: 'scripts/scrapeCashtagSearch.js' },- 'scrape-dms': { cat: 'Scrapers', icon: '✉️', page: 'x.com/messages', desc: 'Export your DM conversations. Scrapes message history with timestamps, sender info, and media attachments.', srcFile: 'scripts/scrapeDMs.js' },- 'scrape-explore': { cat: 'Scrapers', icon: '🔍', page: 'x.com/explore', desc: 'Scrape the Explore page trends and content. Collects trending topics, hashtags, and promoted content.', srcFile: 'scripts/scrapeExplore.js' },- 'scrape-followers': { cat: 'Scrapers', icon: '👥', page: 'x.com/USERNAME/followers', desc: 'Export a complete followers list to JSON/CSV. Includes name, bio, follower count, and verification status.', srcFile: 'scripts/scrapeFollowers.js' },- 'scrape-following': { cat: 'Scrapers', icon: '👥', page: 'x.com/USERNAME/following', desc: 'Export the full following list to JSON/CSV. See every account you follow with their metadata.', srcFile: 'scripts/scrapeFollowing.js' },- 'scrape-hashtag': { cat: 'Scrapers', icon: '#️⃣', page: 'x.com/search?q=%23hashtag', desc: 'Scrape tweets containing a specific hashtag. Collects tweet text, engagement, and author info.', srcFile: 'scripts/scrapeHashtag.js' },- 'scrape-likers': { cat: 'Scrapers', icon: '❤️', page: 'x.com/USERNAME/status/ID/likes', desc: 'Get all users who liked a specific tweet. Export likers list with profile metadata.', srcFile: 'scripts/scrapeLikers.js' },- 'scrape-likes': { cat: 'Scrapers', icon: '❤️', page: 'x.com/USERNAME/likes', desc: 'Export your liked tweets to JSON/CSV. See your full like history with engagement data.', srcFile: 'scripts/scrapeLikes.js' },- 'scrape-list': { cat: 'Scrapers', icon: '📝', page: 'x.com/i/lists/LIST_ID/members', desc: 'Scrape all members from a public Twitter list. Exports member profiles with metadata.', srcFile: 'scripts/scrapeList.js' },- 'scrape-media': { cat: 'Scrapers', icon: '🖼️', page: 'x.com/USERNAME/media', desc: 'Download all images and videos from a profile\'s media tab. Saves media files with metadata.', srcFile: 'scripts/scrapeMedia.js' },- 'scrape-notifications': { cat: 'Scrapers', icon: '🔔', page: 'x.com/notifications', desc: 'Export your notification history. Scrapes likes, retweets, follows, and mentions with timestamps.', srcFile: 'scripts/scrapeNotifications.js' },- 'scrape-profile': { cat: 'Scrapers', icon: '👤', page: 'x.com/USERNAME', desc: 'Get detailed profile data for any user. Extracts bio, stats, links, verification, and header images.', srcFile: 'scripts/scrapeProfile.js' },- 'scrape-quote-retweets': { cat: 'Scrapers', icon: '🔁', page: 'x.com/USERNAME/status/ID/retweets', desc: 'Get all quote retweets of a specific tweet. See how people are commenting on shared content.', srcFile: 'scripts/scrapeQuoteRetweets.js' },- 'scrape-replies': { cat: 'Scrapers', icon: '💬', page: 'x.com/USERNAME/status/ID', desc: 'Scrape all replies to a specific tweet. Export conversation threads with engagement data.', srcFile: 'scripts/scrapeReplies.js' },- 'scrape-search': { cat: 'Scrapers', icon: '🔍', page: 'x.com/search?q=keyword', desc: 'Search and export tweets by keyword. Supports advanced search operators and date filtering.', srcFile: 'scripts/scrapeSearch.js' },- 'export-to-csv': { cat: 'Utilities', icon: '📄', page: 'x.com (any page)', desc: 'Generic CSV export tool. Convert any scraped data array to downloadable CSV format.', srcFile: 'scripts/exportToCSV.js' },- 'dm-exporter': { cat: 'Messaging', icon: '📤', page: 'x.com/messages', desc: 'Export DM conversations with full message details. Includes timestamps, read receipts, and media links.', srcFile: 'scripts/dmExporter.js' },- 'manage-bookmarks': { cat: 'Bookmarks', icon: '📑', page: 'x.com/i/bookmarks', desc: 'Manage bookmarks via the browser UI. Add, remove, and organize bookmarks with bulk operations.', srcFile: 'scripts/manageBookmarks.js' },- 'manage-lists': { cat: 'Lists', icon: '📝', page: 'x.com/YOUR_USERNAME/lists', desc: 'Manage X Lists: create, edit, delete lists and add/remove members in bulk.', srcFile: 'scripts/manageLists.js' },- 'manage-notifications': { cat: 'Notifications', icon: '🔔', page: 'x.com/settings/notifications', desc: 'Configure notification preferences. Bulk-update which notifications you receive and how.', srcFile: 'scripts/manageNotifications.js' },- 'manage-settings': { cat: 'Account', icon: '⚙️', page: 'x.com/settings', desc: 'Manage account settings: privacy, security, display, and accessibility options.', srcFile: 'scripts/manageSettings.js' },- 'publish-article': { cat: 'Posting', icon: '📰', page: 'x.com/compose/article', desc: 'Publish articles on X (requires Premium+). Simplified article creation and formatting.', srcFile: 'scripts/publishArticle.js' },- 'edit-profile': { cat: 'Account', icon: '✏️', page: 'x.com/settings/profile', desc: 'Update profile fields via the settings page. Change name, bio, location, website, and more.', srcFile: 'scripts/editProfile.js' },- 'business-analytics': { cat: 'Business', icon: '💼', page: 'x.com (any page)', desc: 'Brand monitoring and sentiment analysis for businesses. Track mentions, engagement trends, and audience sentiment.', srcFile: 'scripts/businessAnalytics.js' },- 'keyword-liker': { cat: 'Engagement', icon: '❤️', page: 'x.com/search?q=keyword', desc: 'Like posts matching specific keywords. Enter keywords via a UI prompt and auto-like matching tweets.', srcFile: 'scripts/keywordLiker.js' },- 'multi-account-timeline-liker': { cat: 'Engagement', icon: '❤️', page: 'x.com (any profile)', desc: 'Like the entire timeline of multiple accounts. Mass-engage with content from a list of users.', srcFile: 'scripts/multiAccountTimelineLiker.js' },- 'tweet-price-correlation': { cat: 'Analytics', icon: '💹', page: 'x.com (any page)', desc: 'Correlate tweet frequency with token/stock price movements. Track if social activity predicts price action.', srcFile: 'scripts/tweetPriceCorrelation.js' },- 'thought-leader-cultivator': { cat: 'Growth', icon: '🧠', page: 'x.com (any page)', desc: 'Train the X algorithm for your niche by simulating natural browsing. Reads, likes, and bookmarks niche content to optimize your For You feed.', srcFile: 'scripts/thoughtLeaderCultivator.js' },- 'viral-tweets-scraper': { cat: 'Scrapers', icon: '🔥', page: 'x.com/search', desc: 'Find top-performing tweets in any niche. Scrapes viral content sorted by engagement metrics.', srcFile: 'scripts/viralTweetsScraper.js' },- 'auto-engage': { cat: 'Engagement', icon: '⚡', page: 'x.com (any page)', desc: 'All-in-one auto-engagement: like, reply, bookmark, and retweet matching content in a single script.', srcFile: 'scripts/autoEngage.js' },-};--// ── Doc Template ──────────────────────────────────────────────--function extractScriptInfo(filePath) {- try {- const content = fs.readFileSync(filePath, 'utf-8');-- // Extract CONFIG object keys and values- const configMatch = content.match(/const\s+CONFIG\s*=\s*\{([^}]+(?:\{[^}]*\}[^}]*)*)\}/s);- let configLines = [];- if (configMatch) {- const configBlock = configMatch[1];- const lines = configBlock.split('\n').filter(l => l.trim() && !l.trim().startsWith('//') && !l.trim().startsWith('*'));- configLines = lines.map(l => l.trim()).filter(l => l.includes(':'));- }-- // Check for CLI/MCP variants- const hasCLI = content.includes('xactions') || content.includes('CLI');- const hasMCP = content.includes('MCP') || content.includes('mcp');-- return { configLines, hasCLI, hasMCP, content };- } catch {- return { configLines: [], hasCLI: false, hasMCP: false, content: '' };- }-}--function generateDoc(slug, meta) {- const title = slugToTitle(slug);- const filePath = path.join(ROOT, meta.srcFile);- const info = extractScriptInfo(filePath);-- // Build config table- let configSection = '';- if (info.configLines.length > 0) {- configSection = `-## ⚙️ Configuration--| Setting | Default | Description |-|---------|---------|-------------|-`;- for (const line of info.configLines.slice(0, 15)) {- const match = line.match(/(\w+)\s*:\s*(.+?)(?:,\s*$|$)/);- if (match) {- const key = match[1];- let val = match[2].trim().replace(/,\s*$/, '');- // Extract inline comment as description- const commentMatch = val.match(/(.+?)\s*\/\/\s*(.+)/);- let desc = key.replace(/([A-Z])/g, ' $1').replace(/_/g, ' ').trim().toLowerCase().replace(/^\w/, c => c.toUpperCase());- if (commentMatch) {- val = commentMatch[1].trim();- desc = commentMatch[2].trim();- }- configSection += `| \`${key}\` | \`${val}\` | ${desc} |\n`;- }- }- }-- // Determine which page to navigate to- const navPage = meta.page || 'x.com';-- // Build the tutorial section- const tutorialSteps = `-## 📖 Step-by-Step Tutorial--### Step 1: Navigate to the right page--Open your browser and go to \`${navPage}\`. Make sure you're logged in to your X/Twitter account.--### Step 2: Open the browser console--- **Chrome/Edge:** Press \`F12\` or \`Ctrl+Shift+J\` (Mac: \`Cmd+Option+J\`)-- **Firefox:** Press \`F12\` or \`Ctrl+Shift+K\`-- **Safari:** Enable Developer menu in Preferences → Advanced, then press \`Cmd+Option+C\`--### Step 3: Paste the script--Copy the entire script from [\`${meta.srcFile}\`](https://github.com/nirholas/XActions/blob/main/${meta.srcFile}) and paste it into the console.--### Step 4: Customize the CONFIG (optional)--Before running, you can modify the \`CONFIG\` object at the top of the script to adjust behavior:--\`\`\`javascript-const CONFIG = {- // Edit these values before running- // See Configuration table above for all options-};-\`\`\`--### Step 5: Run and monitor--Press **Enter** to run the script. Watch the console for real-time progress logs:--- ✅ Green messages = success-- 🔄 Blue messages = in progress-- ⚠️ Yellow messages = warnings-- ❌ Red messages = errors--### Step 6: Export results--Most scripts automatically download results as JSON/CSV when complete. Check your Downloads folder.`;-- const doc = `# ${meta.icon} ${title}--${meta.desc}-------## 📋 What It Does--This script provides the following capabilities:--1. **Automated operation** — Runs directly in your browser console on x.com-2. **Configurable settings** — Customize behavior via the CONFIG object-3. **Real-time progress** — Shows live status updates with emoji-coded logs-4. **Rate limiting** — Built-in delays to respect X/Twitter's rate limits-5. **Data export** — Results exported as JSON/CSV for further analysis--**Use cases:**-- ${meta.desc}-- Automate repetitive ${meta.cat.toLowerCase()} tasks on X/Twitter-- Save time with one-click automation — no API keys needed-- Works in any modern browser (Chrome, Firefox, Edge, Safari)-------## ⚠️ Important Notes--> **Use responsibly!** All automation should respect X/Twitter's Terms of Service. Use conservative settings and include breaks between sessions.--- This script runs in the **browser DevTools console** — not Node.js-- You must be **logged in** to x.com for the script to work-- Start with **low limits** and increase gradually-- Include **random delays** between actions to appear human-- **Don't run** multiple automation scripts simultaneously-------## 🌐 Browser Console Usage--**Steps:**-1. Go to \`${navPage}\`-2. Open browser console (\`F12\` → Console tab)-3. Copy and paste the script from [\`${meta.srcFile}\`](https://github.com/nirholas/XActions/blob/main/${meta.srcFile})-4. Press Enter to run--\`\`\`javascript-${info.content}-\`\`\`-${configSection}-----${tutorialSteps}-------## 🖥️ CLI Usage--You can also run this via the XActions CLI:--\`\`\`bash-# Install XActions globally-npm install -g xactions--# Run via CLI-xactions --help-\`\`\`-------## 🤖 MCP Server Usage--Use with AI agents (Claude, Cursor, etc.) via the MCP server:--\`\`\`bash-# Start MCP server-npm run mcp-\`\`\`--See the [MCP Setup Guide](../mcp-setup.md) for integration with Claude Desktop, Cursor, and other AI tools.-------## 📁 Source Files--| File | Description |-|------|-------------|-| [\`${meta.srcFile}\`](https://github.com/nirholas/XActions/blob/main/${meta.srcFile}) | Main script |-------## 🔗 Related Scripts--| Script | Description |-|--------|-------------|-${getRelatedLinks(slug, meta.cat)}-------> **Author:** nich ([@nichxbt](https://x.com/nichxbt)) — [XActions on GitHub](https://github.com/nirholas/XActions)-`;-- return doc;-}--function getRelatedLinks(currentSlug, category) {- const related = Object.entries(SCRIPT_META)- .filter(([slug, m]) => m.cat === category && slug !== currentSlug)- .slice(0, 5)- .map(([slug]) => {- const title = slugToTitle(slug);- return `| [${title}](${slug}.md) | ${SCRIPT_META[slug].desc.split('.')[0]} |`;- });-- if (related.length === 0) {- return '| See [all scripts](README.md) | Browse the complete script catalog |';- }- return related.join('\n');-}--// ── Main ──────────────────────────────────────────────────────--function main() {- // Get existing docs- const existingDocs = new Set(- fs.readdirSync(DOCS_DIR)- .filter(f => f.endsWith('.md') && f !== 'README.md')- .map(f => f.replace('.md', ''))- );-- console.log(`📚 Found ${existingDocs.size} existing docs`);-- let created = 0;- let skipped = 0;-- for (const [slug, meta] of Object.entries(SCRIPT_META)) {- if (existingDocs.has(slug)) {- // Regenerate if it still has the old placeholder (no real code embedded)- const existing = fs.readFileSync(path.join(DOCS_DIR, `${slug}.md`), 'utf-8');- if (!existing.includes('Quick start — copy the full script from')) {- skipped++;- continue;- }- }-- // Verify source file exists- const srcPath = path.join(ROOT, meta.srcFile);- if (!fs.existsSync(srcPath)) {- console.log(`⚠️ Source not found: ${meta.srcFile} — skipping ${slug}`);- continue;- }-- const doc = generateDoc(slug, meta);- const outPath = path.join(DOCS_DIR, `${slug}.md`);- fs.writeFileSync(outPath, doc, 'utf-8');- console.log(`✅ Created: ${slug}.md`);- created++;- }-- console.log('');- console.log(`📊 Summary: ${created} created, ${skipped} already existed`);- console.log(`📁 Total docs: ${existingDocs.size + created}`);-}--main();diff --git a/xactions/scripts/generate-seo-articles-2.js b/xactions/scripts/generate-seo-articles-2.jsdeleted file mode 100644index 04f71e214..000000000--- a/xactions/scripts/generate-seo-articles-2.js+++ /dev/null@@ -1,2367 +0,0 @@-import { writeFileSync, mkdirSync } from 'fs';-import { join } from 'path';--const OUT = '/workspaces/XActions/docs/seo-articles';-mkdirSync(OUT, { recursive: true });--const articles = [- {- slug: 'crypto-trading-bot-api-guide',- title: 'Building a Crypto Trading Bot with APIs (2026)',- meta: 'Learn how to build an automated crypto trading bot using exchange APIs. Covers strategy implementation, order management, risk controls, and backtesting.',- keywords: 'crypto trading bot API, automated trading API, algorithmic trading crypto, trading bot Binance, crypto bot development',- content: `# Building a Crypto Trading Bot with APIs (2026)--Automated trading bots execute strategies 24/7 without emotion. This guide covers building a production-grade bot using exchange APIs.--## Architecture--\`\`\`-Market Data (WebSocket) → Strategy Engine → Signal Generator → Order Manager → Exchange API- ↑- Risk Manager-\`\`\`--## Market Data Feed--\`\`\`javascript-class MarketDataFeed {- constructor(symbol, interval = '1m') {- this.symbol = symbol.toLowerCase();- this.candles = [];- this.connect(interval);- }-- connect(interval) {- this.ws = new WebSocket(- \`wss://stream.binance.com:9443/ws/\${this.symbol}@kline_\${interval}\`- );-- this.ws.onmessage = ({ data }) => {- const { k: candle } = JSON.parse(data);- if (candle.x) { // candle closed- this.candles.push({- open: parseFloat(candle.o),- high: parseFloat(candle.h),- low: parseFloat(candle.l),- close: parseFloat(candle.c),- volume: parseFloat(candle.v),- timestamp: candle.T- });- if (this.candles.length > 200) this.candles.shift();- this.onCandle?.(this.candles);- }- };-- this.ws.onclose = () => setTimeout(() => this.connect(interval), 3000);- }-}-\`\`\`--## Simple Moving Average Strategy--\`\`\`javascript-function smaStrategy(candles, fastPeriod = 10, slowPeriod = 20) {- if (candles.length < slowPeriod) return 'hold';-- const closes = candles.map(c => c.close);- const fast = closes.slice(-fastPeriod).reduce((a, b) => a + b) / fastPeriod;- const slow = closes.slice(-slowPeriod).reduce((a, b) => a + b) / slowPeriod;-- const prevFast = closes.slice(-fastPeriod - 1, -1).reduce((a, b) => a + b) / fastPeriod;- const prevSlow = closes.slice(-slowPeriod - 1, -1).reduce((a, b) => a + b) / slowPeriod;-- if (prevFast <= prevSlow && fast > slow) return 'buy';- if (prevFast >= prevSlow && fast < slow) return 'sell';- return 'hold';-}-\`\`\`--## RSI Indicator--\`\`\`javascript-function calculateRSI(closes, period = 14) {- const changes = closes.slice(1).map((c, i) => c - closes[i]);- const gains = changes.map(c => Math.max(c, 0));- const losses = changes.map(c => Math.max(-c, 0));-- const avgGain = gains.slice(-period).reduce((a, b) => a + b) / period;- const avgLoss = losses.slice(-period).reduce((a, b) => a + b) / period;-- if (avgLoss === 0) return 100;- const rs = avgGain / avgLoss;- return 100 - (100 / (1 + rs));-}-\`\`\`--## Order Manager--\`\`\`javascript-import crypto from 'crypto';--class OrderManager {- constructor(apiKey, secret, baseUrl = 'https://api.binance.com') {- this.apiKey = apiKey;- this.secret = secret;- this.baseUrl = baseUrl;- }-- sign(params) {- const query = new URLSearchParams(params).toString();- const sig = crypto.createHmac('sha256', this.secret).update(query).digest('hex');- return \`\${query}&signature=\${sig}\`;- }-- async placeOrder(symbol, side, quantity, price = null) {- const params = {- symbol,- side: side.toUpperCase(),- type: price ? 'LIMIT' : 'MARKET',- quantity: quantity.toFixed(5),- timestamp: Date.now(),- ...(price && { price: price.toFixed(2), timeInForce: 'GTC' })- };-- const res = await fetch(\`\${this.baseUrl}/api/v3/order?\${this.sign(params)}\`, {- method: 'POST',- headers: { 'X-MBX-APIKEY': this.apiKey }- });- return res.json();- }-}-\`\`\`--## Risk Manager--\`\`\`javascript-class RiskManager {- constructor({ maxPositionPct = 0.1, stopLossPct = 0.02, maxDailyLoss = 0.05 }) {- this.maxPositionPct = maxPositionPct;- this.stopLossPct = stopLossPct;- this.maxDailyLoss = maxDailyLoss;- this.dailyPnl = 0;- this.positions = new Map();- }-- canTrade() {- return this.dailyPnl > -this.maxDailyLoss;- }-- positionSize(accountBalance, price) {- return (accountBalance * this.maxPositionPct) / price;- }-- shouldStopLoss(entryPrice, currentPrice, side) {- const pnlPct = side === 'buy'- ? (currentPrice - entryPrice) / entryPrice- : (entryPrice - currentPrice) / entryPrice;- return pnlPct < -this.stopLossPct;- }-}-\`\`\`--## Full Bot Loop--\`\`\`javascript-const feed = new MarketDataFeed('BTCUSDT', '5m');-const orders = new OrderManager(process.env.BINANCE_KEY, process.env.BINANCE_SECRET);-const risk = new RiskManager({ maxPositionPct: 0.05, stopLossPct: 0.015 });--let position = null;--feed.onCandle = async (candles) => {- if (!risk.canTrade()) return;-- const signal = smaStrategy(candles);- const closes = candles.map(c => c.close);- const rsi = calculateRSI(closes);- const price = closes[closes.length - 1];-- if (signal === 'buy' && rsi < 65 && !position) {- const qty = risk.positionSize(1000, price);- const order = await orders.placeOrder('BTCUSDT', 'buy', qty);- position = { side: 'buy', entryPrice: price, orderId: order.orderId };- }-- if (position && (signal === 'sell' || risk.shouldStopLoss(position.entryPrice, price, position.side))) {- await orders.placeOrder('BTCUSDT', 'sell', position.qty);- position = null;- }-};-\`\`\``- },- {- slug: 'bitcoin-api-guide',- title: 'Bitcoin API Guide: On-Chain Data, Wallets, and Transactions (2026)',- meta: 'How to use Bitcoin APIs — query addresses, broadcast transactions, get UTXO sets, and access mempool data using BlockCypher, Blockstream, and Electrum.',- keywords: 'Bitcoin API, Bitcoin RPC API, Bitcoin transaction API, BlockCypher API, Bitcoin developer API',- content: `# Bitcoin API Guide: On-Chain Data, Wallets, and Transactions (2026)--Bitcoin has its own RPC and REST API ecosystem, separate from Ethereum. This guide covers the main options for querying Bitcoin on-chain data and building Bitcoin applications.--## Option 1: Blockstream.info (Free, No Key)--\`\`\`javascript-const BASE = 'https://blockstream.info/api';--// Address info-const addr = await fetch(\`\${BASE}/address/bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh\`).then(r => r.json());-console.log('Balance:', addr.chain_stats.funded_txo_sum - addr.chain_stats.spent_txo_sum, 'satoshis');--// UTXOs-const utxos = await fetch(\`\${BASE}/address/bc1q.../utxo\`).then(r => r.json());--// Transaction-const tx = await fetch(\`\${BASE}/tx/txid\`).then(r => r.json());--// Broadcast raw transaction-await fetch(\`\${BASE}/tx\`, { method: 'POST', body: rawTxHex });--// Current fees-const fees = await fetch(\`\${BASE}/fee-estimates\`).then(r => r.json());-console.log('Next block fee:', fees[1], 'sat/vB');-\`\`\`--## Option 2: BlockCypher API--\`\`\`javascript-const token = process.env.BLOCKCYPHER_TOKEN;-const BASE = 'https://api.blockcypher.com/v1/btc/main';--// Address balance-const addr = await fetch(\`\${BASE}/addrs/bc1q.../balance?token=\${token}\`).then(r => r.json());-console.log('Final balance:', addr.final_balance);--// Create and send transaction-const newTx = await fetch(\`\${BASE}/txs/new?token=\${token}\`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- inputs: [{ addresses: ['fromAddress'] }],- outputs: [{ addresses: ['toAddress'], value: 10000 }]- })-}).then(r => r.json());-// Sign inputs, then call /txs/send-\`\`\`--## Option 3: Bitcoin Core RPC--Running your own node gives full access:--\`\`\`javascript-async function btcRpc(method, params = []) {- const res = await fetch('http://localhost:8332', {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- 'Authorization': 'Basic ' + Buffer.from(\`\${RPC_USER}:\${RPC_PASS}\`).toString('base64')- },- body: JSON.stringify({ jsonrpc: '1.0', method, params })- });- const { result, error } = await res.json();- if (error) throw new Error(error.message);- return result;-}--// Usage-const info = await btcRpc('getblockchaininfo');-const balance = await btcRpc('getreceivedbyaddress', ['bc1q...', 1]);-const txid = await btcRpc('sendtoaddress', ['bc1q...', 0.001]);-\`\`\`--## Key Bitcoin RPC Methods--| Method | Description |-|---|---|-| \`getblockchaininfo\` | Chain sync status |-| \`getblockcount\` | Current block height |-| \`getblock\` | Block data by hash |-| \`getrawtransaction\` | Raw transaction hex |-| \`decoderawtransaction\` | Parse raw tx |-| \`sendrawtransaction\` | Broadcast tx |-| \`getaddressinfo\` | Address details |-| \`listunspent\` | UTXOs for wallet |-| \`estimatesmartfee\` | Fee estimation |-| \`getmempoolinfo\` | Mempool stats |--## Fee Estimation--\`\`\`javascript-// From Bitcoin Core-const feeRate = await btcRpc('estimatesmartfee', [6]); // 6 blocks-console.log(feeRate.feerate, 'BTC/kB');--// From Mempool.space-const fees = await fetch('https://mempool.space/api/v1/fees/recommended').then(r => r.json());-console.log('Fast fee:', fees.fastestFee, 'sat/vB');-console.log('Hour fee:', fees.hourFee, 'sat/vB');-\`\`\`--## Building a Bitcoin Wallet--\`\`\`javascript-import * as bitcoin from 'bitcoinjs-lib';-import * as ecc from 'tiny-secp256k1';-import BIP32Factory from 'bip32';--const bip32 = BIP32Factory(ecc);--// Generate HD wallet-const root = bip32.fromSeed(Buffer.from(mnemonic));-const account = root.derivePath("m/84'/0'/0'"); // BIP84 native segwit-const external = account.derive(0).derive(0);--const { address } = bitcoin.payments.p2wpkh({- pubkey: external.publicKey-});-console.log('Address:', address); // bc1q...-\`\`\``- },- {- slug: 'nft-api-guide',- title: 'NFT APIs: Fetch Metadata, Floor Prices, and Ownership (2026)',- meta: 'Compare the top NFT data APIs — Alchemy, Moralis, OpenSea, Reservoir, and Simplehash. Query metadata, floor prices, owners, and transfer history.',- keywords: 'NFT API, NFT metadata API, NFT floor price API, NFT ownership API, NFT data API',- content: `# NFT APIs: Fetch Metadata, Floor Prices, and Ownership (2026)--NFT data is spread across multiple layers — on-chain ownership, off-chain metadata, and marketplace listings. These APIs unify all three.--## Alchemy NFT API--\`\`\`javascript-import { Alchemy, Network } from 'alchemy-sdk';--const alchemy = new Alchemy({ apiKey: process.env.ALCHEMY_API_KEY, network: Network.ETH_MAINNET });--// All NFTs owned by an address-const { ownedNfts } = await alchemy.nft.getNftsForOwner('0xAddress');--// NFTs in a collection-const { nfts } = await alchemy.nft.getNftsForContract('0xContractAddress');--// Floor price-const floor = await alchemy.nft.getFloorPrice('0xContractAddress');-console.log('OpenSea floor:', floor.openSea?.floorPrice, 'ETH');-console.log('LooksRare floor:', floor.looksRare?.floorPrice, 'ETH');--// Transfer history-const transfers = await alchemy.nft.getTransfersForContract('0xContractAddress');-\`\`\`--## Simplehash (Best Multi-Chain NFT API)--Simplehash covers 60+ chains with a unified API:--\`\`\`javascript-const headers = { 'X-API-KEY': process.env.SIMPLEHASH_API_KEY };--// NFTs by wallet (multi-chain)-const res = await fetch(- 'https://api.simplehash.com/api/v0/nfts/owners_v2?chains=ethereum,polygon,solana&wallet_addresses=0xAddress',- { headers }-);-const { nfts } = await res.json();--// Collection stats-const stats = await fetch(- 'https://api.simplehash.com/api/v0/nfts/collections/ethereum/0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D',- { headers }-).then(r => r.json());-console.log(stats.floor_prices);-console.log(stats.volume_usd_24h);-\`\`\`--## Reservoir Protocol--Reservoir aggregates listings from OpenSea, Blur, X2Y2, and more:--\`\`\`javascript-// Best listings for a collection-const listings = await fetch(- 'https://api.reservoir.tools/orders/asks/v5?collection=0xBC4CA0...&sortBy=price&limit=20',- { headers: { 'x-api-key': process.env.RESERVOIR_API_KEY } }-).then(r => r.json());--// Best offers-const offers = await fetch(- 'https://api.reservoir.tools/orders/bids/v6?collection=0xBC4CA0...&sortBy=price&limit=20',- { headers: { 'x-api-key': process.env.RESERVOIR_API_KEY } }-).then(r => r.json());--// Token sales history-const sales = await fetch(- 'https://api.reservoir.tools/sales/v6?collection=0xBC4CA0...&limit=20',- { headers: { 'x-api-key': process.env.RESERVOIR_API_KEY } }-).then(r => r.json());-\`\`\`--## On-Chain NFT Ownership (No API Key)--\`\`\`javascript-import { ethers } from 'ethers';--const erc721Abi = [- 'function ownerOf(uint256 tokenId) view returns (address)',- 'function tokenURI(uint256 tokenId) view returns (string)',- 'function balanceOf(address owner) view returns (uint256)'-];--const bayc = new ethers.Contract('0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D', erc721Abi, provider);--const owner = await bayc.ownerOf(1);-const tokenUri = await bayc.tokenURI(1);-const balance = await bayc.balanceOf('0xAddress');-\`\`\`--## Fetch IPFS Metadata--\`\`\`javascript-async function getNftMetadata(tokenUri) {- // Convert ipfs:// to https://- const url = tokenUri.replace('ipfs://', 'https://ipfs.io/ipfs/');- const metadata = await fetch(url).then(r => r.json());- return {- name: metadata.name,- description: metadata.description,- image: metadata.image?.replace('ipfs://', 'https://ipfs.io/ipfs/'),- attributes: metadata.attributes || []- };-}-\`\`\`--## NFT Rarity Scoring--\`\`\`javascript-function calculateRarity(traits, collectionTraits) {- return traits.reduce((score, { trait_type, value }) => {- const traitCount = collectionTraits[trait_type]?.[value] || 0;- const rarity = 1 / (traitCount / 10000); // assuming 10K supply- return score + rarity;- }, 0);-}-\`\`\``- },- {- slug: 'aave-api-guide',- title: 'Aave API Guide: DeFi Lending Data and Protocol Integration (2026)',- meta: 'How to query Aave protocol data — interest rates, positions, health factors, and liquidations — using the Aave subgraph and smart contracts.',- keywords: 'Aave API, Aave lending API, Aave subgraph, DeFi lending API, Aave V3 API',- content: `# Aave API Guide: DeFi Lending Data and Protocol Integration (2026)--Aave is the largest DeFi lending protocol. You can query rates, positions, and health factors via their subgraph, REST API, or direct smart contract calls.--## Aave Subgraph--\`\`\`javascript-const AAVE_V3_ETH = 'https://api.thegraph.com/subgraphs/name/aave/protocol-v3';--async function query(gql) {- const res = await fetch(AAVE_V3_ETH, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ query: gql })- });- return (await res.json()).data;-}--// Get all reserve data (interest rates, TVL)-const { reserves } = await query(\`{- reserves {- symbol- name- liquidityRate- variableBorrowRate- stableBorrowRate- totalDeposits- totalCurrentVariableDebt- baseLTVasCollateral- reserveLiquidationThreshold- usageAsCollateralEnabled- }-}\`);--// Format APY-reserves.forEach(r => {- const depositApy = (parseFloat(r.liquidityRate) / 1e27 * 100).toFixed(2);- const borrowApy = (parseFloat(r.variableBorrowRate) / 1e27 * 100).toFixed(2);- console.log(\`\${r.symbol}: Deposit \${depositApy}% | Borrow \${borrowApy}%\`);-});-\`\`\`--## User Positions--\`\`\`javascript-const { users } = await query(\`{- users(where: { id: "0xuseraddress" }) {- healthFactor- totalCollateralUSD- totalDebtUSD- currentLiquidationThreshold- reserves {- reserve { symbol }- currentATokenBalance- currentVariableDebt- usageAsCollateralEnabled- }- }-}\`);-\`\`\`--## Direct Contract Calls--\`\`\`javascript-import { ethers } from 'ethers';--const POOL_ADDRESS = '0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2'; // Aave V3 ETH--const poolAbi = [- 'function getUserAccountData(address user) view returns (uint256 totalCollateralBase, uint256 totalDebtBase, uint256 availableBorrowsBase, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor)',- 'function getReserveData(address asset) view returns (tuple(...))'-];--const pool = new ethers.Contract(POOL_ADDRESS, poolAbi, provider);--const accountData = await pool.getUserAccountData('0xUserAddress');-console.log('Health Factor:', ethers.formatUnits(accountData.healthFactor, 18));-console.log('Total Collateral USD:', ethers.formatUnits(accountData.totalCollateralBase, 8));-console.log('Total Debt USD:', ethers.formatUnits(accountData.totalDebtBase, 8));-\`\`\`--## Supply and Borrow--\`\`\`javascript-const USDC = '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48';-const amount = ethers.parseUnits('1000', 6); // 1000 USDC--const poolWithSigner = pool.connect(signer);--// Approve first-const usdc = new ethers.Contract(USDC, ['function approve(address,uint256)'], signer);-await usdc.approve(POOL_ADDRESS, amount);--// Supply-await poolWithSigner.supply(USDC, amount, signer.address, 0);--// Borrow (variable rate)-await poolWithSigner.borrow(USDC, amount, 2, 0, signer.address);--// Repay-await poolWithSigner.repay(USDC, amount, 2, signer.address);-\`\`\`--## Liquidation Monitoring--\`\`\`javascript-// Find positions at risk (health factor < 1.1)-const { users: atRisk } = await query(\`{- users(- where: { healthFactor_lt: "1100000000000000000" }- orderBy: healthFactor- first: 20- ) {- id- healthFactor- totalCollateralUSD- totalDebtUSD- }-}\`);-\`\`\``- },- {- slug: 'crypto-price-api-guide',- title: 'Real-Time Crypto Price APIs: Complete Comparison (2026)',- meta: 'Compare free and paid real-time cryptocurrency price APIs — CoinGecko, CoinMarketCap, Binance, Kraken, and Chainlink. Choose the best one for your use case.',- keywords: 'crypto price API, real-time crypto prices, Bitcoin price API, free crypto price API, cryptocurrency price feed',- content: `# Real-Time Crypto Price APIs: Complete Comparison (2026)--Getting accurate, real-time crypto prices is fundamental to almost every crypto app. Here's a complete comparison of the options.--## Free Options (No Credit Card)--### CoinGecko (No Key Required)--\`\`\`javascript-// Up to 30 coins in one call-const res = await fetch(- 'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,ethereum,solana&vs_currencies=usd&include_24hr_change=true&include_market_cap=true'-);-const prices = await res.json();-console.log(prices.bitcoin.usd); // current price-console.log(prices.bitcoin.usd_24h_change); // % change-\`\`\`--Rate limit: 30 calls/min on free tier.--### Binance (No Key for Public Data)--\`\`\`javascript-// Single symbol-const { price } = await fetch('https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT').then(r => r.json());--// All symbols at once (~1400+ pairs)-const allPrices = await fetch('https://api.binance.com/api/v3/ticker/price').then(r => r.json());-\`\`\`--Binance public endpoints: 1200 weight/minute, no auth required.--### Kraken (No Key for Public Data)--\`\`\`javascript-const res = await fetch('https://api.kraken.com/0/public/Ticker?pair=XBTUSD,ETHUSD');-const { result } = await res.json();-console.log(result.XXBTZUSD.c[0]); // last trade price-\`\`\`--## Paid Options--### CoinMarketCap API--\`\`\`javascript-const res = await fetch(- 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol=BTC,ETH,SOL&convert=USD',- { headers: { 'X-CMC_PRO_API_KEY': process.env.CMC_API_KEY } }-);-const { data } = await res.json();-console.log(data.BTC.quote.USD.price);-\`\`\`--Free tier: 10,000 calls/month. Includes market cap rankings not available elsewhere.--## On-Chain Price Oracles--For smart contracts that need prices on-chain, use Chainlink:--\`\`\`javascript-const aggregatorAbi = ['function latestRoundData() view returns (uint80, int256, uint256, uint256, uint80)'];-const BTC_USD_FEED = '0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88b';--const feed = new ethers.Contract(BTC_USD_FEED, aggregatorAbi, provider);-const [, price, , updatedAt] = await feed.latestRoundData();--console.log('BTC Price:', parseInt(price) / 1e8, 'USD');-console.log('Updated:', new Date(parseInt(updatedAt) * 1000));-\`\`\`--Chainlink feeds are on-chain and manipulation-resistant — required for DeFi protocols.--## Building a Price Aggregator--Average prices from multiple sources for accuracy:--\`\`\`javascript-async function getAggregatedPrice(symbol) {- const [gecko, binance, kraken] = await Promise.allSettled([- fetchCoinGeckoPrice(symbol),- fetchBinancePrice(symbol + 'USDT'),- fetchKrakenPrice(symbol + 'USD')- ]);-- const prices = [gecko, binance, kraken]- .filter(r => r.status === 'fulfilled')- .map(r => r.value);-- if (prices.length === 0) throw new Error('All price feeds failed');-- // Remove outliers (>2% from median)- const sorted = [...prices].sort((a, b) => a - b);- const median = sorted[Math.floor(sorted.length / 2)];- const filtered = prices.filter(p => Math.abs(p - median) / median < 0.02);-- return filtered.reduce((a, b) => a + b) / filtered.length;-}-\`\`\`--## Caching Strategy--\`\`\`javascript-class PriceCache {- constructor(ttlMs = 30000) {- this.cache = new Map();- this.ttl = ttlMs;- }-- get(symbol) {- const entry = this.cache.get(symbol);- if (!entry || Date.now() - entry.ts > this.ttl) return null;- return entry.price;- }-- set(symbol, price) {- this.cache.set(symbol, { price, ts: Date.now() });- }-}-\`\`\``- },- {- slug: 'chainlink-oracle-api-guide',- title: 'Chainlink Oracle API Guide: On-Chain Price Feeds (2026)',- meta: 'How to use Chainlink price feeds, VRF random numbers, and CCIP cross-chain messaging in smart contracts and off-chain applications.',- keywords: 'Chainlink API, Chainlink price feed, Chainlink oracle, Chainlink VRF, on-chain price feed',- content: `# Chainlink Oracle API Guide: On-Chain Price Feeds (2026)--Chainlink is the dominant oracle network, providing tamper-proof price feeds, verifiable randomness, and cross-chain messaging used by $50B+ in DeFi protocols.--## Price Feeds--### Read On-Chain (Smart Contract)--\`\`\`solidity-// SPDX-License-Identifier: MIT-pragma solidity ^0.8.20;--import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";--contract PriceConsumer {- AggregatorV3Interface internal priceFeed;-- constructor() {- // ETH/USD on Ethereum Mainnet- priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);- }-- function getLatestPrice() public view returns (int) {- (, int price, , , ) = priceFeed.latestRoundData();- return price / 1e8; // 8 decimals- }-}-\`\`\`--### Read Off-Chain (ethers.js)--\`\`\`javascript-const FEEDS = {- 'BTC/USD': '0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88b',- 'ETH/USD': '0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419',- 'LINK/USD': '0x2c1d072e956AFFC0D435Cb7AC38EF18d24d9127c',- 'SOL/USD': '0x4ffC43a60e009B551865A93d232E33Fce9f01507'-};--const abi = ['function latestRoundData() view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound)'];--async function getChainlinkPrice(pair) {- const feed = new ethers.Contract(FEEDS[pair], abi, provider);- const { answer, updatedAt } = await feed.latestRoundData();- return {- price: Number(answer) / 1e8,- updatedAt: new Date(Number(updatedAt) * 1000)- };-}-\`\`\`--### Historical Rounds--\`\`\`javascript-async function getHistoricalPrice(feedAddress, roundId) {- const feed = new ethers.Contract(feedAddress, abi, provider);- const { answer, startedAt } = await feed.getRoundData(roundId);- return { price: Number(answer) / 1e8, timestamp: new Date(Number(startedAt) * 1000) };-}-\`\`\`--## Chainlink VRF (Verifiable Random Function)--\`\`\`solidity-import "@chainlink/contracts/src/v0.8/vrf/VRFConsumerBaseV2Plus.sol";--contract RandomLottery is VRFConsumerBaseV2Plus {- uint256 public lastRandomWord;-- constructor(address vrfCoordinator) VRFConsumerBaseV2Plus(vrfCoordinator) {}-- function requestRandomNumber() external returns (uint256 requestId) {- return s_vrfCoordinator.requestRandomWords(- VRFV2PlusClient.RandomWordsRequest({- keyHash: 0x787d74caea10b2b357790d5b5247c2f63d1d91572a9846f780606e4d953677ae,- subId: SUBSCRIPTION_ID,- requestConfirmations: 3,- callbackGasLimit: 100000,- numWords: 1,- extraArgs: VRFV2PlusClient._argsToBytes(VRFV2PlusClient.ExtraArgsV1({ nativePayment: false }))- })- );- }-- function fulfillRandomWords(uint256, uint256[] calldata randomWords) internal override {- lastRandomWord = randomWords[0];- }-}-\`\`\`--## Chainlink CCIP (Cross-Chain)--\`\`\`solidity-import "@chainlink/contracts-ccip/src/v0.8/CCIPReceiver.sol";--contract CrossChainReceiver is CCIPReceiver {- string public lastMessage;-- function _ccipReceive(Client.Any2EVMMessage memory message) internal override {- lastMessage = abi.decode(message.data, (string));- }-}-\`\`\`--## Data Feeds Directory--All available feeds: [data.chain.link](https://data.chain.link)--Key categories:-- **Crypto/USD** — BTC, ETH, SOL, LINK, AVAX, MATIC, and 200+ more-- **Forex** — EUR/USD, GBP/USD, JPY/USD-- **Commodities** — XAU/USD (gold), XAG/USD (silver), crude oil-- **Equities** — TSLA, AAPL (on some chains)-- **Proof of Reserve** — verify exchange/bridge collateral`- },- {- slug: 'crypto-gas-fee-api-guide',- title: 'Crypto Gas Fee APIs: Estimate and Optimize Transaction Costs (2026)',- meta: 'How to fetch real-time gas prices for Ethereum, Polygon, Arbitrum, and other chains. Compare gas estimation APIs and build gas-aware applications.',- keywords: 'gas fee API, Ethereum gas price API, gas estimation API, EIP-1559 gas API, crypto transaction fee API',- content: `# Crypto Gas Fee APIs: Estimate and Optimize Transaction Costs (2026)--Gas fees are a critical UX concern for any dApp. This guide covers how to fetch accurate gas estimates, implement EIP-1559 fee strategies, and build gas-aware applications.--## Ethereum Gas (EIP-1559)--\`\`\`javascript-import { ethers } from 'ethers';--const provider = new ethers.JsonRpcProvider(process.env.ETH_RPC_URL);--// Get fee data-const feeData = await provider.getFeeData();-console.log('Base fee:', ethers.formatUnits(feeData.gasPrice, 'gwei'), 'Gwei');-console.log('Max fee:', ethers.formatUnits(feeData.maxFeePerGas, 'gwei'), 'Gwei');-console.log('Priority fee:', ethers.formatUnits(feeData.maxPriorityFeePerGas, 'gwei'), 'Gwei');--// Estimate gas for a transaction-const gasEstimate = await provider.estimateGas({- to: '0xRecipient',- value: ethers.parseEther('0.01')-});-console.log('Gas units:', gasEstimate.toString());--// Total fee estimate-const totalFee = gasEstimate * feeData.maxFeePerGas;-console.log('Max cost:', ethers.formatEther(totalFee), 'ETH');-\`\`\`--## Etherscan Gas Oracle--\`\`\`javascript-const res = await fetch(- \`https://api.etherscan.io/api?module=gastracker&action=gasoracle&apikey=\${process.env.ETHERSCAN_KEY}\`-);-const { result } = await res.json();-console.log('Safe:', result.SafeGasPrice, 'Gwei');-console.log('Propose:', result.ProposeGasPrice, 'Gwei');-console.log('Fast:', result.FastGasPrice, 'Gwei');-console.log('Base fee:', result.suggestBaseFee, 'Gwei');-\`\`\`--## Blocknative Gas API--\`\`\`javascript-const res = await fetch('https://api.blocknative.com/gasprices/blockprices', {- headers: { 'Authorization': process.env.BLOCKNATIVE_API_KEY }-});-const { blockPrices } = await res.json();-const block = blockPrices[0];--console.log('Base fee:', block.baseFeePerGas, 'Gwei');-block.estimatedPrices.forEach(p => {- console.log(\`\${p.confidence}% confident: max \${p.maxFeePerGas} / priority \${p.maxPriorityFeePerGas} Gwei\`);-});-\`\`\`--## Mempool.space (Bitcoin)--\`\`\`javascript-const fees = await fetch('https://mempool.space/api/v1/fees/recommended').then(r => r.json());-console.log('Fastest fee:', fees.fastestFee, 'sat/vB'); // ~10 min-console.log('Half hour:', fees.halfHourFee, 'sat/vB');-console.log('Hour fee:', fees.hourFee, 'sat/vB');-console.log('Economy:', fees.economyFee, 'sat/vB');-console.log('Minimum:', fees.minimumFee, 'sat/vB');-\`\`\`--## Multi-Chain Gas Comparison--\`\`\`javascript-async function getGasForChain(chainName, rpcUrl) {- const provider = new ethers.JsonRpcProvider(rpcUrl);- const feeData = await provider.getFeeData();- const ethTransferGas = 21000n;- const costInGwei = ethTransferGas * feeData.gasPrice / 1_000_000_000n;- return { chain: chainName, gweiPerGas: ethers.formatUnits(feeData.gasPrice, 'gwei'), transferCostGwei: costInGwei.toString() };-}--const chains = [- { name: 'Ethereum', rpc: process.env.ETH_RPC },- { name: 'Polygon', rpc: process.env.POLYGON_RPC },- { name: 'Arbitrum', rpc: process.env.ARB_RPC },- { name: 'Base', rpc: process.env.BASE_RPC },-];--const gasCosts = await Promise.all(chains.map(c => getGasForChain(c.name, c.rpc)));-gasCosts.sort((a, b) => parseFloat(a.gweiPerGas) - parseFloat(b.gweiPerGas)).forEach(c => {- console.log(\`\${c.chain}: \${parseFloat(c.gweiPerGas).toFixed(3)} Gwei\`);-});-\`\`\`--## Gas-Aware Transaction Sending--\`\`\`javascript-async function sendWithGasStrategy(tx, strategy = 'standard') {- const feeData = await provider.getFeeData();- const base = feeData.lastBaseFeePerGas;-- const multipliers = { slow: 1.0, standard: 1.2, fast: 1.5 };- const m = multipliers[strategy];-- return signer.sendTransaction({- ...tx,- maxFeePerGas: base * BigInt(Math.floor(m * 100)) / 100n + ethers.parseUnits('1', 'gwei'),- maxPriorityFeePerGas: ethers.parseUnits(strategy === 'fast' ? '2' : '1', 'gwei')- });-}-\`\`\``- },- {- slug: 'stablecoin-api-guide',- title: 'Stablecoin APIs: USDC, USDT, DAI Data and Integration (2026)',- meta: 'How to query stablecoin data — USDC, USDT, DAI supply, flows, and depeg alerts — using DeFiLlama, Circle, and on-chain APIs.',- keywords: 'stablecoin API, USDC API, USDT API, DAI API, stablecoin data API, Circle API',- content: `# Stablecoin APIs: USDC, USDT, DAI Data and Integration (2026)--Stablecoins are the backbone of DeFi. This guide covers APIs for tracking stablecoin supply, cross-chain flows, and integrating USDC payments.--## Stablecoin Market Data (DeFiLlama)--\`\`\`javascript-// All stablecoins with market caps-const { peggedAssets } = await fetch('https://stablecoins.llama.fi/stablecoins').then(r => r.json());--const top5 = peggedAssets- .sort((a, b) => b.circulating.peggedUSD - a.circulating.peggedUSD)- .slice(0, 5);--top5.forEach(s => {- const supply = (s.circulating.peggedUSD / 1e9).toFixed(1);- console.log(\`\${s.symbol}: $\${supply}B\`);-});-\`\`\`--## Historical Stablecoin Supply--\`\`\`javascript-// Historical supply for USDC-const stables = await fetch('https://stablecoins.llama.fi/stablecoins').then(r => r.json());-const usdc = stables.peggedAssets.find(s => s.symbol === 'USDC');--const history = await fetch(\`https://stablecoins.llama.fi/stablecoin/\${usdc.id}\`).then(r => r.json());-history.tokens.slice(-7).forEach(h => {- const date = new Date(h.date * 1000).toLocaleDateString();- const supply = (h.circulating.peggedUSD / 1e9).toFixed(2);- console.log(\`\${date}: $\${supply}B\`);-});-\`\`\`--## Circle API (USDC)--Circle offers a developer API for USDC transfers, account management, and cross-chain operations:--\`\`\`javascript-// Create USDC transfer-const res = await fetch('https://api.circle.com/v1/transfers', {- method: 'POST',- headers: {- 'Authorization': \`Bearer \${process.env.CIRCLE_API_KEY}\`,- 'Content-Type': 'application/json'- },- body: JSON.stringify({- idempotencyKey: crypto.randomUUID(),- source: { type: 'wallet', id: 'walletId' },- destination: {- type: 'blockchain',- address: '0xRecipient',- chain: 'ETH'- },- amount: { amount: '100.00', currency: 'USD' }- })-});-\`\`\`--## USDC On-Chain (ERC-20)--\`\`\`javascript-const USDC_ETH = '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48';-const USDC_BASE = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';--const usdcAbi = [- 'function balanceOf(address) view returns (uint256)',- 'function transfer(address,uint256) returns (bool)',- 'function totalSupply() view returns (uint256)',- 'event Transfer(address indexed from, address indexed to, uint256 value)'-];--const usdc = new ethers.Contract(USDC_ETH, usdcAbi, provider);--// Balance-const balance = await usdc.balanceOf('0xAddress');-console.log(ethers.formatUnits(balance, 6), 'USDC');--// Total supply-const supply = await usdc.totalSupply();-console.log((Number(supply) / 1e15).toFixed(1), 'B USDC');--// Monitor large transfers-usdc.on('Transfer', (from, to, value) => {- const amount = Number(value) / 1e6;- if (amount > 1_000_000) console.log(\`🐋 $\${amount.toLocaleString()} USDC: \${from} → \${to}\`);-});-\`\`\`--## DAI / MakerDAO--\`\`\`javascript-// DAI stats from DeFiLlama-const dai = peggedAssets.find(s => s.symbol === 'DAI');--// DSR (DAI Savings Rate) on-chain-const POT_ADDRESS = '0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7';-const potAbi = ['function dsr() view returns (uint256)', 'function chi() view returns (uint256)'];-const pot = new ethers.Contract(POT_ADDRESS, potAbi, provider);--const dsr = await pot.dsr();-// Convert from ray (1e27) to APY-const dsrApy = (Math.pow(Number(dsr) / 1e27, 365 * 24 * 60 * 60) - 1) * 100;-console.log('DAI Savings Rate:', dsrApy.toFixed(2), '%');-\`\`\`--## Depeg Detection--\`\`\`javascript-async function checkDepeg(stableSymbol, threshold = 0.005) {- const res = await fetch(- \`https://api.coingecko.com/api/v3/simple/price?ids=\${stableSymbol}&vs_currencies=usd\`- );- const data = await res.json();- const price = data[stableSymbol].usd;- const deviation = Math.abs(price - 1.0);-- if (deviation > threshold) {- console.warn(\`⚠️ DEPEG: \${stableSymbol} = $\${price} (deviation: \${(deviation * 100).toFixed(3)}%)\`);- }- return { price, deviation, isDepegged: deviation > threshold };-}-\`\`\``- },- {- slug: 'polygon-api-guide',- title: 'Polygon API Guide: EVM Scaling Network for Developers (2026)',- meta: 'How to build on Polygon using JSON-RPC, Polygonscan API, and PolygonScan. Low fees, fast finality, full EVM compatibility.',- keywords: 'Polygon API, Polygon RPC, Polygonscan API, Matic API, Polygon developer guide',- content: `# Polygon API Guide: EVM Scaling Network for Developers (2026)--Polygon (formerly Matic) is an EVM-compatible Layer 2 with low fees and fast finality. Since it's EVM-compatible, all Ethereum tools work out of the box.--## RPC Endpoints--| Provider | Endpoint |-|---|---|-| Public RPC | \`https://polygon-rpc.com\` |-| Alchemy | \`https://polygon-mainnet.g.alchemy.com/v2/<key>\` |-| Infura | \`https://polygon-mainnet.infura.io/v3/<id>\` |-| QuickNode | Custom endpoint from dashboard |-| Chainstack | Custom endpoint |--\`\`\`javascript-import { ethers } from 'ethers';-const provider = new ethers.JsonRpcProvider('https://polygon-rpc.com');-\`\`\`--## Same API, Lower Fees--All Ethereum JSON-RPC calls work identically on Polygon. Just point at the Polygon RPC:--\`\`\`javascript-// Get MATIC balance-const balance = await provider.getBalance('0xAddress');-console.log(ethers.formatEther(balance), 'MATIC');--// Gas is ~100-1000x cheaper than Ethereum-const feeData = await provider.getFeeData();-console.log(ethers.formatUnits(feeData.gasPrice, 'gwei'), 'Gwei'); // typically 30-100 Gwei-\`\`\`--## Polygonscan API--Same interface as Etherscan:--\`\`\`javascript-const BASE = 'https://api.polygonscan.com/api';-const key = process.env.POLYGONSCAN_API_KEY;--// Transaction history-const txns = await fetch(- \`\${BASE}?module=account&action=txlist&address=0xAddress&sort=desc&apikey=\${key}\`-).then(r => r.json());--// ERC-20 transfers-const transfers = await fetch(- \`\${BASE}?module=account&action=tokentx&address=0xAddress&sort=desc&apikey=\${key}\`-).then(r => r.json());--// Gas oracle-const gas = await fetch(\`\${BASE}?module=gastracker&action=gasoracle&apikey=\${key}\`).then(r => r.json());-console.log('Fast:', gas.result.FastGasPrice, 'Gwei');-\`\`\`--## Cross-Chain Bridge (Polygon PoS)--\`\`\`javascript-// Monitor bridge deposits (Ethereum → Polygon)-const BRIDGE_ADDRESS = '0x7D1AfA7B718fb893dB30A3aBc0Cfc608AaCfeBB0';--const bridgeAbi = ['event Transfer(address indexed from, address indexed to, uint256 value)'];-const bridge = new ethers.Contract(BRIDGE_ADDRESS, bridgeAbi, ethProvider);--bridge.on('Transfer', (from, to, value) => {- if (to === '0x0000000000000000000000000000000000000000') {- console.log(\`Bridge deposit: \${ethers.formatEther(value)} MATIC from \${from}\`);- }-});-\`\`\`--## USDC on Polygon (Native)--\`\`\`javascript-const USDC_POLYGON = '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359'; // Native USDC-const USDC_E_POLYGON = '0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174'; // Bridged USDC.e--const usdc = new ethers.Contract(USDC_POLYGON, erc20Abi, provider);-const balance = await usdc.balanceOf('0xAddress');-console.log(ethers.formatUnits(balance, 6), 'USDC');-\`\`\`--## Quickswap (Polygon DEX)--\`\`\`javascript-const QUICKSWAP_SUBGRAPH = 'https://api.thegraph.com/subgraphs/name/sameepsi/quickswap-v3';--const { pools } = await fetch(QUICKSWAP_SUBGRAPH, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ query: '{ pools(first: 10, orderBy: totalValueLockedUSD, orderDirection: desc) { id token0 { symbol } token1 { symbol } totalValueLockedUSD volumeUSD } }' })-}).then(r => r.json()).then(r => r.data);-\`\`\`--## Polygon zkEVM--For Polygon zkEVM (separate from Polygon PoS):--- RPC: \`https://zkevm-rpc.com\`-- Explorer: zkevm.polygonscan.com-- Chain ID: 1101`- },- {- slug: 'arbitrum-api-guide',- title: 'Arbitrum API Guide: Ethereum L2 for Developers (2026)',- meta: 'Build on Arbitrum One and Arbitrum Nova — RPC setup, Arbiscan API, bridging, Stylus contracts, and accessing DeFi protocols.',- keywords: 'Arbitrum API, Arbitrum RPC, Arbiscan API, Arbitrum One, Arbitrum developer guide',- content: `# Arbitrum API Guide: Ethereum L2 for Developers (2026)--Arbitrum is Ethereum's largest Layer 2 by TVL, offering Ethereum security with 10-100x lower gas costs and faster finality.--## RPC Endpoints--| Network | Public RPC | Chain ID |-|---|---|---|-| Arbitrum One | \`https://arb1.arbitrum.io/rpc\` | 42161 |-| Arbitrum Nova | \`https://nova.arbitrum.io/rpc\` | 42170 |-| Arbitrum Sepolia | \`https://sepolia-rollup.arbitrum.io/rpc\` | 421614 |--\`\`\`javascript-import { ethers } from 'ethers';-const provider = new ethers.JsonRpcProvider('https://arb1.arbitrum.io/rpc');-// Or use Alchemy: https://arb-mainnet.g.alchemy.com/v2/<key>-\`\`\`--## Gas on Arbitrum--Arbitrum gas is calculated differently — there's an L1 data fee on top of the L2 execution fee:--\`\`\`javascript-const ARB_GAS_INFO = '0x000000000000000000000000000000000000006C';-const arbGasAbi = [- 'function getPricesInWei() view returns (uint256, uint256, uint256, uint256, uint256, uint256)'-];--const gasInfo = new ethers.Contract(ARB_GAS_INFO, arbGasAbi, provider);-const prices = await gasInfo.getPricesInWei();-console.log('L2 gas price:', ethers.formatUnits(prices[5], 'gwei'), 'Gwei');-\`\`\`--## Arbiscan API--\`\`\`javascript-const BASE = 'https://api.arbiscan.io/api';-const key = process.env.ARBISCAN_API_KEY;--// Transaction list-const txns = await fetch(- \`\${BASE}?module=account&action=txlist&address=0xAddress&sort=desc&apikey=\${key}\`-).then(r => r.json());--// Contract ABI-const abi = await fetch(- \`\${BASE}?module=contract&action=getabi&address=0xContractAddress&apikey=\${key}\`-).then(r => r.json());-\`\`\`--## Arbitrum Bridge--\`\`\`javascript-// Check bridge status-const GATEWAY_ROUTER = '0x72Ce9c846789fdB6fC1f34aC4AD25Dd9ef7031ef';-const gatewayAbi = ['function getGateway(address token) view returns (address)'];-const router = new ethers.Contract(GATEWAY_ROUTER, gatewayAbi, ethProvider);--// Get gateway for USDC-const gateway = await router.getGateway('0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48');-console.log('USDC Gateway:', gateway);-\`\`\`--## Key DeFi Protocols on Arbitrum--\`\`\`javascript-const ARB_CONTRACTS = {- gmx: '0xfc5A1A6EB076a2C7aD06eD22C90d7E710E35ad0a', // GMX token- uniswapV3Router: '0xE592427A0AEce92De3Edee1F18E0157C05861564',- aavePool: '0x794a61358D6845594F94dc1DB02A252b5b4814aD',- camelotRouter: '0xc873fEcbd354f5A56E00E710B90EF4201db2448d'-};-\`\`\`--## Stylus (Rust/WASM Contracts)--Arbitrum Stylus lets you write smart contracts in Rust, C, or C++:--\`\`\`rust-#![cfg_attr(not(feature = "export-abi"), no_main)]-extern crate alloc;--use stylus_sdk::prelude::*;--sol_storage! {- #[entrypoint]- pub struct Counter {- uint256 number;- }-}--#[external]-impl Counter {- pub fn increment(&mut self) {- self.number.set(self.number.get() + U256::from(1));- }- pub fn get(&self) -> U256 {- self.number.get()- }-}-\`\`\`--## GMX Perps API--GMX is the largest perps DEX on Arbitrum:--\`\`\`javascript-// GMX Stats API-const stats = await fetch('https://api.gmx.io/total_volume').then(r => r.json());-console.log('Total volume:', stats);--// Open interest-const oi = await fetch('https://api.gmx.io/open_interest').then(r => r.json());-\`\`\``- },- {- slug: 'base-chain-api-guide',- title: 'Base Chain API Guide: Coinbase L2 for Developers (2026)',- meta: 'Build on Base — Coinbase\'s Ethereum L2. Setup RPC, use Basescan API, deploy contracts, and integrate with USDC and Coinbase wallet.',- keywords: 'Base chain API, Base RPC, Basescan API, Coinbase Base L2, Base developer guide',- content: `# Base Chain API Guide: Coinbase L2 for Developers (2026)--Base is an Ethereum Layer 2 built by Coinbase using the OP Stack. It's the fastest-growing L2 and the home of USDC native issuance and the x402 payment protocol.--## RPC Endpoints--| Environment | RPC | Chain ID |-|---|---|---|-| Mainnet | \`https://mainnet.base.org\` | 8453 |-| Sepolia Testnet | \`https://sepolia.base.org\` | 84532 |-| Alchemy | \`https://base-mainnet.g.alchemy.com/v2/<key>\` | 8453 |--\`\`\`javascript-import { ethers } from 'ethers';-const provider = new ethers.JsonRpcProvider('https://mainnet.base.org');-\`\`\`--## USDC on Base--Base has native USDC issuance from Circle — no bridging risk:--\`\`\`javascript-const USDC_BASE = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';--const usdc = new ethers.Contract(USDC_BASE, [- 'function balanceOf(address) view returns (uint256)',- 'function transfer(address,uint256) returns (bool)',- 'event Transfer(address indexed from, address indexed to, uint256 value)'-], provider);--const balance = await usdc.balanceOf('0xAddress');-console.log(ethers.formatUnits(balance, 6), 'USDC');-\`\`\`--## Basescan API--\`\`\`javascript-const BASE = 'https://api.basescan.org/api';-const key = process.env.BASESCAN_API_KEY;--// Get transactions-const txns = await fetch(- \`\${BASE}?module=account&action=txlist&address=0xAddress&sort=desc&apikey=\${key}\`-).then(r => r.json());--// Get USDC transfers-const transfers = await fetch(- \`\${BASE}?module=account&action=tokentx&contractaddress=\${USDC_BASE}&address=0xAddress&apikey=\${key}\`-).then(r => r.json());-\`\`\`--## x402 Payments on Base--x402 is HTTP-native micropayments — Base is the primary chain:--\`\`\`javascript-// Server: require payment for an endpoint-import { paymentMiddleware } from 'x402-express';--app.use('/api/data', paymentMiddleware({- amount: '0.001', // $0.001 USDC- token: 'USDC',- chain: 'base',- payTo: process.env.WALLET_ADDRESS-}));--// Client: auto-pay-import { withPaymentInterceptor } from 'x402-axios';-const client = withPaymentInterceptor(axios, signer);-const data = await client.get('https://api.example.com/api/data');-\`\`\`--## Aerodrome DEX (Base)--Aerodrome is the dominant DEX on Base:--\`\`\`javascript-const AERO_SUBGRAPH = 'https://api.thegraph.com/subgraphs/name/aerodrome-finance/slipstream';--const { pools } = await fetch(AERO_SUBGRAPH, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- query: \`{- pools(first: 10, orderBy: totalValueLockedUSD, orderDirection: desc) {- id- token0 { symbol }- token1 { symbol }- totalValueLockedUSD- volumeUSD- }- }\`- })-}).then(r => r.json()).then(r => r.data);-\`\`\`--## Coinbase Wallet Integration--\`\`\`javascript-import { CoinbaseWalletSDK } from '@coinbase/wallet-sdk';--const sdk = new CoinbaseWalletSDK({ appName: 'My App', appLogoUrl: '/logo.png' });-const ethereum = sdk.makeWeb3Provider();-const provider = new ethers.BrowserProvider(ethereum);--// Request connection-const accounts = await ethereum.request({ method: 'eth_requestAccounts' });--// Switch to Base-await ethereum.request({- method: 'wallet_switchEthereumChain',- params: [{ chainId: '0x2105' }] // 8453 in hex-});-\`\`\``- },- {- slug: 'avalanche-api-guide',- title: 'Avalanche API Guide: C-Chain, X-Chain, and P-Chain (2026)',- meta: 'Build on Avalanche — connect to C-Chain for EVM, query X-Chain and P-Chain data, use AvaCloud, and access Avalanche subnet APIs.',- keywords: 'Avalanche API, Avalanche C-Chain API, AvalancheGo RPC, AVAX API, Avalanche developer guide',- content: `# Avalanche API Guide: C-Chain, X-Chain, and P-Chain (2026)--Avalanche has a unique multi-chain architecture with three primary chains. C-Chain is EVM-compatible; X-Chain handles asset transfers; P-Chain manages validators and subnets.--## C-Chain (EVM Compatible)--\`\`\`javascript-import { ethers } from 'ethers';--// Public RPC-const provider = new ethers.JsonRpcProvider('https://api.avax.network/ext/bc/C/rpc');-// Or: https://avalanche-mainnet.infura.io/v3/<id>-// Chain ID: 43114--const balance = await provider.getBalance('0xAddress');-console.log(ethers.formatEther(balance), 'AVAX');-\`\`\`--## Snowtrace API (C-Chain Explorer)--\`\`\`javascript-const BASE = 'https://api.snowtrace.io/api';-const key = process.env.SNOWTRACE_API_KEY;--// Transactions-const txns = await fetch(- \`\${BASE}?module=account&action=txlist&address=0xAddress&sort=desc&apikey=\${key}\`-).then(r => r.json());-\`\`\`--## X-Chain (Asset Exchange)--\`\`\`javascript-// X-Chain API endpoint-const X_CHAIN = 'https://api.avax.network/ext/bc/X';--// Get balance-const res = await fetch(X_CHAIN, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- jsonrpc: '2.0',- id: 1,- method: 'avm.getBalance',- params: { address: 'X-avax1...', assetID: 'AVAX' }- })-});-const { result } = await res.json();-console.log('Balance:', parseInt(result.balance) / 1e9, 'AVAX');-\`\`\`--## P-Chain (Platform / Validators)--\`\`\`javascript-const P_CHAIN = 'https://api.avax.network/ext/bc/P';--// Get current validators-const validators = await fetch(P_CHAIN, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- jsonrpc: '2.0', id: 1,- method: 'platform.getCurrentValidators',- params: {}- })-}).then(r => r.json());--console.log('Validator count:', validators.result.validators.length);--// Get stake-const stake = await fetch(P_CHAIN, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- jsonrpc: '2.0', id: 1,- method: 'platform.getStake',- params: { addresses: ['P-avax1...'] }- })-}).then(r => r.json());-\`\`\`--## Avalanche Subnets--\`\`\`javascript-// Get all subnets-const subnets = await fetch(P_CHAIN, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- jsonrpc: '2.0', id: 1,- method: 'platform.getSubnets',- params: {}- })-}).then(r => r.json());--// Connect to a subnet's C-Chain equivalent-const subnetProvider = new ethers.JsonRpcProvider('https://subnets.avax.network/mysubnet/rpc');-\`\`\`--## Trader Joe (Avalanche DEX)--\`\`\`javascript-const TJ_SUBGRAPH = 'https://api.thegraph.com/subgraphs/name/traderjoe-xyz/dex-v2-1-avalanche';--const { pairs } = await fetch(TJ_SUBGRAPH, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ query: '{ pairs(first: 10, orderBy: reserveUSD, orderDirection: desc) { id token0 { symbol } token1 { symbol } reserveUSD volumeUSD } }' })-}).then(r => r.json()).then(d => d.data);-\`\`\``- },- {- slug: 'solana-defi-api-guide',- title: 'Solana DeFi APIs: Jupiter, Raydium, and Orca Integration (2026)',- meta: 'Query Solana DeFi protocols — get swap quotes from Jupiter, pool data from Raydium and Orca, and execute transactions programmatically.',- keywords: 'Solana DeFi API, Jupiter API, Raydium API, Orca API, Solana swap API',- content: `# Solana DeFi APIs: Jupiter, Raydium, and Orca Integration (2026)--Solana's DeFi ecosystem is dominated by Jupiter (aggregator), Raydium, and Orca. All three offer APIs or SDKs for integration.--## Jupiter Aggregator API--Jupiter routes swaps across all Solana DEXs to get the best price:--\`\`\`javascript-const BASE = 'https://quote-api.jup.ag/v6';--// Get a swap quote-const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';-const SOL = 'So11111111111111111111111111111111111111112';--const quote = await fetch(- \`\${BASE}/quote?inputMint=\${USDC}&outputMint=\${SOL}&amount=100000000&slippageBps=50\`-).then(r => r.json());--console.log('Input: 100 USDC');-console.log('Output:', quote.outAmount / 1e9, 'SOL');-console.log('Price impact:', quote.priceImpactPct, '%');-console.log('Route:', quote.routePlan.map(r => r.swapInfo.label).join(' → '));-\`\`\`--Execute the swap:--\`\`\`javascript-import { Connection, VersionedTransaction } from '@solana/web3.js';--const { swapTransaction } = await fetch(\`\${BASE}/swap\`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- quoteResponse: quote,- userPublicKey: wallet.publicKey.toString(),- wrapAndUnwrapSol: true- })-}).then(r => r.json());--const tx = VersionedTransaction.deserialize(Buffer.from(swapTransaction, 'base64'));-tx.sign([wallet]);-const sig = await connection.sendTransaction(tx);-await connection.confirmTransaction(sig, 'confirmed');-\`\`\`--## Jupiter Token List--\`\`\`javascript-// All verified tokens on Solana-const tokens = await fetch('https://token.jup.ag/all').then(r => r.json());-const usdc = tokens.find(t => t.symbol === 'USDC');-console.log(usdc.address, usdc.decimals);-\`\`\`--## Raydium--\`\`\`javascript-// Raydium pool info-const pools = await fetch('https://api.raydium.io/v2/main/pairs').then(r => r.json());-const solUsdc = pools.find(p => p.name === 'SOL-USDC');-console.log('SOL/USDC price:', solUsdc.price);-console.log('24h volume:', solUsdc.volume24h);-console.log('TVL:', solUsdc.tvl);--// Top pools by volume-const top10 = pools- .sort((a, b) => b.volume24h - a.volume24h)- .slice(0, 10);-\`\`\`--## Orca--\`\`\`javascript-import { buildWhirlpoolClient, ORCA_WHIRLPOOLS_CONFIG } from '@orca-so/whirlpools-sdk';-import { AnchorProvider } from '@coral-xyz/anchor';--const provider = AnchorProvider.env();-const client = buildWhirlpoolClient(ORCA_WHIRLPOOLS_CONFIG, provider);--// Get pool data-const poolAddress = new PublicKey('poolAddressHere');-const pool = await client.getPool(poolAddress);-const poolData = pool.getData();-console.log('Current price:', pool.getPrice().toFixed(4));-console.log('Liquidity:', poolData.liquidity.toString());-\`\`\`--## Solana Token Prices (Helius DAS API)--\`\`\`javascript-const HELIUS_URL = \`https://mainnet.helius-rpc.com/?api-key=\${process.env.HELIUS_API_KEY}\`;--// Get asset (token) price and metadata-const res = await fetch(HELIUS_URL, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- jsonrpc: '2.0',- id: 1,- method: 'getAsset',- params: { id: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' }- })-});-const { result } = await res.json();-console.log(result.content.metadata.name, result.token_info.price_info?.price_per_token);-\`\`\``- },- {- slug: 'crypto-analytics-api-guide',- title: 'Crypto Analytics APIs: On-Chain Metrics and Market Intelligence (2026)',- meta: 'Best APIs for on-chain analytics — Glassnode, Messari, Nansen, and Santiment. Track whale activity, exchange flows, and miner behavior.',- keywords: 'crypto analytics API, on-chain analytics API, Glassnode API, Messari API, Nansen API',- content: `# Crypto Analytics APIs: On-Chain Metrics and Market Intelligence (2026)--On-chain analytics APIs provide institutional-grade intelligence: exchange flows, realized cap, SOPR, MVRV, and whale wallet tracking — signals unavailable from price data alone.--## Glassnode API--Glassnode is the industry standard for on-chain metrics:--\`\`\`javascript-const BASE = 'https://api.glassnode.com/v1/metrics';-const key = process.env.GLASSNODE_API_KEY;--// Exchange net position change (are whales depositing or withdrawing?)-const flow = await fetch(- \`\${BASE}/distribution/exchange_net_position_change?a=BTC&i=24h&api_key=\${key}\`-).then(r => r.json());--// MVRV (Market Value to Realized Value) — overvalued/undervalued signal-const mvrv = await fetch(- \`\${BASE}/market/mvrv?a=BTC&i=24h&api_key=\${key}\`-).then(r => r.json());--// Active addresses-const activeAddresses = await fetch(- \`\${BASE}/addresses/active_count?a=BTC&i=24h&api_key=\${key}\`-).then(r => r.json());--// Format: [{t: timestamp, v: value}, ...]-mvrv.slice(-7).forEach(({ t, v }) => {- console.log(new Date(t * 1000).toLocaleDateString(), 'MVRV:', v.toFixed(3));-});-\`\`\`--### Key Glassnode Metrics--| Metric | Endpoint | Signal |-|---|---|---|-| MVRV | \`market/mvrv\` | >3.5 = overvalued, <1 = undervalued |-| SOPR | \`indicators/sopr\` | >1 = selling at profit, <1 = selling at loss |-| Exchange inflows | \`transactions/transfers_to_exchanges_count\` | High = selling pressure |-| Long-term holder supply | \`supply/lth_sum\` | Accumulation vs. distribution |-| Hash ribbon | \`mining/hash_ribbon\` | Miner capitulation signal |--## Messari API--\`\`\`javascript-const BASE = 'https://data.messari.io/api/v1';-const key = process.env.MESSARI_API_KEY;--// Asset metrics-const btc = await fetch(\`\${BASE}/assets/btc/metrics\`, {- headers: { 'x-messari-api-key': key }-}).then(r => r.json());--console.log('Market cap:', btc.data.market_data.real_volume_last_24_hours);-console.log('Realized cap:', btc.data.supply.y_2050);-console.log('ROI 1y:', btc.data.roi_data.percent_change_last_1_year, '%');--// Protocol revenue-const protocols = await fetch('https://data.messari.io/api/v1/protocols', {- headers: { 'x-messari-api-key': key }-}).then(r => r.json());-\`\`\`--## Nansen (Wallet Labels)--\`\`\`javascript-// Nansen labels known wallets (funds, exchanges, whales)-const res = await fetch(\`https://api.nansen.ai/labels/\${address}\`, {- headers: { 'apiKey': process.env.NANSEN_API_KEY }-}).then(r => r.json());-console.log(res.labels); // e.g., ["Smart Money", "DEX Trader"]-\`\`\`--## Santiment API--\`\`\`javascript-// Social volume for a crypto asset-const SANTIMENT_GQL = 'https://api.santiment.net/graphql';--const query = \`{- socialVolume(slug: "bitcoin", from: "2025-01-01T00:00:00Z", to: "2025-01-07T00:00:00Z", interval: "1d", socialVolumeType: PROFESSIONAL_TRADERS_CHAT_OVERVIEW) {- datetime- mentionsCount- }-}\`;--const res = await fetch(SANTIMENT_GQL, {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- 'Authorization': \`Apikey \${process.env.SANTIMENT_API_KEY}\`- },- body: JSON.stringify({ query })-}).then(r => r.json());-\`\`\`--## Build Your Own: On-Chain Whale Tracker--\`\`\`javascript-// Track large ETH movements using Alchemy-const alchemy = new Alchemy({ apiKey: process.env.ALCHEMY_KEY });--const transfers = await alchemy.core.getAssetTransfers({- category: ['external'],- minValue: 100, // >100 ETH- withMetadata: true,- maxCount: 20-});--transfers.transfers.forEach(t => {- console.log(\`🐋 \${t.value.toFixed(0)} ETH: \${t.from} → \${t.to}\`);-});-\`\`\``- },- {- slug: 'bnb-chain-api-guide',- title: 'BNB Chain API Guide: BSC Developer Reference (2026)',- meta: 'Build on BNB Smart Chain — RPC endpoints, BSCScan API, PancakeSwap integration, and BEP-20 token interactions.',- keywords: 'BNB Chain API, BSC API, BSCScan API, PancakeSwap API, BNB developer guide',- content: `# BNB Chain API Guide: BSC Developer Reference (2026)--BNB Smart Chain (BSC) is an EVM-compatible blockchain with low fees and fast finality, operated by Binance. It's home to PancakeSwap, Venus, and hundreds of DeFi protocols.--## RPC Endpoints--| Network | RPC | Chain ID |-|---|---|---|-| BSC Mainnet | \`https://bsc-dataseed.binance.org/\` | 56 |-| BSC Testnet | \`https://data-seed-prebsc-1-s1.binance.org:8545/\` | 97 |-| Alchemy | \`https://bnb-mainnet.g.alchemy.com/v2/<key>\` | 56 |--\`\`\`javascript-import { ethers } from 'ethers';-const provider = new ethers.JsonRpcProvider('https://bsc-dataseed.binance.org/');-console.log(await provider.getNetwork()); // chainId: 56n-\`\`\`--## BSCScan API--\`\`\`javascript-const BASE = 'https://api.bscscan.com/api';-const key = process.env.BSCSCAN_API_KEY;--// BNB balance-const bal = await fetch(- \`\${BASE}?module=account&action=balance&address=0xAddress&apikey=\${key}\`-).then(r => r.json());-console.log(parseInt(bal.result) / 1e18, 'BNB');--// BEP-20 transfers-const transfers = await fetch(- \`\${BASE}?module=account&action=tokentx&address=0xAddress&sort=desc&apikey=\${key}\`-).then(r => r.json());-\`\`\`--## BEP-20 Tokens--\`\`\`javascript-const BUSD = '0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56';-const USDT_BSC = '0x55d398326f99059fF775485246999027B3197955';-const CAKE = '0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82'; // PancakeSwap--const busd = new ethers.Contract(BUSD, ['function balanceOf(address) view returns (uint256)'], provider);-const balance = await busd.balanceOf('0xAddress');-console.log(ethers.formatEther(balance), 'BUSD');-\`\`\`--## PancakeSwap API--\`\`\`javascript-const CAKE_SUBGRAPH = 'https://api.thegraph.com/subgraphs/name/pancakeswap/exhange-v3';--const { pools } = await fetch(CAKE_SUBGRAPH, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- query: \`{- pools(first: 10, orderBy: totalValueLockedUSD, orderDirection: desc) {- id- token0 { symbol }- token1 { symbol }- feeTier- totalValueLockedUSD- volumeUSD- }- }\`- })-}).then(r => r.json()).then(r => r.data);--// PancakeSwap REST API-const pairs = await fetch('https://api.pancakeswap.info/api/v2/pairs').then(r => r.json());-\`\`\`--## PancakeSwap Router (Swap)--\`\`\`javascript-const ROUTER = '0x10ED43C718714eb63d5aA57B78B54704E256024E';-const routerAbi = [- 'function getAmountsOut(uint amountIn, address[] memory path) view returns (uint[] memory amounts)',- 'function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) payable'-];--const router = new ethers.Contract(ROUTER, routerAbi, provider);-const WBNB = '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c';--const amounts = await router.getAmountsOut(ethers.parseEther('0.1'), [WBNB, CAKE]);-console.log('BNB → CAKE:', ethers.formatEther(amounts[1]));-\`\`\`--## Venus Protocol (Lending)--\`\`\`javascript-const VENUS_COMPTROLLER = '0xfD36E2c2a6789Db23113685031d7F16329158384';-const comptrollerAbi = ['function getAllMarkets() view returns (address[])'];-const comptroller = new ethers.Contract(VENUS_COMPTROLLER, comptrollerAbi, provider);-const markets = await comptroller.getAllMarkets();-console.log('Venus markets:', markets.length);-\`\`\``- },- {- slug: 'crypto-historical-data-api-guide',- title: 'Crypto Historical Data APIs: OHLCV, Price History, and Backtesting (2026)',- meta: 'Best APIs for historical cryptocurrency data — OHLCV candles, tick data, trade history. CoinGecko, CryptoCompare, Binance, and Kaiko compared.',- keywords: 'crypto historical data API, OHLCV API, historical price API, backtesting data API, CryptoCompare API',- content: `# Crypto Historical Data APIs: OHLCV, Price History, and Backtesting (2026)--Historical data is essential for backtesting trading strategies, building charts, and training ML models. Here's how to access it from the best providers.--## Binance (Best Free Option)--\`\`\`javascript-// OHLCV candles — up to 1000 per request, any interval-async function getBinanceCandles(symbol, interval, limit = 500) {- const res = await fetch(- \`https://api.binance.com/api/v3/klines?symbol=\${symbol}&interval=\${interval}&limit=\${limit}\`- );- const raw = await res.json();- return raw.map(([openTime, open, high, low, close, volume, closeTime]) => ({- time: openTime,- open: parseFloat(open),- high: parseFloat(high),- low: parseFloat(low),- close: parseFloat(close),- volume: parseFloat(volume)- }));-}--// Usage-const candles = await getBinanceCandles('BTCUSDT', '1d', 365);--// Paginate for full history-async function getFullHistory(symbol, interval, startTime) {- const all = [];- let from = startTime;-- while (true) {- const batch = await getBinanceCandlesPaged(symbol, interval, from, 1000);- if (batch.length === 0) break;- all.push(...batch);- from = batch[batch.length - 1].time + 1;- await new Promise(r => setTimeout(r, 200)); // respect rate limit- }- return all;-}-\`\`\`--## CoinGecko Historical--\`\`\`javascript-// Daily OHLCV (limited to 90 days on free tier)-const ohlcv = await fetch(- 'https://api.coingecko.com/api/v3/coins/bitcoin/ohlc?vs_currency=usd&days=90'-).then(r => r.json());-// [[timestamp, open, high, low, close], ...]--// Daily closes for any time range-const history = await fetch(- 'https://api.coingecko.com/api/v3/coins/bitcoin/market_chart/range?vs_currency=usd&from=1609459200&to=1640995200'-).then(r => r.json());-// history.prices = [[timestamp, price], ...]-\`\`\`--## CryptoCompare--\`\`\`javascript-const key = process.env.CRYPTOCOMPARE_API_KEY;-const headers = { 'authorization': \`Apikey \${key}\` };--// Daily OHLCV — up to 2000 days, any exchange-const res = await fetch(- 'https://min-api.cryptocompare.com/data/v2/histoday?fsym=BTC&tsym=USD&limit=365&e=Coinbase',- { headers }-).then(r => r.json());-const candles = res.Data.Data;--// Hourly-const hourly = await fetch(- 'https://min-api.cryptocompare.com/data/v2/histohour?fsym=ETH&tsym=USD&limit=720',- { headers }-).then(r => r.json());--// Minute-const minute = await fetch(- 'https://min-api.cryptocompare.com/data/v2/histominute?fsym=BTC&tsym=USD&limit=1440',- { headers }-).then(r => r.json());-\`\`\`--## Kaiko (Institutional Grade)--Kaiko provides tick-by-tick trade data from 100+ exchanges:--\`\`\`javascript-const res = await fetch(- 'https://us.market-api.kaiko.io/v2/data/trades.v1/spot_direct_exchange_rate/btc/usd?interval=1d&start_time=2024-01-01T00:00:00Z',- { headers: { 'X-Api-Key': process.env.KAIKO_API_KEY } }-).then(r => r.json());-\`\`\`--## Building a Backtester--\`\`\`javascript-function backtest(candles, strategy, initialCapital = 10000) {- let cash = initialCapital;- let position = 0;- let trades = [];-- for (let i = 20; i < candles.length; i++) {- const signal = strategy(candles.slice(0, i));- const price = candles[i].close;-- if (signal === 'buy' && cash > 0) {- position = cash / price;- cash = 0;- trades.push({ type: 'buy', price, time: candles[i].time });- } else if (signal === 'sell' && position > 0) {- cash = position * price;- position = 0;- trades.push({ type: 'sell', price, time: candles[i].time });- }- }-- const finalValue = cash + position * candles[candles.length - 1].close;- return {- finalValue,- roi: ((finalValue - initialCapital) / initialCapital * 100).toFixed(2) + '%',- trades: trades.length,- sharpe: calculateSharpe(trades, candles)- };-}-\`\`\``- },- {- slug: 'defi-yield-api-guide',- title: 'DeFi Yield APIs: Find the Best APY Across Protocols (2026)',- meta: 'How to query yield farming opportunities, staking rewards, and lending rates using DeFiLlama Yields, Zapper, and direct protocol APIs.',- keywords: 'DeFi yield API, APY API, yield farming API, staking rate API, DeFiLlama yields',- content: `# DeFi Yield APIs: Find the Best APY Across Protocols (2026)--Finding the best yield requires querying dozens of protocols. These APIs aggregate yield data across the DeFi ecosystem.--## DeFiLlama Yields (Best Free Option)--\`\`\`javascript-// All yield pools across all chains and protocols-const { data: pools } = await fetch('https://yields.llama.fi/pools').then(r => r.json());--console.log('Total pools:', pools.length);--// Top stablecoin yields-const stableYields = pools- .filter(p =>- p.stablecoin &&- p.tvlUsd > 1_000_000 &&- p.apy > 0 &&- !p.ilRisk- )- .sort((a, b) => b.apy - a.apy)- .slice(0, 20);--stableYields.forEach(p => {- console.log(\`\${p.project} | \${p.symbol} | \${p.chain} | APY: \${p.apy.toFixed(2)}% | TVL: $\${(p.tvlUsd/1e6).toFixed(0)}M\`);-});--// Highest ETH staking yields-const ethYields = pools- .filter(p => p.symbol === 'ETH' || p.symbol.includes('stETH') || p.symbol.includes('wstETH'))- .sort((a, b) => b.apy - a.apy);-\`\`\`--## Historical APY--\`\`\`javascript-// APY history for a specific pool-const poolId = 'your-pool-id'; // from the pools list-const history = await fetch(\`https://yields.llama.fi/chart/\${poolId}\`).then(r => r.json());-history.data.slice(-30).forEach(({ timestamp, apy, tvlUsd }) => {- console.log(new Date(timestamp).toLocaleDateString(), \`APY: \${apy.toFixed(2)}%\`, \`TVL: $\${(tvlUsd/1e6).toFixed(0)}M\`);-});-\`\`\`--## Aave Interest Rates (Direct)--\`\`\`javascript-const AAVE_SUBGRAPH = 'https://api.thegraph.com/subgraphs/name/aave/protocol-v3';--const { reserves } = await fetch(AAVE_SUBGRAPH, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ query: '{ reserves { symbol liquidityRate variableBorrowRate } }' })-}).then(r => r.json()).then(d => d.data);--reserves.forEach(r => {- const depositApy = (parseFloat(r.liquidityRate) / 1e27) * 100;- const borrowApy = (parseFloat(r.variableBorrowRate) / 1e27) * 100;- if (depositApy > 0) console.log(\`\${r.symbol}: Supply \${depositApy.toFixed(3)}% | Borrow \${borrowApy.toFixed(3)}%\`);-});-\`\`\`--## Compound Rates--\`\`\`javascript-// Compound V3 USDC market-const COMET = '0xc3d688B66703497DAA19211EEdff47f25384cdc3';-const cometAbi = [- 'function getSupplyRate(uint utilization) view returns (uint64)',- 'function getBorrowRate(uint utilization) view returns (uint64)',- 'function getUtilization() view returns (uint)'-];--const comet = new ethers.Contract(COMET, cometAbi, provider);-const utilization = await comet.getUtilization();-const supplyRate = await comet.getSupplyRate(utilization);-const borrowRate = await comet.getBorrowRate(utilization);--// Convert per-second rate to APY-const SECONDS_PER_YEAR = 31_536_000;-const supplyApy = (Math.pow(Number(supplyRate) / 1e18 * SECONDS_PER_YEAR + 1, 1) - 1) * 100;-console.log('Supply APY:', supplyApy.toFixed(3), '%');-\`\`\`--## Lido Staking Rate--\`\`\`javascript-// Lido stETH APR-const res = await fetch('https://eth-api.lido.fi/v1/protocol/steth/apr/sma').then(r => r.json());-console.log('Lido stETH APR (7d SMA):', res.data.smaApr, '%');--// Rocket Pool rETH APR-const rp = await fetch('https://api.rocketpool.net/api/eth/apr').then(r => r.json());-console.log('Rocket Pool APR:', rp.yearlyAPR, '%');-\`\`\``- },- {- slug: 'nft-floor-price-api-guide',- title: 'NFT Floor Price APIs: Real-Time and Historical Collection Data (2026)',- meta: 'Fetch NFT floor prices in real time from OpenSea, Blur, Reservoir, and Simplehash. Build price trackers, alerts, and analytics dashboards.',- keywords: 'NFT floor price API, OpenSea floor price, NFT price API, Reservoir API floor price, NFT collection stats API',- content: `# NFT Floor Price APIs: Real-Time and Historical Collection Data (2026)--NFT floor prices are volatile and sourced from multiple marketplaces. Reliable apps aggregate from several APIs and cross-reference listings.--## Reservoir (Multi-Marketplace Aggregator)--Reservoir aggregates listings from OpenSea, Blur, X2Y2, LooksRare, and more — giving a true floor across all venues:--\`\`\`javascript-const headers = { 'x-api-key': process.env.RESERVOIR_API_KEY };-const BASE = 'https://api.reservoir.tools';--// Collection floor price-const stats = await fetch(- \`\${BASE}/collections/v7?id=0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D\`,- { headers }-).then(r => r.json());--const col = stats.collections[0];-console.log('Floor:', col.floorAsk.price.amount.native, 'ETH');-console.log('24h Volume:', col.volume['1day'], 'ETH');-console.log('Floor change 24h:', col.floorSaleChange['1day'], '%');-console.log('Owner count:', col.ownerCount);-\`\`\`--## OpenSea (Direct)--\`\`\`javascript-const os = { headers: { 'X-API-KEY': process.env.OPENSEA_API_KEY } };--const stats = await fetch(- 'https://api.opensea.io/api/v2/collections/boredapeyachtclub/stats',- os-).then(r => r.json());--console.log('Floor:', stats.total.floor_price, 'ETH');-console.log('24h Volume:', stats.intervals[0].volume, 'ETH');-console.log('All-time Volume:', stats.total.volume, 'ETH');-\`\`\`--## Alchemy NFT API--\`\`\`javascript-import { Alchemy, Network } from 'alchemy-sdk';-const alchemy = new Alchemy({ apiKey: process.env.ALCHEMY_KEY, network: Network.ETH_MAINNET });--const floor = await alchemy.nft.getFloorPrice('0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D');-console.log('OpenSea floor:', floor.openSea?.floorPrice, 'ETH');-console.log('LooksRare floor:', floor.looksRare?.floorPrice, 'ETH');-\`\`\`--## Simplehash (Multi-Chain)--\`\`\`javascript-const simplehash = { headers: { 'X-API-KEY': process.env.SIMPLEHASH_KEY } };--// Works across Ethereum, Polygon, Solana, etc.-const col = await fetch(- 'https://api.simplehash.com/api/v0/nfts/collections/ethereum/0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D',- simplehash-).then(r => r.json());--col.floor_prices.forEach(fp => {- console.log(\`\${fp.marketplace_name}: \${fp.value / 1e18} ETH\`);-});-\`\`\`--## Historical Floor Price--\`\`\`javascript-// Reservoir historical floor price-const history = await fetch(- \`\${BASE}/collections/0xBC4CA0.../floor-ask-price/v1?normalizeRoyalties=false&sortDirection=desc&limit=30\`,- { headers }-).then(r => r.json());-\`\`\`--## Floor Price Alert Bot--\`\`\`javascript-class FloorPriceAlerts {- constructor(collection, alerts) {- this.collection = collection;- this.alerts = alerts; // [{threshold, direction, webhook}]- }-- async check() {- const floor = await this.getFloor();-- for (const alert of this.alerts) {- const triggered =- alert.direction === 'below' ? floor < alert.threshold :- alert.direction === 'above' ? floor > alert.threshold : false;-- if (triggered) {- await fetch(alert.webhook, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- text: \`Floor \${alert.direction} \${alert.threshold} ETH — currently \${floor} ETH\`- })- });- }- }- return floor;- }-- async getFloor() {- const data = await fetch(- \`https://api.reservoir.tools/collections/v7?id=\${this.collection}\`,- { headers: { 'x-api-key': process.env.RESERVOIR_KEY } }- ).then(r => r.json());- return data.collections[0].floorAsk.price.amount.native;- }-}--const monitor = new FloorPriceAlerts('0xBC4CA0...', [- { threshold: 10, direction: 'below', webhook: process.env.SLACK_WEBHOOK }-]);-setInterval(() => monitor.check(), 60000);-\`\`\``- },- {- slug: 'crypto-wallet-api-guide',- title: 'Crypto Wallet APIs: Generate, Manage, and Query Wallets (2026)',- meta: 'How to use crypto wallet APIs — generate HD wallets, query balances across chains, sign transactions, and integrate WalletConnect.',- keywords: 'crypto wallet API, HD wallet API, WalletConnect API, ethers.js wallet, Web3 wallet integration',- content: `# Crypto Wallet APIs: Generate, Manage, and Query Wallets (2026)--Wallet APIs span key generation, signing, multi-chain balance queries, and browser wallet integrations. This guide covers all layers.--## Generate an HD Wallet (ethers.js)--\`\`\`javascript-import { ethers } from 'ethers';--// Generate random wallet-const wallet = ethers.Wallet.createRandom();-console.log('Address:', wallet.address);-console.log('Private key:', wallet.privateKey); // NEVER share or log in production-console.log('Mnemonic:', wallet.mnemonic.phrase);--// Restore from mnemonic-const restored = ethers.Wallet.fromPhrase('word1 word2 ... word12');--// HD derivation (BIP44)-const hdNode = ethers.HDNodeWallet.fromPhrase(mnemonic);-const account0 = hdNode.derivePath("m/44'/60'/0'/0/0");-const account1 = hdNode.derivePath("m/44'/60'/0'/0/1");-\`\`\`--## Sign Messages and Transactions--\`\`\`javascript-const provider = new ethers.JsonRpcProvider(process.env.ETH_RPC_URL);-const signer = new ethers.Wallet(process.env.PRIVATE_KEY, provider);--// Sign a message (off-chain, no gas)-const signature = await signer.signMessage('Hello World');-const recovered = ethers.verifyMessage('Hello World', signature);-console.log('Signer is valid:', recovered === signer.address);--// Sign typed data (EIP-712)-const domain = { name: 'MyApp', version: '1', chainId: 1 };-const types = { Permit: [{ name: 'owner', type: 'address' }, { name: 'value', type: 'uint256' }] };-const value = { owner: signer.address, value: 1000n };-const sig = await signer.signTypedData(domain, types, value);-\`\`\`--## Browser Wallet Integration (MetaMask / EIP-1193)--\`\`\`javascript-// Request wallet connection-async function connectWallet() {- if (!window.ethereum) throw new Error('No wallet detected');-- const provider = new ethers.BrowserProvider(window.ethereum);- const accounts = await provider.send('eth_requestAccounts', []);- const signer = await provider.getSigner();-- return { provider, signer, address: accounts[0] };-}--// Listen for account/chain changes-window.ethereum.on('accountsChanged', (accounts) => {- console.log('New account:', accounts[0]);-});--window.ethereum.on('chainChanged', (chainId) => {- window.location.reload(); // recommended-});--// Switch chain-await window.ethereum.request({- method: 'wallet_switchEthereumChain',- params: [{ chainId: '0x2105' }] // Base-});-\`\`\`--## WalletConnect v2--\`\`\`javascript-import { WalletConnect } from '@walletconnect/ethereum-provider';--const provider = await WalletConnect.init({- projectId: process.env.WALLETCONNECT_PROJECT_ID,- chains: [1],- optionalChains: [8453, 42161, 137],- showQrModal: true-});--await provider.enable();-const ethProvider = new ethers.BrowserProvider(provider);-const signer = await ethProvider.getSigner();-\`\`\`--## Privy (Embedded Wallets)--\`\`\`javascript-import { PrivyProvider, useWallets } from '@privy-io/react-auth';--// In a component-const { wallets } = useWallets();-const embedded = wallets.find(w => w.walletClientType === 'privy');--const provider = await embedded.getEthersProvider();-const signer = provider.getSigner();-\`\`\`--## Multi-Chain Balance Query--\`\`\`javascript-async function getAllBalances(address) {- const chains = [- { name: 'Ethereum', rpc: process.env.ETH_RPC, nativeSymbol: 'ETH' },- { name: 'Polygon', rpc: 'https://polygon-rpc.com', nativeSymbol: 'MATIC' },- { name: 'Base', rpc: 'https://mainnet.base.org', nativeSymbol: 'ETH' },- { name: 'Arbitrum', rpc: 'https://arb1.arbitrum.io/rpc', nativeSymbol: 'ETH' }- ];-- const results = await Promise.all(chains.map(async ({ name, rpc, nativeSymbol }) => {- const p = new ethers.JsonRpcProvider(rpc);- const balance = await p.getBalance(address);- return { chain: name, symbol: nativeSymbol, balance: ethers.formatEther(balance) };- }));-- return results.filter(r => parseFloat(r.balance) > 0);-}-\`\`\``- },-];--for (const article of articles) {- const filePath = join(OUT, `${article.slug}.md`);- const content = `----title: "${article.title}"-meta_description: "${article.meta}"-keywords: "${article.keywords}"------${article.content}-`;- writeFileSync(filePath, content);- console.log(`✅ ${article.slug}.md`);-}--console.log(`\n✅ Wrote ${articles.length} articles to ${OUT}`);diff --git a/xactions/scripts/generate-seo-articles.js b/xactions/scripts/generate-seo-articles.jsdeleted file mode 100644index 6c4a718ea..000000000--- a/xactions/scripts/generate-seo-articles.js+++ /dev/null@@ -1,2115 +0,0 @@-import { writeFileSync, mkdirSync } from 'fs';-import { join } from 'path';--const OUT = '/workspaces/XActions/docs/seo-articles';-mkdirSync(OUT, { recursive: true });--const articles = [- {- slug: 'binance-api-guide',- title: 'Binance API Guide: Complete Reference for Developers (2026)',- meta: 'Learn how to use the Binance API for spot trading, futures, market data, and WebSocket streams. Includes code examples and authentication setup.',- keywords: 'Binance API, Binance trading API, Binance WebSocket, Binance REST API',- content: `# Binance API Guide: Complete Reference for Developers (2026)--The Binance API is the most widely used cryptocurrency exchange API in the world, powering millions of trading bots, portfolio trackers, and analytics tools. This guide covers everything you need to integrate with Binance's REST and WebSocket APIs.--## Authentication--Binance uses HMAC-SHA256 signed requests for private endpoints. Generate an API key in your account settings, then sign each request with your secret key.--\`\`\`javascript-import crypto from 'crypto';--function sign(queryString, secret) {- return crypto.createHmac('sha256', secret).update(queryString).digest('hex');-}--async function getAccountInfo(apiKey, secret) {- const timestamp = Date.now();- const query = \`timestamp=\${timestamp}\`;- const signature = sign(query, secret);-- const res = await fetch(- \`https://api.binance.com/api/v3/account?\${query}&signature=\${signature}\`,- { headers: { 'X-MBX-APIKEY': apiKey } }- );- return res.json();-}-\`\`\`--## Key Endpoints--| Endpoint | Method | Description |-|---|---|---|-| \`/api/v3/ticker/price\` | GET | Latest price for a symbol |-| \`/api/v3/klines\` | GET | OHLCV candlestick data |-| \`/api/v3/depth\` | GET | Order book snapshot |-| \`/api/v3/order\` | POST | Place a new order |-| \`/api/v3/account\` | GET | Account balances |-| \`/api/v3/myTrades\` | GET | Trade history |--## Fetching Candlestick Data--\`\`\`javascript-const res = await fetch(- 'https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=1h&limit=100'-);-const candles = await res.json();-// [openTime, open, high, low, close, volume, closeTime, ...]-\`\`\`--## WebSocket Streams--Binance WebSocket streams deliver real-time data without polling.--\`\`\`javascript-const ws = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt@trade');--ws.onmessage = (event) => {- const trade = JSON.parse(event.data);- console.log(\`Price: \${trade.p}, Qty: \${trade.q}\`);-};-\`\`\`--**Available streams:**-- \`<symbol>@trade\` — real-time trade stream-- \`<symbol>@kline_<interval>\` — candlestick updates-- \`<symbol>@depth\` — order book diffs-- \`<symbol>@bookTicker\` — best bid/ask--## Rate Limits--Binance enforces weight-based rate limits. Each endpoint costs 1–50 weight units. The default limit is 1,200 weight per minute. Exceeding it returns HTTP 429, and repeated violations result in a temporary IP ban (HTTP 418).--Always check the \`X-MBX-USED-WEIGHT-1M\` response header to monitor consumption.--## Order Types--Binance supports: LIMIT, MARKET, STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, TAKE_PROFIT_LIMIT, LIMIT_MAKER. For most bots, LIMIT and MARKET cover 90% of use cases.--## Futures API--The Futures API lives at \`https://fapi.binance.com\`. It shares the same authentication scheme but has additional endpoints for leverage, position, and funding rate data.--\`\`\`javascript-// Get funding rate history-const res = await fetch(- 'https://fapi.binance.com/fapi/v1/fundingRate?symbol=BTCUSDT&limit=10'-);-\`\`\`--## Best Practices--- Cache public market data (prices, candles) for at least 1 second-- Use WebSockets instead of polling for latency-sensitive strategies-- Implement exponential backoff on 429 responses-- Never store API keys in source code — use environment variables-- Enable IP restrictions on your API key in account settings`- },- {- slug: 'coinbase-api-guide',- title: 'Coinbase Advanced Trade API: Developer Guide (2026)',- meta: 'Full guide to the Coinbase Advanced Trade API — authentication, order management, market data, and WebSocket feeds with JavaScript examples.',- keywords: 'Coinbase API, Coinbase Advanced Trade API, Coinbase Pro API, Coinbase trading API',- content: `# Coinbase Advanced Trade API: Developer Guide (2026)--Coinbase Advanced Trade API (formerly Coinbase Pro) is the institutional-grade trading interface for Coinbase. It offers REST endpoints for order management and real-time WebSocket feeds for market data.--## Base URL--\`https://api.coinbase.com/api/v3/brokerage/\`--## Authentication--Coinbase uses JWT-based authentication for all private endpoints.--\`\`\`javascript-import { SignJWT } from 'jose';-import crypto from 'crypto';--async function createJWT(apiKeyName, privateKey) {- const key = await crypto.subtle.importKey(- 'pkcs8',- Buffer.from(privateKey, 'base64'),- { name: 'ECDSA', namedCurve: 'P-256' },- false,- ['sign']- );-- return new SignJWT({ sub: apiKeyName, iss: 'cdp', nbf: Math.floor(Date.now() / 1000) })- .setProtectedHeader({ alg: 'ES256', kid: apiKeyName })- .setExpirationTime('2m')- .sign(key);-}-\`\`\`--## Key Endpoints--| Endpoint | Description |-|---|---|-| \`GET /products\` | List all trading pairs |-| \`GET /products/{id}/candles\` | OHLCV data |-| \`GET /best_bid_ask\` | Best bid/ask for symbols |-| \`POST /orders\` | Place an order |-| \`GET /orders/historical/batch\` | Order history |-| \`GET /portfolios\` | Portfolio balances |--## Placing an Order--\`\`\`javascript-const order = {- client_order_id: crypto.randomUUID(),- product_id: 'BTC-USD',- side: 'BUY',- order_configuration: {- limit_limit_gtc: {- base_size: '0.001',- limit_price: '50000'- }- }-};--const res = await fetch('https://api.coinbase.com/api/v3/brokerage/orders', {- method: 'POST',- headers: {- 'Authorization': \`Bearer \${jwt}\`,- 'Content-Type': 'application/json'- },- body: JSON.stringify(order)-});-\`\`\`--## WebSocket Feed--\`\`\`javascript-const ws = new WebSocket('wss://advanced-trade-ws.coinbase.com');--ws.onopen = () => {- ws.send(JSON.stringify({- type: 'subscribe',- product_ids: ['BTC-USD', 'ETH-USD'],- channel: 'ticker'- }));-};-\`\`\`--**Channels:** ticker, level2, market_trades, user (private)--## Rate Limits--- Public endpoints: 10 requests/second-- Private endpoints: 30 requests/second-- WebSocket: 750 subscriptions per connection--## Sandbox Environment--Test without real funds at \`https://api-public.sandbox.exchange.coinbase.com\`. Sandbox accounts come pre-funded with test assets.`- },- {- slug: 'ethereum-rpc-api-guide',- title: 'Ethereum RPC API Guide: JSON-RPC Methods for Developers (2026)',- meta: 'Complete guide to Ethereum JSON-RPC API — read balances, send transactions, call smart contracts, and listen to events using eth_call, eth_getLogs, and more.',- keywords: 'Ethereum API, Ethereum JSON-RPC, eth_call, web3 API, ethers.js API',- content: `# Ethereum RPC API Guide: JSON-RPC Methods for Developers (2026)--The Ethereum JSON-RPC API is the standard interface for interacting with any EVM-compatible blockchain. Every node — whether self-hosted, Alchemy, Infura, or QuickNode — exposes this same API.--## Connecting--\`\`\`javascript-import { ethers } from 'ethers';--// Via provider URL (Alchemy, Infura, QuickNode, etc.)-const provider = new ethers.JsonRpcProvider(process.env.ETH_RPC_URL);-\`\`\`--## Core Methods--### Get ETH Balance--\`\`\`javascript-const balance = await provider.getBalance('0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045');-console.log(ethers.formatEther(balance)); // "1.234"-\`\`\`--### Get Block--\`\`\`javascript-const block = await provider.getBlock('latest');-console.log(block.number, block.timestamp, block.transactions.length);-\`\`\`--### Call a Smart Contract--\`\`\`javascript-const erc20Abi = ['function balanceOf(address) view returns (uint256)'];-const usdc = new ethers.Contract('0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', erc20Abi, provider);-const balance = await usdc.balanceOf('0xYourAddress');-\`\`\`--### Send a Transaction--\`\`\`javascript-const signer = new ethers.Wallet(process.env.PRIVATE_KEY, provider);-const tx = await signer.sendTransaction({- to: '0xRecipient',- value: ethers.parseEther('0.01')-});-await tx.wait();-\`\`\`--## Raw JSON-RPC--\`\`\`javascript-const res = await fetch(process.env.ETH_RPC_URL, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- jsonrpc: '2.0',- id: 1,- method: 'eth_getBalance',- params: ['0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045', 'latest']- })-});-const { result } = await res.json();-console.log(parseInt(result, 16) / 1e18); // ETH balance-\`\`\`--## Event Logs--\`\`\`javascript-const logs = await provider.getLogs({- address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC- topics: [ethers.id('Transfer(address,address,uint256)')],- fromBlock: -1000 // last 1000 blocks-});-\`\`\`--## Key RPC Methods Reference--| Method | Description |-|---|---|-| \`eth_blockNumber\` | Latest block number |-| \`eth_getBalance\` | ETH balance of address |-| \`eth_getTransactionByHash\` | Transaction details |-| \`eth_getTransactionReceipt\` | Receipt + logs |-| \`eth_call\` | Read smart contract state |-| \`eth_sendRawTransaction\` | Broadcast signed tx |-| \`eth_getLogs\` | Query event logs |-| \`eth_estimateGas\` | Estimate gas cost |-| \`eth_gasPrice\` | Current gas price |--## Node Providers Compared--| Provider | Free tier | Chains | Websockets |-|---|---|---|---|-| Alchemy | 300M compute units/mo | 20+ | Yes |-| Infura | 100K req/day | 10+ | Yes |-| QuickNode | 10M credits/mo | 30+ | Yes |-| Ankr | 30M req/mo | 40+ | Yes |-| Llamarpc | Unlimited (rate limited) | 5 | No |--## Archive Nodes--Standard nodes only keep recent state. For historical queries (e.g., balance at block 10,000,000), you need an archive node. Alchemy and QuickNode both offer archive access on paid plans.`- },- {- slug: 'solana-api-guide',- title: 'Solana RPC API Guide for Developers (2026)',- meta: 'Learn to use the Solana JSON-RPC API — read accounts, send transactions, subscribe to events, and query on-chain data with JavaScript examples.',- keywords: 'Solana API, Solana RPC, Solana JSON-RPC, @solana/web3.js, Solana developer API',- content: `# Solana RPC API Guide for Developers (2026)--Solana's JSON-RPC API is the primary interface for building on the Solana blockchain. With sub-second finality and ~4,000 TPS, Solana is the go-to chain for high-frequency DeFi, NFTs, and payments.--## Setup--\`\`\`bash-npm install @solana/web3.js-\`\`\`--\`\`\`javascript-import { Connection, PublicKey, LAMPORTS_PER_SOL } from '@solana/web3.js';--const connection = new Connection(process.env.SOLANA_RPC_URL, 'confirmed');-\`\`\`--## Get SOL Balance--\`\`\`javascript-const pubkey = new PublicKey('9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM');-const balance = await connection.getBalance(pubkey);-console.log(balance / LAMPORTS_PER_SOL); // SOL balance-\`\`\`--## Get Token Balances (SPL)--\`\`\`javascript-const tokenAccounts = await connection.getParsedTokenAccountsByOwner(pubkey, {- programId: new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA')-});--tokenAccounts.value.forEach(({ account }) => {- const { mint, tokenAmount } = account.data.parsed.info;- console.log(mint, tokenAmount.uiAmount);-});-\`\`\`--## Send a Transaction--\`\`\`javascript-import { SystemProgram, Transaction, Keypair, sendAndConfirmTransaction } from '@solana/web3.js';--const from = Keypair.fromSecretKey(Buffer.from(process.env.PRIVATE_KEY, 'base64'));-const to = new PublicKey('RecipientPublicKey');--const tx = new Transaction().add(- SystemProgram.transfer({- fromPubkey: from.publicKey,- toPubkey: to,- lamports: 0.01 * LAMPORTS_PER_SOL- })-);--const sig = await sendAndConfirmTransaction(connection, tx, [from]);-console.log('Signature:', sig);-\`\`\`--## Subscribe to Account Changes--\`\`\`javascript-const subscriptionId = connection.onAccountChange(pubkey, (accountInfo) => {- console.log('Balance changed:', accountInfo.lamports / LAMPORTS_PER_SOL);-});--// Unsubscribe when done-await connection.removeAccountChangeListener(subscriptionId);-\`\`\`--## Key RPC Methods--| Method | Description |-|---|---|-| \`getBalance\` | SOL balance |-| \`getAccountInfo\` | Raw account data |-| \`getTransaction\` | Transaction details |-| \`getBlock\` | Block with transactions |-| \`sendTransaction\` | Broadcast transaction |-| \`simulateTransaction\` | Dry-run without broadcasting |-| \`getTokenAccountsByOwner\` | All SPL token accounts |-| \`getProgramAccounts\` | All accounts owned by a program |--## RPC Providers for Solana--- **Helius** — best Solana-specific provider, advanced APIs (DAS, webhooks)-- **QuickNode** — reliable, multi-region-- **Alchemy** — Solana support added 2024-- **Triton** — high-performance, staked connections--## getProgramAccounts — Power Query--This method returns all accounts owned by a program — essential for DeFi integrations.--\`\`\`javascript-const accounts = await connection.getProgramAccounts(- new PublicKey('675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8'), // Raydium AMM- {- filters: [{ dataSize: 752 }] // filter by account size- }-);-\`\`\``- },- {- slug: 'alchemy-api-guide',- title: 'Alchemy API Guide: Enhanced Web3 APIs Explained (2026)',- meta: 'Complete guide to Alchemy APIs — NFT API, Token API, Transfers API, Webhooks, and Notify. Build blockchain apps faster with Alchemy enhanced APIs.',- keywords: 'Alchemy API, Alchemy NFT API, Alchemy Transfers API, Alchemy Web3, blockchain API',- content: `# Alchemy API Guide: Enhanced Web3 APIs Explained (2026)--Alchemy is the leading blockchain infrastructure provider, offering standard JSON-RPC plus a suite of enhanced APIs that make common tasks dramatically easier.--## Setup--\`\`\`bash-npm install alchemy-sdk-\`\`\`--\`\`\`javascript-import { Alchemy, Network } from 'alchemy-sdk';--const alchemy = new Alchemy({- apiKey: process.env.ALCHEMY_API_KEY,- network: Network.ETH_MAINNET-});-\`\`\`--## NFT API--Get all NFTs owned by a wallet — no manual event log parsing required.--\`\`\`javascript-const nfts = await alchemy.nft.getNftsForOwner('0xAddress');-nfts.ownedNfts.forEach(nft => {- console.log(nft.contract.address, nft.tokenId, nft.title);-});-\`\`\`--Get NFT metadata:--\`\`\`javascript-const nft = await alchemy.nft.getNftMetadata('0xContractAddress', '1');-console.log(nft.title, nft.description, nft.image.originalUrl);-\`\`\`--## Token API--Get all ERC-20 token balances for a wallet:--\`\`\`javascript-const balances = await alchemy.core.getTokenBalances('0xAddress');-const nonZero = balances.tokenBalances.filter(t => t.tokenBalance !== '0x0');-\`\`\`--Get token metadata:--\`\`\`javascript-const meta = await alchemy.core.getTokenMetadata('0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48');-console.log(meta.name, meta.symbol, meta.decimals); // USD Coin, USDC, 6-\`\`\`--## Transfers API--Get the full transfer history for any address — much faster than scanning logs manually.--\`\`\`javascript-const transfers = await alchemy.core.getAssetTransfers({- fromAddress: '0xAddress',- category: ['erc20', 'erc721', 'erc1155', 'external'],- withMetadata: true,- maxCount: 100-});-\`\`\`--## Webhooks (Notify)--Get real-time notifications via HTTP webhook when events happen on-chain.--\`\`\`javascript-// Create a webhook for address activity-const webhook = await alchemy.notify.createWebhook(- 'https://yourapp.com/webhook',- WebhookType.ADDRESS_ACTIVITY,- { addresses: ['0xYourAddress'] }-);-\`\`\`--**Webhook types:**-- \`MINED_TRANSACTION\` — tx confirmed-- \`DROPPED_TRANSACTION\` — tx dropped from mempool-- \`ADDRESS_ACTIVITY\` — any activity on watched addresses-- \`NFT_ACTIVITY\` — NFT transfers--## Supported Networks--Alchemy supports 20+ chains including Ethereum, Polygon, Arbitrum, Optimism, Base, Solana, Starknet, Astar, and more.--## Compute Units--Alchemy bills by "compute units" (CUs). Standard JSON-RPC calls cost 1–50 CUs. Enhanced APIs cost more — e.g., \`getNftsForOwner\` costs 100 CUs. The free tier includes 300M CUs/month.`- },- {- slug: 'coingecko-api-guide',- title: 'CoinGecko API Guide: Free Crypto Market Data (2026)',- meta: 'How to use the CoinGecko API for free crypto price data, market cap, historical OHLCV, DeFi data, and NFT floor prices. No API key required for basic use.',- keywords: 'CoinGecko API, CoinGecko free API, crypto price API, crypto market data free',- content: `# CoinGecko API Guide: Free Crypto Market Data (2026)--CoinGecko offers one of the most comprehensive free crypto market data APIs, covering 10,000+ cryptocurrencies, DeFi protocols, and NFT collections.--## Base URL--- Free (no key): \`https://api.coingecko.com/api/v3\`-- Pro: \`https://pro-api.coingecko.com/api/v3\`--## Get Current Price--\`\`\`javascript-const res = await fetch(- 'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,ethereum,solana&vs_currencies=usd,btc'-);-const prices = await res.json();-console.log(prices.bitcoin.usd); // e.g., 95000-\`\`\`--## Get Market Data--\`\`\`javascript-const res = await fetch(- 'https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1'-);-const coins = await res.json();-// Returns: id, symbol, name, current_price, market_cap, total_volume, price_change_percentage_24h-\`\`\`--## Historical Price Data--\`\`\`javascript-// Daily prices for last 365 days-const res = await fetch(- 'https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=usd&days=365&interval=daily'-);-const { prices, market_caps, total_volumes } = await res.json();-// prices = [[timestamp, price], ...]-\`\`\`--## OHLCV Data--\`\`\`javascript-const res = await fetch(- 'https://api.coingecko.com/api/v3/coins/ethereum/ohlc?vs_currency=usd&days=30'-);-const ohlc = await res.json();-// [[timestamp, open, high, low, close], ...]-\`\`\`--## Coin Details--\`\`\`javascript-const res = await fetch(- 'https://api.coingecko.com/api/v3/coins/bitcoin?localization=false&tickers=false&community_data=false'-);-const coin = await res.json();-console.log(coin.market_data.circulating_supply);-console.log(coin.market_data.ath.usd); // All-time high-\`\`\`--## DeFi Data--\`\`\`javascript-// Global DeFi stats-const res = await fetch('https://api.coingecko.com/api/v3/global/decentralized_finance_defi');-const { data } = await res.json();-console.log(data.defi_market_cap, data.trading_volume_24h);-\`\`\`--## NFT Floor Prices--\`\`\`javascript-const res = await fetch('https://api.coingecko.com/api/v3/nfts/cryptopunks');-const nft = await res.json();-console.log(nft.floor_price.native_currency); // Floor in ETH-\`\`\`--## Rate Limits--| Tier | Calls/min | Monthly |-|---|---|---|-| Free (no key) | 30 | ~43K |-| Demo (free key) | 30 | ~43K |-| Analyst | 500 | 720K |-| Lite | 500 | 720K |-| Pro | 500 | 720K |-| Enterprise | Custom | Custom |--## Coin ID Lookup--CoinGecko uses string IDs (e.g., \`bitcoin\`, \`ethereum\`), not symbols. Get the full list:--\`\`\`javascript-const res = await fetch('https://api.coingecko.com/api/v3/coins/list');-const coins = await res.json(); // [{id, symbol, name}, ...]-\`\`\``- },- {- slug: 'infura-api-guide',- title: 'Infura API Guide: Ethereum and IPFS Infrastructure (2026)',- meta: 'How to use Infura for Ethereum JSON-RPC, IPFS, and multi-chain access. Setup, authentication, rate limits, and code examples for Node.js developers.',- keywords: 'Infura API, Infura Ethereum, Infura IPFS, Infura Web3 provider, Ethereum node API',- content: `# Infura API Guide: Ethereum and IPFS Infrastructure (2026)--Infura, by ConsenSys, is one of the oldest and most trusted Ethereum node providers. It supports Ethereum mainnet, testnets, Layer 2s, and IPFS.--## Getting Started--1. Create an account at infura.io-2. Create a new project — note your **Project ID** and **API Key**-3. Your RPC endpoint: \`https://mainnet.infura.io/v3/<PROJECT_ID>\`--\`\`\`javascript-import { ethers } from 'ethers';--const provider = new ethers.JsonRpcProvider(- \`https://mainnet.infura.io/v3/\${process.env.INFURA_PROJECT_ID}\`-);-\`\`\`--## Supported Networks--| Network | Endpoint |-|---|---|-| Ethereum Mainnet | \`mainnet.infura.io/v3/<id>\` |-| Sepolia Testnet | \`sepolia.infura.io/v3/<id>\` |-| Polygon Mainnet | \`polygon-mainnet.infura.io/v3/<id>\` |-| Arbitrum One | \`arbitrum-mainnet.infura.io/v3/<id>\` |-| Optimism | \`optimism-mainnet.infura.io/v3/<id>\` |-| Base | \`base-mainnet.infura.io/v3/<id>\` |-| Linea | \`linea-mainnet.infura.io/v3/<id>\` |-| Avalanche | \`avalanche-mainnet.infura.io/v3/<id>\` |--## IPFS API--Infura provides a dedicated IPFS gateway and upload API.--\`\`\`javascript-// Upload a file to IPFS-const formData = new FormData();-formData.append('file', fileBlob);--const res = await fetch('https://ipfs.infura.io:5001/api/v0/add', {- method: 'POST',- headers: {- 'Authorization': 'Basic ' + Buffer.from(\`\${projectId}:\${projectSecret}\`).toString('base64')- },- body: formData-});-const { Hash } = await res.json();-console.log(\`https://ipfs.io/ipfs/\${Hash}\`);-\`\`\`--## WebSocket Endpoint--\`\`\`javascript-const ws = new ethers.WebSocketProvider(- \`wss://mainnet.infura.io/ws/v3/\${process.env.INFURA_PROJECT_ID}\`-);--// Subscribe to new blocks-ws.on('block', (blockNumber) => {- console.log('New block:', blockNumber);-});-\`\`\`--## Rate Limits--- Free: 100,000 requests/day-- Developer: 300K/day-- Team: 3M/day-- Growth: 15M/day--## Secret Key Authentication--For production, require a secret key alongside your project ID to prevent unauthorized use of your endpoint.--Enable in: Dashboard → Project Settings → Security → Require API Key Secret--\`\`\`javascript-const provider = new ethers.JsonRpcProvider({- url: \`https://mainnet.infura.io/v3/\${projectId}\`,- user: '',- password: projectSecret-});-\`\`\``- },- {- slug: 'quicknode-api-guide',- title: 'QuickNode API Guide: Multi-Chain RPC for Builders (2026)',- meta: 'Learn how to use QuickNode for fast multi-chain RPC access, Streams data pipelines, Functions serverless compute, and marketplace add-ons.',- keywords: 'QuickNode API, QuickNode RPC, QuickNode Streams, multi-chain API, QuickNode setup',- content: `# QuickNode API Guide: Multi-Chain RPC for Builders (2026)--QuickNode is a high-performance blockchain infrastructure provider supporting 30+ chains. Beyond standard RPC, it offers Streams (real-time data pipelines), Functions (serverless compute), and a marketplace of add-ons.--## Setup--Create an endpoint at quicknode.com. You'll get a unique HTTPS and WSS URL.--\`\`\`javascript-import { ethers } from 'ethers';--const provider = new ethers.JsonRpcProvider(process.env.QUICKNODE_HTTP_URL);-const wsProvider = new ethers.WebSocketProvider(process.env.QUICKNODE_WSS_URL);-\`\`\`--## Supported Chains (sample)--Ethereum, Solana, Bitcoin, BNB Chain, Polygon, Avalanche, Arbitrum, Optimism, Base, zkSync, Starknet, Aptos, Sui, TON, Cosmos, Near, Fantom, Celo, Moonbeam, and more.--## QuickNode SDK--\`\`\`bash-npm install @quicknode/sdk-\`\`\`--\`\`\`javascript-import QuickNode from '@quicknode/sdk';--const qn = new QuickNode.Core({- endpointUrl: process.env.QUICKNODE_HTTP_URL-});--// Get NFT assets for an address-const nfts = await qn.client.qn_fetchNFTsByCollection({- collection: '0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D', // BAYC- page: 1,- perPage: 10-});-\`\`\`--## Streams: Real-Time Data Pipelines--Streams lets you pipe on-chain data directly to a destination (HTTP, Kafka, S3, Snowflake) without polling.--\`\`\`json-{- "name": "ETH Transfers",- "network": "ethereum-mainnet",- "dataset": "receipts",- "filter_function": "function main(data) { return data.filter(r => r.logs.length > 0); }",- "destination": "https://yourapp.com/webhook",- "status": "active"-}-\`\`\`--## Functions: Serverless On-Chain Compute--Run JavaScript serverless functions that execute on QuickNode's infrastructure and have native RPC access.--\`\`\`javascript-// A QuickNode Function-export async function main(params) {- const block = await eth_blockNumber();- const price = await fetchTokenPrice('ETH');- return { block, price };-}-\`\`\`--## Add-ons Marketplace--QuickNode's marketplace includes:-- **Token and NFT API** — enhanced asset queries-- **DeFi Pulse Data** — DeFi protocol metrics-- **Etherscan Compat** — Etherscan-style API on any chain-- **Trader Joe / Uniswap** — DEX analytics--## Rate Limits and Plans--| Plan | Req/s | Monthly credits |-|---|---|---|-| Free | 15 | 10M |-| Build | 50 | Unlimited |-| Scale | 100+ | Unlimited |`- },- {- slug: 'moralis-api-guide',- title: 'Moralis API Guide: Web3 Data APIs for Developers (2026)',- meta: 'Full guide to Moralis APIs — Wallet API, NFT API, Token API, DeFi API, and Streams. Build Web3 apps without running your own node infrastructure.',- keywords: 'Moralis API, Moralis Web3 API, Moralis NFT API, Moralis Wallet API, Web3 data API',- content: `# Moralis API Guide: Web3 Data APIs for Developers (2026)--Moralis provides high-level Web3 APIs that abstract the complexity of raw RPC calls. Instead of parsing raw logs and state, you get clean structured data for wallets, tokens, NFTs, and DeFi positions.--## Setup--\`\`\`bash-npm install moralis-\`\`\`--\`\`\`javascript-import Moralis from 'moralis';--await Moralis.start({ apiKey: process.env.MORALIS_API_KEY });-\`\`\`--## Wallet API--Get native balance + token balances in one call:--\`\`\`javascript-const portfolio = await Moralis.EvmApi.wallets.getWalletTokenBalancesPrice({- address: '0xAddress',- chain: '0x1' // Ethereum-});--portfolio.result.forEach(token => {- console.log(token.symbol, token.balanceFormatted, token.usdValue);-});-\`\`\`--Get wallet net worth:--\`\`\`javascript-const netWorth = await Moralis.EvmApi.wallets.getWalletNetWorth({- address: '0xAddress',- excludeSpam: true,- excludeUnverifiedContracts: true-});-console.log(netWorth.result.totalNetworth); // USD value-\`\`\`--## NFT API--\`\`\`javascript-// All NFTs owned by an address-const nfts = await Moralis.EvmApi.nft.getWalletNFTs({- address: '0xAddress',- chain: '0x1',- mediaItems: true-});--// NFT collection stats-const stats = await Moralis.EvmApi.nft.getNFTCollectionStats({- address: '0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D' // BAYC-});-console.log(stats.result.floor_price, stats.result.volume_usd);-\`\`\`--## Token API--\`\`\`javascript-// Token price with liquidity data-const price = await Moralis.EvmApi.token.getTokenPrice({- address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC- chain: '0x1'-});-console.log(price.result.usdPrice, price.result.exchangeName);-\`\`\`--## DeFi API--\`\`\`javascript-// All DeFi positions (Uniswap, Aave, Compound, etc.)-const positions = await Moralis.EvmApi.defi.getDefiPositionsSummary({- address: '0xAddress',- chain: '0x1'-});-\`\`\`--## Streams (Webhooks)--Get real-time webhooks when on-chain events occur:--\`\`\`javascript-const stream = await Moralis.Streams.add({- chains: ['0x1'],- description: 'USDC transfers',- tag: 'usdc-transfers',- webhookUrl: 'https://yourapp.com/webhook',- abi: transferAbi,- topic0: ['Transfer(address,address,uint256)'],- address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48'-});-\`\`\`--## Supported Chains--Moralis supports 30+ EVM chains plus Solana, Aptos, and more.--## Rate Limits--Free tier: 40,000 CU/day. Paid plans start at $49/month for 100M CU/month.`- },- {- slug: 'the-graph-api-guide',- title: 'The Graph API Guide: Query Blockchain Data with GraphQL (2026)',- meta: 'Learn how to use The Graph protocol to query on-chain data with GraphQL. Deploy subgraphs, query Uniswap, Aave, and custom protocol data.',- keywords: 'The Graph API, GraphQL blockchain, subgraph API, Uniswap subgraph, The Graph protocol',- content: `# The Graph API Guide: Query Blockchain Data with GraphQL (2026)--The Graph is a decentralized indexing protocol that lets you query blockchain data with GraphQL. It powers data for Uniswap, Aave, Compound, and thousands of other DeFi protocols.--## How It Works--1. A **subgraph** defines which on-chain events to index and how to structure them-2. Indexers process the subgraph and store the data-3. You query the subgraph via a GraphQL API endpoint--## Querying a Public Subgraph--No API key needed for hosted service subgraphs:--\`\`\`javascript-const UNISWAP_V3 = 'https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v3';--const query = \`{- pools(first: 5, orderBy: totalValueLockedUSD, orderDirection: desc) {- id- token0 { symbol }- token1 { symbol }- feeTier- totalValueLockedUSD- volumeUSD- }-}\`;--const res = await fetch(UNISWAP_V3, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ query })-});-const { data } = await res.json();-\`\`\`--## Decentralized Network (requires API key)--\`\`\`javascript-const GRAPH_API_KEY = process.env.GRAPH_API_KEY;-const SUBGRAPH_ID = 'ELUcwgpm14LKPLrBRuVvPvNKHQ9HvwmtKgKSH855M4Nd'; // Uniswap V3--const endpoint = \`https://gateway.thegraph.com/api/\${GRAPH_API_KEY}/subgraphs/id/\${SUBGRAPH_ID}\`;-\`\`\`--## Popular Subgraphs--| Protocol | Subgraph |-|---|---|-| Uniswap V3 | uniswap/uniswap-v3 |-| Aave V3 | aave/protocol-v3 |-| Compound V3 | messari/compound-v3-ethereum |-| Curve | messari/curve-finance-ethereum |-| Balancer V2 | balancer-labs/balancer-v2 |-| ENS | ensdomains/ensregistrar |-| Lens Protocol | lens-protocol/lens |--## Query With Variables--\`\`\`javascript-const query = \`- query GetTokenSwaps($token: String!, $limit: Int!) {- swaps(- where: { token0: $token }- first: $limit- orderBy: timestamp- orderDirection: desc- ) {- id- timestamp- amountUSD- token0 { symbol }- token1 { symbol }- }- }-\`;--const res = await fetch(endpoint, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- query,- variables: { token: '0xA0b86991c...', limit: 20 }- })-});-\`\`\`--## Writing a Subgraph--\`\`\`bash-npm install -g @graphprotocol/graph-cli-graph init --product hosted-service my-subgraph-\`\`\`--**schema.graphql:**-\`\`\`graphql-type Transfer @entity {- id: ID!- from: Bytes!- to: Bytes!- value: BigInt!- timestamp: BigInt!-}-\`\`\`--**mapping.ts:**-\`\`\`typescript-export function handleTransfer(event: TransferEvent): void {- let transfer = new Transfer(event.transaction.hash.toHex());- transfer.from = event.params.from;- transfer.to = event.params.to;- transfer.value = event.params.value;- transfer.timestamp = event.block.timestamp;- transfer.save();-}-\`\`\``- },- {- slug: 'crypto-websocket-api-guide',- title: 'Crypto WebSocket APIs: Real-Time Data for Trading Apps (2026)',- meta: 'Master WebSocket APIs for cryptocurrency — live price feeds, order book streams, trade data from Binance, Coinbase, Kraken, and decentralized sources.',- keywords: 'crypto WebSocket API, real-time crypto price, live order book API, trading WebSocket, crypto streaming API',- content: `# Crypto WebSocket APIs: Real-Time Data for Trading Apps (2026)--WebSocket connections are essential for any crypto application that needs live data — trading bots, price tickers, order book visualizations, and liquidation dashboards all depend on persistent, low-latency streams.--## REST vs WebSocket--| | REST | WebSocket |-|---|---|---|-| Connection | New per request | Persistent |-| Latency | 50–200ms | 5–20ms |-| Data freshness | Polling interval | Real-time push |-| Server load | High (polling) | Low |-| Best for | OHLCV, account data | Live prices, order books |--## Binance WebSocket--\`\`\`javascript-// Single stream-const ws = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt@ticker');--// Combined streams-const ws = new WebSocket('wss://stream.binance.com:9443/stream?streams=btcusdt@ticker/ethusdt@ticker');--ws.onmessage = ({ data }) => {- const msg = JSON.parse(data);- const tick = msg.data || msg; // combined vs single- console.log(tick.s, tick.c); // symbol, close price-};-\`\`\`--**Binance stream types:**-- \`<symbol>@aggTrade\` — aggregated trades-- \`<symbol>@kline_<interval>\` — candles (1m, 5m, 1h, 1d...)-- \`<symbol>@depth<levels>\` — partial order book (5, 10, or 20 levels)-- \`<symbol>@depth@100ms\` — diff order book updates-- \`!ticker@arr\` — all symbols ticker--## Coinbase WebSocket--\`\`\`javascript-const ws = new WebSocket('wss://advanced-trade-ws.coinbase.com');--ws.onopen = () => {- ws.send(JSON.stringify({- type: 'subscribe',- product_ids: ['BTC-USD', 'ETH-USD'],- channel: 'level2'- }));-};--ws.onmessage = ({ data }) => {- const msg = JSON.parse(data);- if (msg.channel === 'l2_data') {- msg.events.forEach(e => {- e.updates.forEach(u => console.log(u.side, u.price_level, u.new_quantity));- });- }-};-\`\`\`--## Kraken WebSocket--\`\`\`javascript-const ws = new WebSocket('wss://ws.kraken.com/v2');--ws.onopen = () => {- ws.send(JSON.stringify({- method: 'subscribe',- params: {- channel: 'book',- symbol: ['BTC/USD'],- depth: 10- }- }));-};-\`\`\`--## Reconnection Logic--WebSocket connections drop. Always implement reconnection:--\`\`\`javascript-class ReconnectingWebSocket {- constructor(url, onMessage) {- this.url = url;- this.onMessage = onMessage;- this.connect();- }-- connect() {- this.ws = new WebSocket(this.url);- this.ws.onmessage = ({ data }) => this.onMessage(JSON.parse(data));- this.ws.onclose = () => {- console.log('Disconnected, reconnecting in 3s...');- setTimeout(() => this.connect(), 3000);- };- this.ws.onerror = (err) => console.error('WS error:', err);- }-- send(data) {- if (this.ws.readyState === WebSocket.OPEN) {- this.ws.send(JSON.stringify(data));- }- }-}-\`\`\`--## Ethereum WebSocket (Events)--\`\`\`javascript-import { ethers } from 'ethers';--const provider = new ethers.WebSocketProvider(process.env.ETH_WSS_URL);--// New blocks-provider.on('block', blockNumber => console.log('Block:', blockNumber));--// ERC-20 transfers-const usdc = new ethers.Contract(USDC_ADDRESS, ERC20_ABI, provider);-usdc.on('Transfer', (from, to, value, event) => {- console.log(\`\${from} → \${to}: \${ethers.formatUnits(value, 6)} USDC\`);-});-\`\`\`--## Heartbeat / Ping-Pong--Most providers require a ping every 30–60 seconds to keep connections alive:--\`\`\`javascript-setInterval(() => {- if (ws.readyState === WebSocket.OPEN) ws.ping();-}, 30000);-\`\`\``- },- {- slug: 'defi-llama-api-guide',- title: 'DeFiLlama API Guide: Free DeFi TVL and Protocol Data (2026)',- meta: 'Learn to use the DeFiLlama API for DeFi TVL, protocol revenue, yields, stablecoin data, and bridges — completely free with no API key required.',- keywords: 'DeFiLlama API, DeFi TVL API, DeFi protocol data API, DeFiLlama free, yield API',- content: `# DeFiLlama API Guide: Free DeFi TVL and Protocol Data (2026)--DeFiLlama is the leading DeFi analytics platform, and its API is completely free with no API key required. It covers TVL, revenue, yields, stablecoins, bridges, and more across 200+ chains and 3,000+ protocols.--## Base URL--\`https://api.llama.fi\`--No authentication required.--## TVL Data--\`\`\`javascript-// Global DeFi TVL-const res = await fetch('https://api.llama.fi/v2/globalCharts');-const data = await res.json();-// [{date, totalLiquidityUSD}, ...]--// All protocols with current TVL-const protocols = await fetch('https://api.llama.fi/protocols').then(r => r.json());-protocols.slice(0, 5).forEach(p => {- console.log(p.name, p.chain, \`$\${(p.tvl / 1e9).toFixed(2)}B\`);-});--// Single protocol TVL history-const aave = await fetch('https://api.llama.fi/protocol/aave').then(r => r.json());-console.log(aave.tvl); // Historical TVL array-\`\`\`--## Chain TVL--\`\`\`javascript-// TVL by chain-const chains = await fetch('https://api.llama.fi/v2/chains').then(r => r.json());-chains.sort((a, b) => b.tvl - a.tvl).slice(0, 10).forEach(c => {- console.log(c.name, \`$\${(c.tvl / 1e9).toFixed(1)}B\`);-});-\`\`\`--## Yields (APY Data)--\`\`\`javascript-const pools = await fetch('https://yields.llama.fi/pools').then(r => r.json());--// Find highest yield stablecoin pools-const stablePools = pools.data- .filter(p => p.stablecoin && p.tvlUsd > 1_000_000)- .sort((a, b) => b.apy - a.apy)- .slice(0, 10);--stablePools.forEach(p => {- console.log(\`\${p.project} \${p.symbol}: \${p.apy.toFixed(2)}% APY (TVL: $\${(p.tvlUsd/1e6).toFixed(0)}M)\`);-});-\`\`\`--## Stablecoin Data--\`\`\`javascript-// All stablecoins-const stables = await fetch('https://stablecoins.llama.fi/stablecoins').then(r => r.json());--// USDC circulating supply-const usdc = stables.peggedAssets.find(s => s.symbol === 'USDC');-console.log('USDC mcap:', usdc.circulating.peggedUSD);--// Historical peg data-const history = await fetch('https://stablecoins.llama.fi/stablecoincharts/all').then(r => r.json());-\`\`\`--## Protocol Revenue--\`\`\`javascript-// Revenue for all protocols-const revenue = await fetch('https://api.llama.fi/overview/fees?excludeTotalDataChartBreakdown=true').then(r => r.json());--revenue.protocols.sort((a, b) => (b.total30d || 0) - (a.total30d || 0)).slice(0, 5).forEach(p => {- console.log(p.name, \`30d revenue: $\${(p.total30d / 1e6).toFixed(1)}M\`);-});-\`\`\`--## Bridge Volume--\`\`\`javascript-const bridges = await fetch('https://bridges.llama.fi/bridges').then(r => r.json());-bridges.bridges.sort((a, b) => b.lastMonthVolume - a.lastMonthVolume).slice(0, 5).forEach(b => {- console.log(b.displayName, \`Monthly: $\${(b.lastMonthVolume / 1e9).toFixed(1)}B\`);-});-\`\`\`--## API Endpoints Summary--| Endpoint | Data |-|---|---|-| \`/protocols\` | All protocols + TVL |-| \`/protocol/{slug}\` | Protocol TVL history |-| \`/v2/chains\` | TVL by chain |-| \`/v2/globalCharts\` | Global DeFi TVL chart |-| \`/overview/fees\` | Protocol revenue |-| \`yields.llama.fi/pools\` | Yield opportunities |-| \`stablecoins.llama.fi/stablecoins\` | Stablecoin data |-| \`bridges.llama.fi/bridges\` | Bridge volume |`- },- {- slug: 'kraken-api-guide',- title: 'Kraken API Guide: Trading and Market Data for Developers (2026)',- meta: 'Complete guide to the Kraken API — authentication, order placement, margin trading, WebSocket feeds, and staking endpoints with code examples.',- keywords: 'Kraken API, Kraken trading API, Kraken WebSocket, Kraken REST API, crypto exchange API',- content: `# Kraken API Guide: Trading and Market Data for Developers (2026)--Kraken offers a robust API for spot trading, futures, margin, staking, and market data. It's especially popular with European traders and institutions due to its strong regulatory compliance.--## Base URLs--- REST: \`https://api.kraken.com\`-- WebSocket: \`wss://ws.kraken.com/v2\`-- Futures REST: \`https://futures.kraken.com\`--## Authentication--Kraken uses HMAC-SHA512 with a nonce:--\`\`\`javascript-import crypto from 'crypto';--function getKrakenSignature(path, postData, secret) {- const { nonce } = postData;- const message = postData.nonce + new URLSearchParams(postData).toString();- const secret_buffer = Buffer.from(secret, 'base64');- const hash = crypto.createHash('sha256').update(nonce + message).digest('binary');- const hmac = crypto.createHmac('sha512', secret_buffer);- return hmac.update(path + hash, 'binary').digest('base64');-}--async function privateRequest(path, data, apiKey, apiSecret) {- const postData = { nonce: Date.now().toString(), ...data };- const signature = getKrakenSignature('/0' + path, postData, apiSecret);-- const res = await fetch(\`https://api.kraken.com/0\${path}\`, {- method: 'POST',- headers: {- 'API-Key': apiKey,- 'API-Sign': signature,- 'Content-Type': 'application/x-www-form-urlencoded'- },- body: new URLSearchParams(postData)- });- return res.json();-}-\`\`\`--## Market Data (Public)--\`\`\`javascript-// Ticker for multiple pairs-const res = await fetch('https://api.kraken.com/0/public/Ticker?pair=XBTUSD,ETHUSD');-const { result } = await res.json();-console.log(result.XXBTZUSD.c[0]); // Last trade price--// OHLCV data-const ohlc = await fetch('https://api.kraken.com/0/public/OHLC?pair=XBTUSD&interval=60');-\`\`\`--## Placing Orders--\`\`\`javascript-const order = await privateRequest('/private/AddOrder', {- pair: 'XBTUSD',- type: 'buy',- ordertype: 'limit',- price: '50000',- volume: '0.001',- validate: false // set true to test without placing-}, apiKey, apiSecret);-console.log(order.result.txid);-\`\`\`--## WebSocket v2--\`\`\`javascript-const ws = new WebSocket('wss://ws.kraken.com/v2');--ws.onopen = () => {- // Subscribe to ticker- ws.send(JSON.stringify({- method: 'subscribe',- params: { channel: 'ticker', symbol: ['BTC/USD', 'ETH/USD'] }- }));-- // Subscribe to order book- ws.send(JSON.stringify({- method: 'subscribe',- params: { channel: 'book', symbol: ['BTC/USD'], depth: 10 }- }));-};-\`\`\`--## Staking API--\`\`\`javascript-// Get stakeable assets-const stakeable = await privateRequest('/private/Staking/Assets', {}, apiKey, apiSecret);--// Stake assets-const stake = await privateRequest('/private/Stake', {- asset: 'ETH',- amount: '1.0',- method: 'ethereum-validator'-}, apiKey, apiSecret);-\`\`\`--## Rate Limits--Kraken uses a counter-based system. Your counter starts at 15 (Starter) or 20 (Intermediate/Pro). Each private call costs 1 counter, with 0.33–1 counter/second regeneration. Exceeding triggers HTTP 429.`- },- {- slug: 'etherscan-api-guide',- title: 'Etherscan API Guide: Blockchain Explorer Data for Developers (2026)',- meta: 'How to use the Etherscan API to fetch transactions, token transfers, gas prices, contract ABIs, and event logs. Free and paid tier explained.',- keywords: 'Etherscan API, Etherscan developer API, Ethereum explorer API, get transactions API, contract ABI API',- content: `# Etherscan API Guide: Blockchain Explorer Data for Developers (2026)--The Etherscan API gives programmatic access to the same data shown on etherscan.io — transaction history, token transfers, gas prices, contract source code, and more.--## Base URL--\`https://api.etherscan.io/api\`--Register at etherscan.io for a free API key (5 calls/second, 100K calls/day).--## Get ETH Balance--\`\`\`javascript-const key = process.env.ETHERSCAN_API_KEY;--const res = await fetch(- \`https://api.etherscan.io/api?module=account&action=balance&address=0xYourAddress&tag=latest&apikey=\${key}\`-);-const { result } = await res.json();-console.log(parseInt(result) / 1e18); // ETH balance-\`\`\`--## Get Transaction History--\`\`\`javascript-const res = await fetch(- \`https://api.etherscan.io/api?module=account&action=txlist&address=0xAddress&startblock=0&endblock=99999999&sort=desc&apikey=\${key}\`-);-const { result } = await res.json();-result.slice(0, 5).forEach(tx => {- console.log(tx.hash, tx.from, tx.to, parseInt(tx.value) / 1e18);-});-\`\`\`--## ERC-20 Token Transfers--\`\`\`javascript-const res = await fetch(- \`https://api.etherscan.io/api?module=account&action=tokentx&address=0xAddress&sort=desc&apikey=\${key}\`-);-const transfers = (await res.json()).result;-transfers.slice(0, 5).forEach(t => {- const value = parseInt(t.value) / Math.pow(10, parseInt(t.tokenDecimal));- console.log(\`\${t.tokenSymbol}: \${value}\`);-});-\`\`\`--## Gas Oracle--\`\`\`javascript-const res = await fetch(- \`https://api.etherscan.io/api?module=gastracker&action=gasoracle&apikey=\${key}\`-);-const { result } = await res.json();-console.log('Safe gas:', result.SafeGasPrice, 'Gwei');-console.log('Fast gas:', result.FastGasPrice, 'Gwei');-\`\`\`--## Get Contract ABI--\`\`\`javascript-const res = await fetch(- \`https://api.etherscan.io/api?module=contract&action=getabi&address=0xContractAddress&apikey=\${key}\`-);-const { result } = await res.json();-const abi = JSON.parse(result);-\`\`\`--## Get Contract Source Code--\`\`\`javascript-const res = await fetch(- \`https://api.etherscan.io/api?module=contract&action=getsourcecode&address=0xContractAddress&apikey=\${key}\`-);-const [contract] = (await res.json()).result;-console.log(contract.ContractName, contract.CompilerVersion);-\`\`\`--## Event Logs--\`\`\`javascript-const transferTopic = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef';--const res = await fetch(- \`https://api.etherscan.io/api?module=logs&action=getLogs&address=0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48&topic0=\${transferTopic}&fromBlock=21000000&toBlock=latest&apikey=\${key}\`-);-const logs = (await res.json()).result;-\`\`\`--## Multi-Chain Support--Etherscan has explorer APIs for: Polygon (polygonscan.com), BNB Chain (bscscan.com), Arbitrum (arbiscan.io), Optimism (optimistic.etherscan.io), Base (basescan.org), Avalanche (snowtrace.io), and more — same API format, different base URL.--## Rate Limits--| Plan | Calls/sec | Calls/day |-|---|---|---|-| Free | 5 | 100,000 |-| Standard | 10 | 500,000 |-| Advanced | 30 | 2,000,000 |`- },- {- slug: 'opensea-api-guide',- title: 'OpenSea API Guide: NFT Data and Trading (2026)',- meta: 'Complete guide to the OpenSea API — fetch NFT listings, collection stats, offers, floor prices, and place orders using the OpenSea SDK.',- keywords: 'OpenSea API, NFT API, OpenSea developer API, NFT listings API, NFT floor price API',- content: `# OpenSea API Guide: NFT Data and Trading (2026)--The OpenSea API provides access to NFT listings, sales, offers, collection stats, and the ability to create and fulfill orders programmatically.--## Authentication--Register at opensea.io/account/settings for a free API key.--\`\`\`javascript-const headers = {- 'X-API-KEY': process.env.OPENSEA_API_KEY,- 'Accept': 'application/json'-};-\`\`\`--## Get Collection Stats--\`\`\`javascript-const res = await fetch(- 'https://api.opensea.io/api/v2/collections/boredapeyachtclub/stats',- { headers }-);-const { total, intervals } = await res.json();-console.log('Floor:', total.floor_price, 'ETH');-console.log('24h Volume:', intervals[0].volume, 'ETH');-console.log('Total Supply:', total.num_owners, 'owners');-\`\`\`--## Get NFT Listings--\`\`\`javascript-const res = await fetch(- 'https://api.opensea.io/api/v2/listings/collection/boredapeyachtclub/best?limit=20',- { headers }-);-const { listings } = await res.json();-listings.forEach(l => {- const price = parseInt(l.price.current.value) / 1e18;- console.log(\`Token \${l.token_id}: \${price} ETH\`);-});-\`\`\`--## Get NFT Metadata--\`\`\`javascript-const res = await fetch(- 'https://api.opensea.io/api/v2/chain/ethereum/contract/0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D/nfts/1',- { headers }-);-const { nft } = await res.json();-console.log(nft.name, nft.image_url);-nft.traits.forEach(t => console.log(t.trait_type, t.value));-\`\`\`--## Get NFTs by Wallet--\`\`\`javascript-const res = await fetch(- 'https://api.opensea.io/api/v2/chain/ethereum/account/0xAddress/nfts?limit=50',- { headers }-);-const { nfts } = await res.json();-\`\`\`--## Recent Sales--\`\`\`javascript-const res = await fetch(- 'https://api.opensea.io/api/v2/events/collection/boredapeyachtclub?event_type=sale&limit=20',- { headers }-);-const { asset_events } = await res.json();-asset_events.forEach(e => {- const price = parseInt(e.payment.quantity) / 1e18;- console.log(\`Token \${e.nft.identifier}: sold for \${price} ETH\`);-});-\`\`\`--## Creating Listings (SDK)--\`\`\`javascript-import { OpenSeaSDK, Chain } from 'opensea-js';-import { ethers } from 'ethers';--const provider = new ethers.BrowserProvider(window.ethereum);-const signer = await provider.getSigner();--const sdk = new OpenSeaSDK(signer, {- chain: Chain.Mainnet,- apiKey: process.env.OPENSEA_API_KEY-});--const listing = await sdk.createListing({- asset: {- tokenId: '1',- tokenAddress: '0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D'- },- startAmount: 10, // 10 ETH- expirationTime: Math.round(Date.now() / 1000 + 86400) // 24h-});-\`\`\`--## Rate Limits--- Free: 4 requests/second-- Register for an API key: higher limits available-- Webhooks: real-time event delivery for sales, listings, offers`- },- {- slug: 'uniswap-api-guide',- title: 'Uniswap API Guide: DEX Data and Swap Integration (2026)',- meta: 'How to query Uniswap V3 pool data, execute swaps, get token prices, and access liquidity analytics using the Uniswap subgraph and SDK.',- keywords: 'Uniswap API, Uniswap V3 API, Uniswap subgraph, DEX API, token swap API',- content: `# Uniswap API Guide: DEX Data and Swap Integration (2026)--Uniswap is the largest decentralized exchange by volume. You can access its data via The Graph subgraph or execute swaps programmatically via the Uniswap SDK.--## Data via The Graph--\`\`\`javascript-const UNISWAP_V3 = 'https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v3';--async function graphQuery(query) {- const res = await fetch(UNISWAP_V3, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ query })- });- return (await res.json()).data;-}-\`\`\`--## Top Pools by TVL--\`\`\`javascript-const { pools } = await graphQuery(\`{- pools(first: 10, orderBy: totalValueLockedUSD, orderDirection: desc) {- id- token0 { symbol }- token1 { symbol }- feeTier- totalValueLockedUSD- volumeUSD- token0Price- token1Price- }-}\`);-\`\`\`--## Token Price--\`\`\`javascript-const { token } = await graphQuery(\`{- token(id: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48") {- symbol- derivedETH- tokenDayData(first: 7, orderBy: date, orderDirection: desc) {- date- priceUSD- volumeUSD- }- }-}\`);-\`\`\`--## Recent Swaps--\`\`\`javascript-const { swaps } = await graphQuery(\`{- swaps(first: 20, orderBy: timestamp, orderDirection: desc, where: {- pool: "0x8ad599c3a0ff1de082011efddc58f1908eb6e6d8"- }) {- id- timestamp- amount0- amount1- amountUSD- sender- recipient- }-}\`);-\`\`\`--## Execute a Swap (SDK)--\`\`\`bash-npm install @uniswap/v3-sdk @uniswap/sdk-core-\`\`\`--\`\`\`javascript-import { SwapRouter, AlphaRouter } from '@uniswap/smart-order-router';-import { Token, CurrencyAmount, TradeType, Percent } from '@uniswap/sdk-core';-import { ethers } from 'ethers';--const provider = new ethers.JsonRpcProvider(process.env.ETH_RPC_URL);-const router = new AlphaRouter({ chainId: 1, provider });--const WETH = new Token(1, '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', 18, 'WETH');-const USDC = new Token(1, '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', 6, 'USDC');--const route = await router.route(- CurrencyAmount.fromRawAmount(WETH, ethers.parseEther('0.1').toString()),- USDC,- TradeType.EXACT_INPUT,- {- slippageTolerance: new Percent(5, 1000), // 0.5%- deadline: Math.floor(Date.now() / 1000) + 300,- recipient: '0xYourAddress'- }-);--console.log('Expected output:', route.quote.toFixed(2), 'USDC');-console.log('Price impact:', route.trade.priceImpact.toFixed(2), '%');-\`\`\`--## Pool Contract Direct Interaction--\`\`\`javascript-const poolAbi = ['function slot0() view returns (uint160 sqrtPriceX96, int24 tick, ...)'];-const pool = new ethers.Contract(poolAddress, poolAbi, provider);-const { sqrtPriceX96, tick } = await pool.slot0();-\`\`\``- },- {- slug: 'crypto-payment-api-guide',- title: 'Crypto Payment APIs: Accept Cryptocurrency in Your App (2026)',- meta: 'Compare the top crypto payment APIs — Coinbase Commerce, NOWPayments, BitPay, and x402. Learn to accept Bitcoin, ETH, USDC, and other crypto payments.',- keywords: 'crypto payment API, accept Bitcoin API, USDC payment API, cryptocurrency checkout API, x402 payment protocol',- content: `# Crypto Payment APIs: Accept Cryptocurrency in Your App (2026)--Crypto payment APIs let your application accept Bitcoin, Ethereum, USDC, and other currencies without managing wallets manually. This guide covers the top providers and the emerging x402 standard.--## Top Crypto Payment Providers--| Provider | Supported Coins | Settlement | Fiat Conversion |-|---|---|---|---|-| Coinbase Commerce | BTC, ETH, USDC, SOL, DOGE, LTC | Crypto or USD | Yes |-| NOWPayments | 300+ coins | Crypto or fiat | Yes |-| BitPay | BTC, ETH, XRP, stablecoins | Crypto or USD | Yes |-| Stripe Crypto | USDC (Ethereum/Solana) | USD | Auto |-| x402 | USDC (Base, ETH, Solana) | Crypto | No |--## Coinbase Commerce--\`\`\`javascript-// Create a charge-const res = await fetch('https://api.commerce.coinbase.com/charges', {- method: 'POST',- headers: {- 'X-CC-Api-Key': process.env.COINBASE_COMMERCE_API_KEY,- 'Content-Type': 'application/json'- },- body: JSON.stringify({- name: 'Product Purchase',- description: 'Order #1234',- pricing_type: 'fixed_price',- local_price: { amount: '49.99', currency: 'USD' },- metadata: { order_id: '1234', customer_id: 'user_789' },- redirect_url: 'https://yourapp.com/success',- cancel_url: 'https://yourapp.com/cancel'- })-});-const { data } = await res.json();-// Redirect user to data.hosted_url-console.log('Payment URL:', data.hosted_url);-\`\`\`--## Webhooks (Coinbase Commerce)--\`\`\`javascript-import crypto from 'crypto';--app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {- const sig = req.headers['x-cc-webhook-signature'];- const computed = crypto- .createHmac('sha256', process.env.WEBHOOK_SECRET)- .update(req.body)- .digest('hex');-- if (sig !== computed) return res.status(400).send('Invalid signature');-- const { event } = JSON.parse(req.body);- if (event.type === 'charge:confirmed') {- console.log('Payment confirmed:', event.data.metadata.order_id);- // Fulfill order- }- res.json({ received: true });-});-\`\`\`--## NOWPayments--\`\`\`javascript-// Create payment-const res = await fetch('https://api.nowpayments.io/v1/payment', {- method: 'POST',- headers: {- 'x-api-key': process.env.NOWPAYMENTS_API_KEY,- 'Content-Type': 'application/json'- },- body: JSON.stringify({- price_amount: 49.99,- price_currency: 'usd',- pay_currency: 'btc',- order_id: '1234',- order_description: 'Product purchase'- })-});-const payment = await res.json();-// Send user to payment.pay_address to pay payment.pay_amount BTC-\`\`\`--## x402: HTTP-Native Crypto Payments--x402 is an emerging standard where any HTTP endpoint can require payment natively. The flow:--1. Client requests resource → server returns \`402 Payment Required\` with payment details-2. Client pays in USDC → includes \`X-Payment\` header in retry-3. Server verifies payment → returns resource--\`\`\`javascript-// Client-side x402 fetch-import { fetchWithPayment } from 'x402-fetch';--const res = await fetchWithPayment('https://api.example.com/premium-data', {- wallet: signer // ethers.js signer-});-const data = await res.json();-\`\`\`--\`\`\`javascript-// Server-side x402 middleware (Express)-import { paymentMiddleware } from 'x402-express';--app.use('/premium', paymentMiddleware({- amount: 0.01, // $0.01 USDC- token: 'USDC',- chain: 'base',- payTo: process.env.WALLET_ADDRESS-}));-\`\`\`--## Best Practices--- Always verify payments server-side via webhook, never trust client-reported status-- Use idempotency keys to prevent double-fulfillment-- Store transaction hashes for audit trails-- Monitor for underpayments — crypto amounts can vary with gas fees-- For fiat merchants, use auto-conversion to avoid crypto volatility exposure`- },- {- slug: 'blockchain-data-api-comparison',- title: 'Top Blockchain Data APIs Compared: Alchemy vs Infura vs QuickNode (2026)',- meta: 'Side-by-side comparison of Alchemy, Infura, QuickNode, Moralis, and Ankr — pricing, features, supported chains, rate limits, and best use cases.',- keywords: 'blockchain API comparison, Alchemy vs Infura, QuickNode vs Alchemy, best blockchain API, Web3 infrastructure comparison',- content: `# Top Blockchain Data APIs Compared: Alchemy vs Infura vs QuickNode (2026)--Choosing the right blockchain infrastructure provider affects your app's reliability, latency, and cost. Here's a detailed comparison of the major players.--## Feature Comparison--| Feature | Alchemy | Infura | QuickNode | Moralis | Ankr |-|---|---|---|---|---|---|-| Free tier | 300M CU/mo | 100K req/day | 10M credits/mo | 40K CU/day | 30M req/mo |-| Enhanced APIs | Yes (NFT, Token, etc.) | Limited | Yes (add-ons) | Yes (best) | No |-| WebSocket | Yes | Yes | Yes | No | Yes |-| Archive data | Yes (paid) | Yes (paid) | Yes (paid) | Yes | Yes |-| Chains | 20+ | 10+ | 30+ | 30+ | 40+ |-| Webhooks | Yes (Notify) | No | No | Yes (Streams) | No |-| Serverless functions | No | No | Yes (Functions) | No | No |-| Data pipelines | No | No | Yes (Streams) | Yes (Streams) | No |-| SLA uptime | 99.9% | 99.9% | 99.9% | 99.9% | 99.5% |--## Pricing (paid tiers starting from)--| Provider | Starter | Growth | Scale |-|---|---|---|---|-| Alchemy | Free | $49/mo | $199/mo |-| Infura | Free | $50/mo | $225/mo |-| QuickNode | Free | $9/mo | $49/mo |-| Moralis | Free | $49/mo | $249/mo |-| Ankr | Free | $189/mo | Custom |--## Latency Comparison (Ethereum Mainnet, global average)--| Provider | p50 | p95 | p99 |-|---|---|---|---|-| Alchemy | 45ms | 120ms | 280ms |-| QuickNode | 38ms | 95ms | 210ms |-| Infura | 52ms | 145ms | 320ms |-| Ankr | 68ms | 190ms | 450ms |--*Source: independent testing, 2025 Q4*--## Best For Each Use Case--### DeFi application with NFT features-**→ Alchemy** — best enhanced APIs for NFTs, tokens, and transfers. Webhooks for real-time events.--### High-frequency trading bot-**→ QuickNode** — lowest latency, dedicated endpoints, global nodes.--### Wallet or portfolio app-**→ Moralis** — highest-level APIs, wallet net worth, token balances with USD values in one call.--### Multi-chain application (30+ chains)-**→ QuickNode or Ankr** — broadest chain coverage.--### IPFS + Ethereum combination-**→ Infura** — built-in IPFS gateway alongside Ethereum RPC.--### Budget-conscious project-**→ Ankr** — generous free tier, pay-as-you-go pricing.--## Code Portability--All providers implement the standard Ethereum JSON-RPC spec, so switching is straightforward — just change the RPC URL:--\`\`\`javascript-// Easy to swap providers-const PROVIDERS = {- alchemy: \`https://eth-mainnet.g.alchemy.com/v2/\${ALCHEMY_KEY}\`,- infura: \`https://mainnet.infura.io/v3/\${INFURA_ID}\`,- quicknode: process.env.QUICKNODE_URL,- ankr: 'https://rpc.ankr.com/eth'-};--const provider = new ethers.JsonRpcProvider(PROVIDERS.alchemy);-\`\`\`--## Recommendation--For most production applications: **Alchemy** for Ethereum/EVM dApps with rich data needs, **QuickNode** for performance-critical trading infrastructure, **Moralis** for full-stack Web3 apps that need high-level portfolio and DeFi APIs.--Use multiple providers in parallel for critical applications — fan out requests and use whichever responds first.`- },- {- slug: 'crypto-portfolio-api-guide',- title: 'Building a Crypto Portfolio Tracker with APIs (2026)',- meta: 'Step-by-step guide to building a crypto portfolio tracker using CoinGecko, Alchemy, and Moralis APIs. Fetch balances, prices, and P&L in real time.',- keywords: 'crypto portfolio API, portfolio tracker API, crypto balance API, DeFi portfolio API, Web3 portfolio',- content: `# Building a Crypto Portfolio Tracker with APIs (2026)--A complete portfolio tracker needs three data layers: on-chain balances (what you hold), price data (what it's worth), and transaction history (how you got it). Here's how to combine them.--## Architecture--\`\`\`-Wallet Addresses- ↓-Moralis / Alchemy → Token balances + USD values- ↓-CoinGecko / CMC → Historical prices for P&L- ↓-Etherscan / Alchemy → Transaction history-\`\`\`--## Step 1: Fetch All Token Balances with USD Values--\`\`\`javascript-import Moralis from 'moralis';--await Moralis.start({ apiKey: process.env.MORALIS_API_KEY });--async function getPortfolio(address, chain = '0x1') {- const [native, tokens] = await Promise.all([- Moralis.EvmApi.balance.getNativeBalance({ address, chain }),- Moralis.EvmApi.wallets.getWalletTokenBalancesPrice({ address, chain })- ]);-- const holdings = [- {- symbol: 'ETH',- balance: parseFloat(native.result.ether),- usdValue: parseFloat(native.result.ether) * await getEthPrice()- },- ...tokens.result- .filter(t => !t.possibleSpam && parseFloat(t.balanceFormatted) > 0)- .map(t => ({- symbol: t.symbol,- name: t.name,- balance: parseFloat(t.balanceFormatted),- usdValue: t.usdValue || 0,- priceChange24h: t.usd24hrPercentChange || 0- }))- ];-- return holdings;-}-\`\`\`--## Step 2: Multi-Chain Portfolio--\`\`\`javascript-const CHAINS = {- ethereum: '0x1',- polygon: '0x89',- arbitrum: '0xa4b1',- base: '0x2105',- bsc: '0x38'-};--async function getMultiChainPortfolio(address) {- const results = await Promise.all(- Object.entries(CHAINS).map(async ([name, chainId]) => {- const holdings = await getPortfolio(address, chainId);- return holdings.map(h => ({ ...h, chain: name }));- })- );-- return results.flat().sort((a, b) => b.usdValue - a.usdValue);-}-\`\`\`--## Step 3: Historical P&L--\`\`\`javascript-async function getTokenPnl(symbol, purchaseDate, purchaseAmount, purchaseUsdValue) {- const coinId = await getCoinGeckoId(symbol);-- const res = await fetch(- \`https://api.coingecko.com/api/v3/coins/\${coinId}/history?date=\${formatDate(purchaseDate)}\`- );- const { market_data } = await res.json();- const purchasePriceUsd = market_data.current_price.usd;-- const currentPriceRes = await fetch(- \`https://api.coingecko.com/api/v3/simple/price?ids=\${coinId}&vs_currencies=usd\`- );- const { [coinId]: { usd: currentPrice } } = await currentPriceRes.json();-- const currentValue = purchaseAmount * currentPrice;- const pnl = currentValue - purchaseUsdValue;- const pnlPct = ((currentPrice - purchasePriceUsd) / purchasePriceUsd) * 100;-- return { pnl, pnlPct, currentValue, purchasePriceUsd, currentPrice };-}-\`\`\`--## Step 4: DeFi Positions--\`\`\`javascript-async function getDefiPositions(address) {- const positions = await Moralis.EvmApi.defi.getDefiPositionsSummary({- address,- chain: '0x1'- });-- return positions.result.map(p => ({- protocol: p.protocol_name,- type: p.position_type,- label: p.label,- usdValue: p.balance_usd- }));-}-\`\`\`--## Step 5: Real-Time Price Updates--\`\`\`javascript-async function streamPrices(symbols, onUpdate) {- const ids = await Promise.all(symbols.map(s => getCoinGeckoId(s)));-- setInterval(async () => {- const res = await fetch(- \`https://api.coingecko.com/api/v3/simple/price?ids=\${ids.join(',')}&vs_currencies=usd&include_24hr_change=true\`- );- const prices = await res.json();- onUpdate(prices);- }, 30000); // every 30s-}-\`\`\`--## Complete Portfolio Summary--\`\`\`javascript-async function getFullPortfolio(address) {- const [holdings, defi] = await Promise.all([- getMultiChainPortfolio(address),- getDefiPositions(address)- ]);-- const walletTotal = holdings.reduce((sum, h) => sum + h.usdValue, 0);- const defiTotal = defi.reduce((sum, p) => sum + p.usdValue, 0);-- return {- address,- totalUsd: walletTotal + defiTotal,- walletTotal,- defiTotal,- holdings,- defiPositions: defi- };-}-\`\`\``- },-];--for (const article of articles) {- const filePath = join(OUT, `${article.slug}.md`);- const content = `----title: "${article.title}"-meta_description: "${article.meta}"-keywords: "${article.keywords}"------${article.content}-`;- writeFileSync(filePath, content);- console.log(`✅ ${article.slug}.md`);-}--console.log(`\n✅ Wrote ${articles.length} articles to ${OUT}`);diff --git a/xactions/scripts/submit-to-glama.js b/xactions/scripts/submit-to-glama.jsdeleted file mode 100644index 3359aeb7d..000000000--- a/xactions/scripts/submit-to-glama.js+++ /dev/null@@ -1,154 +0,0 @@-#!/usr/bin/env node-// Copyright (c) 2024-2026 nich (@nichxbt). Business Source License 1.1.-// Submit all nirholas MCP repos to glama.ai by pushing glama.json to each repo-// Glama crawls GitHub for glama.json — this is the official submission method-// by nichxbt-//-// Usage:-// node scripts/submit-to-glama.js # submit all MCP repos-// node scripts/submit-to-glama.js --dry-run # preview only, no changes--const GITHUB_TOKEN = process.env.GITHUB_TOKEN;-const GITHUB_USERNAME = 'nirholas';-const DRY_RUN = process.argv.includes('--dry-run');-const API = 'https://api.github.com';--if (!GITHUB_TOKEN) {- console.error('❌ GITHUB_TOKEN env var required');- process.exit(1);-}--const HEADERS = {- Authorization: `Bearer ${GITHUB_TOKEN}`,- Accept: 'application/vnd.github+json',- 'X-GitHub-Api-Version': '2022-11-28',- 'Content-Type': 'application/json',- 'User-Agent': 'xactions-glama-submitter',-};--const GLAMA_JSON =- JSON.stringify(- { $schema: 'https://glama.ai/mcp/schemas/server.json', maintainers: [GITHUB_USERNAME] },- null,- 2- ) + '\n';--const GLAMA_JSON_B64 = Buffer.from(GLAMA_JSON).toString('base64');--const MCP_KEYWORDS = ['mcp', 'model-context-protocol', 'modelcontextprotocol', 'model context protocol'];--function isMcpRepo(repo) {- const text = [repo.name, repo.description || '', ...(repo.topics || [])].join(' ').toLowerCase();- return MCP_KEYWORDS.some((kw) => text.includes(kw));-}--async function gh(path, options = {}) {- const res = await fetch(`${API}${path}`, { headers: HEADERS, ...options });- if (res.status === 404) return null;- if (!res.ok) {- const body = await res.text();- throw new Error(`GitHub ${res.status}: ${body.slice(0, 200)}`);- }- return res.status === 204 ? null : res.json();-}--async function getAllRepos() {- const repos = [];- let page = 1;- while (true) {- const batch = await gh(`/users/${GITHUB_USERNAME}/repos?type=owner&per_page=100&page=${page}`);- if (!batch || batch.length === 0) break;- repos.push(...batch);- if (batch.length < 100) break;- page++;- }- return repos;-}--async function submitRepo(repo) {- const { name, default_branch, archived, private: isPrivate } = repo;-- if (archived) return { status: 'skipped', reason: 'archived' };- if (isPrivate) return { status: 'skipped', reason: 'private' };-- const existing = await gh(`/repos/${GITHUB_USERNAME}/${name}/contents/glama.json`);-- if (existing) {- const content = Buffer.from(existing.content, 'base64').toString('utf8');- if (content.includes(GITHUB_USERNAME)) {- return { status: 'skipped', reason: 'already has glama.json' };- }- }-- if (DRY_RUN) {- return { status: 'dry-run', reason: existing ? 'would update' : 'would create' };- }-- await gh(`/repos/${GITHUB_USERNAME}/${name}/contents/glama.json`, {- method: 'PUT',- body: JSON.stringify({- message: 'chore: add glama.json for MCP registry submission',- content: GLAMA_JSON_B64,- branch: default_branch,- ...(existing ? { sha: existing.sha } : {}),- }),- });-- return { status: existing ? 'updated' : 'created' };-}--async function main() {- console.log(`🔍 Fetching repos for ${GITHUB_USERNAME}...`);- const allRepos = await getAllRepos();- console.log(`📦 ${allRepos.length} total repos`);-- const mcpRepos = allRepos.filter(isMcpRepo);- console.log(`⚡ ${mcpRepos.length} MCP repos to process\n`);-- if (DRY_RUN) console.log('🧪 DRY RUN — no changes will be made\n');-- const results = { created: [], updated: [], skipped: [], failed: [] };-- for (let i = 0; i < mcpRepos.length; i++) {- const repo = mcpRepos[i];- process.stdout.write(` [${i + 1}/${mcpRepos.length}] ${repo.name} ... `);- try {- const result = await submitRepo(repo);- const label = result.reason ? `${result.status} (${result.reason})` : result.status;- process.stdout.write(`${label}\n`);-- if (result.status === 'created' || result.status === 'dry-run') results.created.push(repo.name);- else if (result.status === 'updated') results.updated.push(repo.name);- else results.skipped.push(`${repo.name} — ${result.reason}`);-- await new Promise((r) => setTimeout(r, 400)); // GitHub secondary rate limit- } catch (err) {- process.stdout.write(`❌ ${err.message}\n`);- results.failed.push(`${repo.name}: ${err.message}`);- }- }-- console.log('\n' + '─'.repeat(50));- console.log('📊 Summary');- console.log('─'.repeat(50));- console.log(`✅ Created: ${results.created.length}`);- console.log(`🔄 Updated: ${results.updated.length}`);- console.log(`⏭️ Skipped: ${results.skipped.length}`);- console.log(`❌ Failed: ${results.failed.length}`);-- if (results.failed.length > 0) {- console.log('\nFailed:');- results.failed.forEach((r) => console.log(` • ${r}`));- }-- if (results.created.length + results.updated.length > 0) {- console.log('\n🎉 glama.json committed to all MCP repos.');- console.log(' Glama crawls GitHub periodically — repos will appear at:');- console.log(' https://glama.ai/mcp/servers within ~24h');- }-}--main().catch((err) => {- console.error('❌ Fatal:', err.message);- process.exit(1);-});diff --git a/xactions/scripts/test-x402-payment.js b/xactions/scripts/test-x402-payment.jsdeleted file mode 100644index dace60572..000000000--- a/xactions/scripts/test-x402-payment.js+++ /dev/null@@ -1,359 +0,0 @@-#!/usr/bin/env node-// Copyright (c) 2024-2026 nich (@nichxbt). Business Source License 1.1.-/**- * x402 Real Payment Flow Test- *- * Exercises the complete x402 payment lifecycle against a running server:- * 1. Hits a protected endpoint without payment → expects 402- * 2. Parses payment requirements from the response- * 3. Signs a real EIP-3009 USDC transfer with a local wallet- * 4. Retries with the signed X-PAYMENT header- * 5. Reports success or failure with diagnostics- *- * Usage:- * node scripts/test-x402-payment.js [endpoint]- *- * Prerequisites:- * - Server running (npm run dev)- * - viem installed (npm install viem)- *- * Environment variables (optional):- * X402_PRIVATE_KEY — wallet private key for signing (generates ephemeral if unset)- * API_BASE_URL — server URL (default: http://localhost:3001)- *- * Note: Without funded testnet USDC, the facilitator will reject the payment- * at the verification step. The test still validates that the full protocol- * flow works correctly up to that point.- *- * @author nichxbt- */--import { config } from 'dotenv';-import { fileURLToPath } from 'url';-import { dirname, join } from 'path';-import { existsSync } from 'fs';-import crypto from 'crypto';--// Load environment variables-const __dirname = dirname(fileURLToPath(import.meta.url));-const envPath = join(__dirname, '..', '.env');-if (existsSync(envPath)) {- config({ path: envPath });-}--// Configuration-const API_URL = process.env.API_BASE_URL || 'http://localhost:3001';-const TEST_ENDPOINT = process.argv[2] || '/api/ai/scrape/profile';--// ═════════════════════════════════════════════════════════════════════��═════════-// Wallet Setup-// ═══════════════════════════════════════════════════════════════════════════════--async function setupWallet() {- const { createWalletClient, http } = await import('viem');- const { privateKeyToAccount, generatePrivateKey } = await import('viem/accounts');- const { baseSepolia } = await import('viem/chains');-- const pk = process.env.X402_PRIVATE_KEY || generatePrivateKey();- const account = privateKeyToAccount(pk);-- const wallet = createWalletClient({- account,- chain: baseSepolia,- transport: http(),- });-- return { wallet, account, privateKey: pk, ephemeral: !process.env.X402_PRIVATE_KEY };-}--// ═══════════════════════════════════════════════════════════════════════════════-// Payment Signing (EIP-3009 TransferWithAuthorization)-// ═══════════════════════════════════════════════════════════════════════════════--async function signPayment(wallet, account, requirements) {- const accept = requirements.accepts?.[0];- if (!accept) throw new Error('No accepted payment scheme in requirements');-- const usdcAddress = accept.asset || '0x036CbD53842c5426634e7929541eC2318f3dCF7e';- const networkId = accept.network || 'eip155:84532';- const chainId = parseInt(networkId.split(':')[1]);-- // Parse price — handle "$0.001" or raw number- let rawPrice = accept.maxAmountRequired || accept.price;- if (typeof rawPrice === 'string' && rawPrice.startsWith('$')) {- // Convert USD string to USDC atomic units (6 decimals)- rawPrice = Math.round(parseFloat(rawPrice.replace('$', '')) * 1e6).toString();- }-- const nonce = `0x${crypto.randomBytes(32).toString('hex')}`;- const validAfter = 0;- const validBefore = Math.floor(Date.now() / 1000) + 3600;-- const domain = {- name: 'USD Coin',- version: '2',- chainId,- verifyingContract: usdcAddress,- };-- const types = {- TransferWithAuthorization: [- { name: 'from', type: 'address' },- { name: 'to', type: 'address' },- { name: 'value', type: 'uint256' },- { name: 'validAfter', type: 'uint256' },- { name: 'validBefore', type: 'uint256' },- { name: 'nonce', type: 'bytes32' },- ],- };-- const message = {- from: account.address,- to: accept.payTo,- value: BigInt(rawPrice),- validAfter: BigInt(validAfter),- validBefore: BigInt(validBefore),- nonce,- };-- const signature = await wallet.signTypedData({- domain,- types,- primaryType: 'TransferWithAuthorization',- message,- });-- return {- x402Version: 2,- scheme: 'exact',- network: networkId,- payload: {- signature,- authorization: {- from: account.address,- to: accept.payTo,- value: rawPrice,- validAfter: validAfter.toString(),- validBefore: validBefore.toString(),- nonce,- },- },- };-}--// ════════════════════════════════════════════════════════════════════════��══════-// Main Test Flow-// ═══════════════════════════════════════════════════════════════════════════════--async function main() {- console.log('╔════════════════════════════════════════════════════════════════╗');- console.log('║ x402 Real Payment Flow Test ║');- console.log('╚════════════════════════════════════════════════════════════════╝\n');-- // Step 0: Set up wallet- console.log('STEP 0: Wallet Setup');- console.log('─'.repeat(60));- let walletInfo;- try {- walletInfo = await setupWallet();- console.log(` Address: ${walletInfo.account.address}`);- console.log(` Source: ${walletInfo.ephemeral ? 'ephemeral (generated)' : 'X402_PRIVATE_KEY env var'}`);- if (walletInfo.ephemeral) {- console.log(` ⚠️ Ephemeral wallet has no USDC — verification will fail (expected)`);- console.log(` Fund a wallet and set X402_PRIVATE_KEY for full e2e test`);- }- console.log('');- } catch (error) {- console.log(` ❌ Failed: ${error.message}`);- console.log(` Install viem: npm install viem\n`);- process.exit(1);- }-- // Step 1: Request without payment- console.log(`STEP 1: Initial Request (No Payment)`);- console.log('─'.repeat(60));- console.log(` Target: ${API_URL}${TEST_ENDPOINT}`);-- let paymentRequirements = null;- try {- const response = await fetch(`${API_URL}${TEST_ENDPOINT}`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ username: 'elonmusk' }),- });-- console.log(` Status: ${response.status} ${response.statusText}`);-- if (response.status === 402) {- console.log(' ✅ Received 402 Payment Required\n');-- // Parse payment requirements from header- const paymentHeader = response.headers.get('x-payment-requirements') ||- response.headers.get('payment-required');-- if (paymentHeader) {- try {- paymentRequirements = JSON.parse(Buffer.from(paymentHeader, 'base64').toString('utf-8'));- console.log(' 📋 Payment requirements decoded from header');- } catch {- // Try plain JSON- try {- paymentRequirements = JSON.parse(paymentHeader);- } catch {- console.log(' ⚠️ Could not decode payment header');- }- }- }-- // Also check the response body for requirements- if (!paymentRequirements) {- const body = await response.json();- if (body.x402?.accepts) {- paymentRequirements = body.x402;- console.log(' 📋 Payment requirements extracted from body');- }- }- } else if (response.status === 200) {- console.log(' ⚠️ Got 200 — x402 payments may not be active');- const body = await response.json();- console.log(' Response:', JSON.stringify(body).slice(0, 300));- process.exit(0);- } else {- console.log(` ❌ Unexpected status: ${response.status}`);- const body = await response.text();- console.log(` Body: ${body.slice(0, 500)}\n`);- process.exit(1);- }- } catch (error) {- if (error.cause?.code === 'ECONNREFUSED') {- console.log(' ❌ Connection refused — is the server running?');- console.log(` Start with: npm run dev\n`);- } else {- console.log(` ❌ Request failed: ${error.message}\n`);- }- process.exit(1);- }-- // Step 2: Parse requirements- console.log('STEP 2: Payment Requirements');- console.log('─'.repeat(60));-- if (!paymentRequirements) {- console.log(' ❌ No payment requirements received\n');- process.exit(1);- }-- const accepts = paymentRequirements.accepts;- if (!accepts || accepts.length === 0) {- console.log(' ❌ No accepted payment options\n');- process.exit(1);- }-- console.log(` x402 Version: ${paymentRequirements.x402Version || 'unknown'}`);- console.log(` Options: ${accepts.length} network(s) accepted`);- for (const opt of accepts) {- const extra = opt.extra || {};- const testnetTag = extra.testnet ? ' [testnet]' : '';- const recTag = extra.recommended ? ' ★' : '';- console.log(` - ${extra.networkName || opt.network}: ${opt.maxAmountRequired || opt.price}${testnetTag}${recTag}`);- }- console.log('');-- // Step 3: Sign payment- console.log('STEP 3: Sign Payment');- console.log('─'.repeat(60));-- let payment;- try {- payment = await signPayment(walletInfo.wallet, walletInfo.account, paymentRequirements);- console.log(` ✅ Payment signed`);- console.log(` Scheme: ${payment.scheme}`);- console.log(` Network: ${payment.network}`);- console.log(` From: ${payment.payload.authorization.from}`);- console.log(` To: ${payment.payload.authorization.to}`);- console.log(` Value: ${payment.payload.authorization.value} (USDC atomic units)`);- console.log('');- } catch (error) {- console.log(` ❌ Signing failed: ${error.message}\n`);- process.exit(1);- }-- // Step 4: Retry with payment- console.log('STEP 4: Retry with Signed Payment');- console.log('─'.repeat(60));-- try {- const encodedPayment = Buffer.from(JSON.stringify(payment)).toString('base64');-- const response = await fetch(`${API_URL}${TEST_ENDPOINT}`, {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- 'X-PAYMENT': encodedPayment,- },- body: JSON.stringify({ username: 'elonmusk' }),- });-- console.log(` Status: ${response.status} ${response.statusText}`);-- // Check for settlement header- const settlementHeader = response.headers.get('x-payment-response') ||- response.headers.get('payment-response');- if (settlementHeader) {- console.log(' ✅ PAYMENT-RESPONSE header received');- try {- const settlement = JSON.parse(Buffer.from(settlementHeader, 'base64').toString('utf-8'));- if (settlement.transaction) {- console.log(` Transaction: ${settlement.transaction}`);- }- } catch {- // Settlement parsing is optional- }- }-- const body = await response.json();-- if (response.status === 200) {- console.log(' ✅ Payment accepted — request succeeded!\n');- console.log('RESULT');- console.log('─'.repeat(60));- console.log(JSON.stringify(body, null, 2).slice(0, 1000));- } else if (response.status === 402) {- console.log(' ⚠️ Payment rejected by facilitator');- console.log(` Reason: ${body.error || body.message || JSON.stringify(body)}`);- if (walletInfo.ephemeral) {- console.log('\n This is expected with an unfunded ephemeral wallet.');- console.log(' The protocol flow is working correctly.');- }- } else {- console.log(` ❌ Unexpected: ${response.status}`);- console.log(` Body: ${JSON.stringify(body).slice(0, 500)}`);- }- console.log('');- } catch (error) {- console.log(` ❌ Request failed: ${error.message}\n`);- }-- // Summary- console.log('═'.repeat(60));- console.log('SUMMARY');- console.log('═'.repeat(60));- console.log(`- Protocol flow:- ✅ Server returns 402 with payment requirements- ✅ Requirements include network options + pricing- ✅ Client signs EIP-712 typed data (EIP-3009)- ✅ Client retries with X-PAYMENT header-- To complete a full end-to-end payment:- 1. Get test USDC from https://faucet.circle.com (Base Sepolia)- 2. Fund your wallet: ${walletInfo.account.address}- 3. Set X402_PRIVATE_KEY in .env- 4. Re-run this script-`);-}--main().catch(err => {- console.error('Fatal error:', err);- process.exit(1);-});diff --git a/xactions/scripts/verify-x402.js b/xactions/scripts/verify-x402.jsdeleted file mode 100644index 0f417ceb0..000000000--- a/xactions/scripts/verify-x402.js+++ /dev/null@@ -1,289 +0,0 @@-#!/usr/bin/env node-// Copyright (c) 2024-2026 nich (@nichxbt). Business Source License 1.1.-/**- * x402 Configuration Verification Script- *- * Validates x402 setup and tests connectivity to the facilitator.- * Run this before deploying to ensure everything is configured correctly.- *- * Usage:- * node scripts/verify-x402.js- * npm run verify:x402- *- * @author nichxbt- */--import { config } from 'dotenv';-import { fileURLToPath } from 'url';-import { dirname, join } from 'path';-import { existsSync } from 'fs';--// Load environment variables-const __dirname = dirname(fileURLToPath(import.meta.url));-const envPath = join(__dirname, '..', '.env');--if (existsSync(envPath)) {- config({ path: envPath });-} else {- console.log('⚠️ No .env file found, using environment variables\n');-}--// Import configuration from the actual config module to ensure consistency-import {- PAY_TO_ADDRESS,- FACILITATOR_URL,- NETWORK,- AI_OPERATION_PRICES,- validateConfig,- isX402Configured-} from '../api/config/x402-config.js';--// Network names for display-const NETWORK_NAMES = {- 'eip155:84532': 'Base Sepolia (testnet)',- 'eip155:8453': 'Base (mainnet)',- 'eip155:1': 'Ethereum Mainnet',- 'eip155:11155111': 'Ethereum Sepolia (testnet)',-};--console.log('╔════════════════════════════════════════════════════════════════╗');-console.log('║ XActions x402 Configuration Verification ║');-console.log('╚════════════════════════════════════════════════════════════════╝\n');--let hasErrors = false;-let hasWarnings = false;--// ═══════════════════════════════════════════════════════════════════════════════-// Check Payment Address-// ═══════════════════════════════════════════════════════════════════════════════--console.log('📍 Payment Address Configuration');-console.log('─'.repeat(60));--if (!PAY_TO_ADDRESS) {- console.log('❌ X402_PAY_TO_ADDRESS is not set');- console.log(' Payments cannot be received without this address.');- console.log(' Set it in your .env file or environment variables.\n');- hasErrors = true;-} else if (!PAY_TO_ADDRESS.match(/^0x[a-fA-F0-9]{40}$/)) {- console.log('❌ X402_PAY_TO_ADDRESS is invalid');- console.log(` Current value: ${PAY_TO_ADDRESS}`);- console.log(' Must be a valid Ethereum address (0x + 40 hex chars)\n');- hasErrors = true;-} else {- console.log(`✅ Payment address: ${PAY_TO_ADDRESS}`);- console.log(` First 6 chars: ${PAY_TO_ADDRESS.slice(0, 6)}...${PAY_TO_ADDRESS.slice(-4)}\n`);-}--// ═══════════════════════════════════════════════════════════════════════════════-// Check Network Configuration-// ═══════════════════════════════════════════════════════════════════════════════--console.log('🌐 Network Configuration');-console.log('─'.repeat(60));--const networkName = NETWORK_NAMES[NETWORK] || 'Unknown Network';-console.log(` Network: ${NETWORK}`);-console.log(` Name: ${networkName}`);--if (NETWORK === 'eip155:84532') {- console.log('⚠️ Running on TESTNET - payments use test USDC');- console.log(' Switch to eip155:8453 for mainnet/production\n');- hasWarnings = true;-} else if (NETWORK === 'eip155:8453') {- console.log('✅ Running on MAINNET - real USDC payments\n');-} else {- console.log('⚠️ Non-standard network - ensure facilitator supports it\n');- hasWarnings = true;-}--// ═══════════════════════════════════════════════════════════════════════════════-// Check Facilitator Connection-// ═══════════════════════════════════════════════════════════════════════════════--console.log('🔗 Facilitator Connection');-console.log('─'.repeat(60));-console.log(` URL: ${FACILITATOR_URL}`);--try {- console.log(' Testing connection...');-- const controller = new AbortController();- const timeout = setTimeout(() => controller.abort(), 10000);-- const response = await fetch(FACILITATOR_URL, {- method: 'GET',- headers: {- 'Accept': 'application/json',- 'User-Agent': 'XActions-Verify/1.0',- },- signal: controller.signal,- });-- clearTimeout(timeout);-- if (response.ok) {- console.log(`✅ Facilitator is reachable (HTTP ${response.status})`);-- // Try to get version info if available- try {- const data = await response.json();- if (data.version) {- console.log(` Facilitator version: ${data.version}`);- }- if (data.supportedNetworks) {- console.log(` Supported networks: ${data.supportedNetworks.join(', ')}`);- }- } catch {- // Response might not be JSON, that's okay- }- console.log('');- } else {- console.log(`⚠️ Facilitator returned HTTP ${response.status}`);- console.log(' This may indicate configuration issues\n');- hasWarnings = true;- }-} catch (error) {- if (error.name === 'AbortError') {- console.log('❌ Connection timed out after 10 seconds');- } else {- console.log(`❌ Failed to reach facilitator: ${error.message}`);- }- console.log(' Check your network connection and facilitator URL\n');- hasErrors = true;-}--// ═══════════════════════════════════════════════════════════════════════════════-// Pricing Configuration-// ═══════════════════════════════════════════════════════════════════════════════--console.log('💰 Pricing Configuration');-console.log('─'.repeat(60));--const categories = {- 'Scraping': Object.entries(AI_OPERATION_PRICES).filter(([k]) => k.startsWith('scrape:')),- 'Actions': Object.entries(AI_OPERATION_PRICES).filter(([k]) => k.startsWith('action:')),- 'Monitoring': Object.entries(AI_OPERATION_PRICES).filter(([k]) => k.startsWith('monitor:') || k.startsWith('alert:')),- 'Utility': Object.entries(AI_OPERATION_PRICES).filter(([k]) => k.startsWith('download:') || k.startsWith('export:') || k.startsWith('unroll:')),-};--for (const [category, operations] of Object.entries(categories)) {- console.log(`\n ${category}:`);- for (const [op, price] of operations) {- const opName = op.split(':')[1].padEnd(25);- console.log(` ${opName} ${price}`);- }-}--// Calculate some stats-const prices = Object.values(AI_OPERATION_PRICES).map(p => parseFloat(p.replace('$', '')));-const minPrice = Math.min(...prices);-const maxPrice = Math.max(...prices);-const avgPrice = (prices.reduce((a, b) => a + b, 0) / prices.length).toFixed(4);--console.log(`\n Summary:`);-console.log(` Total operations: ${prices.length}`);-console.log(` Price range: $${minPrice} - $${maxPrice}`);-console.log(` Average price: $${avgPrice}\n`);--// ═══════════════════════════════════════════════════════════════════════════════-// Environment Check-// ═══════════════════════════════════════════════════════════════════════════════--console.log('🔧 Environment Check');-console.log('─'.repeat(60));--const nodeVersion = process.version;-console.log(` Node.js: ${nodeVersion}`);--if (parseInt(nodeVersion.slice(1)) < 18) {- console.log('⚠️ Node.js 18+ recommended for native fetch support\n');- hasWarnings = true;-} else {- console.log('✅ Node.js version is compatible\n');-}--// Check for required packages-console.log(' Checking dependencies...');--const requiredPackages = ['@x402/core', '@x402/evm', '@x402/express'];-const optionalPackages = ['viem', 'ethers'];--for (const pkg of requiredPackages) {- try {- await import(pkg);- console.log(` ✅ ${pkg} - installed`);- } catch {- console.log(` ❌ ${pkg} - NOT INSTALLED`);- console.log(` Run: npm install ${pkg}`);- hasErrors = true;- }-}--for (const pkg of optionalPackages) {- try {- await import(pkg);- console.log(` ✅ ${pkg} - installed (optional)`);- } catch {- console.log(` ℹ️ ${pkg} - not installed (optional)`);- }-}--console.log('');--// ═══════════════════════════════════════════════════════════════════════════════-// Security Check-// ═══════════════════════════════════════════════════════════════════════════════--console.log('🔒 Security Check');-console.log('─'.repeat(60));--if (process.env.X402_SKIP_VERIFICATION === 'true') {- console.log('🚨 X402_SKIP_VERIFICATION is enabled!');- console.log(' API endpoints will NOT require payment.');- console.log(' This should ONLY be used in development.\n');- hasWarnings = true;-} else {- console.log('✅ Payment verification is enabled\n');-}--if (process.env.X402_PRIVATE_KEY) {- console.log('⚠️ X402_PRIVATE_KEY is set in environment');- console.log(' Ensure this is a dedicated payment wallet, not your main wallet');- console.log(' Never commit private keys to version control\n');- hasWarnings = true;-}--if (process.env.NODE_ENV === 'production') {- console.log('✅ Running in production mode');-} else {- console.log(`ℹ️ Running in ${process.env.NODE_ENV || 'development'} mode`);-}--console.log('');--// ═══════════════════════════════════════════════════════════════════════════════-// Summary-// ═══════════════════════════════════════════════════════════════════════════════--console.log('═'.repeat(60));-console.log('VERIFICATION SUMMARY');-console.log('═'.repeat(60));--if (hasErrors) {- console.log('\n❌ FAILED - Critical issues found that must be resolved\n');- console.log('Please fix the errors above before deploying.');- process.exit(1);-} else if (hasWarnings) {- console.log('\n⚠️ PASSED WITH WARNINGS\n');- console.log('Configuration is functional but review warnings above.');- console.log('For production, ensure:');- console.log(' - Network is set to mainnet (eip155:8453)');- console.log(' - X402_SKIP_VERIFICATION is NOT set');- console.log(' - Payment address is correct');- process.exit(0);-} else {- console.log('\n✅ ALL CHECKS PASSED\n');- console.log('x402 configuration is ready for deployment.');- process.exit(0);-}