Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(pump-claims): post first-time creator fee claims to their own Telegram channel
nirholasacf4d4d32afa
diff --git a/.env.example b/.env.exampleindex e3698ade7..5d23d7836 100644--- a/.env.example+++ b/.env.example@@ -1477,6 +1477,15 @@ TELEGRAM_CHANGELOG_CHAT_ID=-1003927666373# commit firehose out of the holder-facing changelog channel.TELEGRAM_COMMITS_CHAT_ID=+# Telegram pump.fun first-claims channel (@pumpfunclaims).+# /api/cron/pump-claims-push posts each first-time creator fee claim here, one+# message per claim. Use the channel @handle or the -100… numeric id; the bot+# above must be an admin of the channel. Deliberately has NO fallback to the+# changelog channel: this is a high-volume third-party coin feed and holders+# are a different audience. Leave blank to disable the lane entirely.+# The scan behind it also needs PUMPFUN_BOT_URL set to return anything.+TELEGRAM_PUMP_CLAIMS_CHAT_ID=+# Telegram Oracle signals channel: the live feed of three.ws/oracle. The# oracle-score cron (every 2 min) posts each coin that first crosses the tier# floor (ORACLE_ALERT_MIN_TIER) OR the raw score floor (ORACLE_FEED_MIN_SCORE,diff --git a/CLAUDE.md b/CLAUDE.mdindex 4443cdf02..9d433e70f 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -305,7 +305,7 @@ The whole build + submit + purge in one command: `npm run deploy:gcp:full`.- Frontend: vanilla JS modules + Vite (`npm run dev`, port 3000).- 3D: Three.js with glTF/GLB.- Backend touchpoints: serverless-style handlers in `api/`, workers in `workers/`.-- **Production runs on Google Cloud Run, NOT Vercel** (migrated 2026-07-07 after Vercel disabled the deployment). One container ([server/index.mjs](server/index.mjs)) serves the static frontend, the vercel.json route table, and all `api/**` handlers; the crons (107 as of 2026-08-14, see vercel.json) run on Cloud Scheduler. `vercel.json` is a LIVE config file: `server/index.mjs` reads its `routes` array on boot (split at the `{handle:"filesystem"}` marker into pre- and post-filesystem phases), and `scripts/create-gcp-scheduler.mjs` reads its `crons` array to sync Cloud Scheduler jobs. The server itself never reads `crons`. Never delete `vercel.json` as a leftover. GCP builds/deploys must pin the `three-ws-build@` (build) and `three-ws@` (runtime) service accounts; the project's default compute SA was deleted. Deploys: see the "Deploy runbook" section above.+- **Production runs on Google Cloud Run, NOT Vercel** (migrated 2026-07-07 after Vercel disabled the deployment). One container ([server/index.mjs](server/index.mjs)) serves the static frontend, the vercel.json route table, and all `api/**` handlers; the crons (108 as of 2026-08-14, see vercel.json) run on Cloud Scheduler. `vercel.json` is a LIVE config file: `server/index.mjs` reads its `routes` array on boot (split at the `{handle:"filesystem"}` marker into pre- and post-filesystem phases), and `scripts/create-gcp-scheduler.mjs` reads its `crons` array to sync Cloud Scheduler jobs. The server itself never reads `crons`. Never delete `vercel.json` as a leftover. GCP builds/deploys must pin the `three-ws-build@` (build) and `three-ws@` (runtime) service accounts; the project's default compute SA was deleted. Deploys: see the "Deploy runbook" section above.- **Env-var trap:** `vercel env pull` returns EMPTY for secret-type vars. Never trust a Vercel env export as complete. Production env lives on the Cloud Run service (`gcloud run services describe/update three-ws-api --region us-central1`).- Solana/agent SDKs in `sdk/`, `solana-agent-sdk/`, `agent-payments-sdk/`.- Real APIs in use: Pump.fun feed, Solana RPC, OpenAI/Anthropic via worker proxies. Never mock these.diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 87b73e84c..aa4b2a48a 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -157,6 +157,7 @@ bottom.| Launch Studio (coin-launch use cases) | [api/_lib/launch/](api/_lib/launch) `→ /launch-studio`, [api/pump/launch-studio.js](api/pump/launch-studio.js), [public/launch-studio/launch-studio.js](public/launch-studio/launch-studio.js) | In-repo | Engine + catalog of 50 declarative launch recipes — reward coins for trending GitHub repos/creators ([github-trending.js](api/_lib/github-trending.js)) and coins riding live narratives ([launcher-trends.js](api/_lib/launcher-trends.js)). Live preview → `/launch` handoff. Docs: [docs/launch-usecases.md](docs/launch-usecases.md), [api/_lib/launch/README.md](api/_lib/launch/README.md) || Native launchpad (three.ws's own bonding curve) | Curve economics [api/_lib/native-launch/config.js](api/_lib/native-launch/config.js), curve wrapper [api/_lib/native-launch/dbc.js](api/_lib/native-launch/dbc.js), dispatcher [api/native-launch/[action].js](api/native-launch/%5Baction%5D.js) `→ /api/native-launch/{config,quote,pool,launch-prep,launch-confirm,launches}`, lane toggle in [public/studio/launch-panel.js](public/studio/launch-panel.js) | In-repo (devnet-verified; mainnet config not yet deployed) | The second launch lane beside pump.fun: a coin launch on a bonding curve three.ws configures and owns, so the platform earns a share of every trade instead of only creator fees. Runs on Meteora's audited Dynamic Bonding Curve program with three.ws as the on-chain partner — 1B supply, SOL-quoted, immutable metadata, 1% trading fee split 50/50 creator/platform, graduating at ~85 SOL raised into a DAMM v2 pool with **100% of LP permanently locked** (un-ruggable, both sides keep earning). Same custody model as the pump lane (server builds an unsigned tx, the launcher's wallet + mint keypair sign client-side, confirm verifies on-chain that the curve program actually ran before recording). The lane hides itself entirely until a partner config is pinned for that network (`NATIVE_LAUNCH_CONFIG_KEY[_DEVNET]`), so launches fall back to pump.fun rather than half-working. Not to be confused with `/api/launchpad/*` (Launchpad Studio, the page builder). Storage: [native_launches](api/_lib/migrations/20260726100000_native_launchpad.sql). Setup: [scripts/native-launchpad-create-config.mjs](scripts/native-launchpad-create-config.mjs). E2E: [scripts/native-launchpad-e2e-devnet.mjs](scripts/native-launchpad-e2e-devnet.mjs). Docs: [docs/native-launchpad.md](docs/native-launchpad.md). Tests: [tests/native-launch-curve.test.js](tests/native-launch-curve.test.js), [tests/native-launch-endpoint.test.js](tests/native-launch-endpoint.test.js) || Memetic Launcher (per-user autonomous coin launcher) | [pages/launcher.html](pages/launcher.html) `→ /launcher` + [src/user-launcher.js](src/user-launcher.js), API [api/launcher/me.js](api/launcher/me.js), engine [api/_lib/launcher-engine.js](api/_lib/launcher-engine.js) (cron [api/cron/launcher-tick.js](api/cron/launcher-tick.js)), trends [api/_lib/launcher-trends.js](api/_lib/launcher-trends.js) | In-repo | Every user designs their own autonomous pump.fun launcher: mode (trend/meme/hybrid/random), trend sources, cadence, network. Preview (default) records picks without moving SOL; **Live** mints for real, SELF-FUNDED - each launch paid by the user's own agent wallet (base ~0.022 SOL + dev buy), never master SOL, with typed go-live confirm, dev-buy + daily-SOL-cap clamps, unfunded-wallet skips (breaker-immune), and an agent-wallet funding panel with live balances. Docs: [docs/memetic-launcher.md](docs/memetic-launcher.md). Tests: [tests/user-launcher.test.js](tests/user-launcher.test.js), [tests/launcher-engine.test.js](tests/launcher-engine.test.js) |+| pump.fun first-claims Telegram channel (@pumpfunclaims) | Delivery lane [api/_lib/pump-claims-push.js](api/_lib/pump-claims-push.js), cron [api/cron/pump-claims-push.js](api/cron/pump-claims-push.js) (every 5 min), shared scanner [api/_lib/pump-claims.js](api/_lib/pump-claims.js) (also backs `GET /api/pump/first-claims` and the `pumpfun_first_claims` MCP tool) | In-repo · lane wired, channel dark pending `PUMPFUN_BOT_URL` + `TELEGRAM_PUMP_CLAIMS_CHAT_ID` | A live feed of first-time pump.fun creator fee claims, one message per claim: the first time a creator ever pulls accrued rewards out of the fee vault is an irreversible on-chain signal that they are engaged with their coin. Mirrors the commit-feed lane's safety properties (DB lock, seed-without-posting on first run, per-message state writes, oldest-first drain, 3h replay cutoff) but dedupes by transaction signature rather than timestamp, because claims routinely share a second and a timestamp cursor drops the second one. No fallback to the holder changelog channel on purpose. The RPC fallback inside the scanner cannot serve this feed (the pump program clears a 200-signature page in under one second, so a scan covers no useful window); an indexer is required. Docs: [docs/pump-claims-channel.md](docs/pump-claims-channel.md). Tests: [tests/pump-claims-push.test.js](tests/pump-claims-push.test.js) || On-chain agent invocation | [contracts/agent-invocation/](contracts/agent-invocation) | In-repo | Anchor program: verifiable agent-to-agent skill invocation events. SDK: [agent-protocol-sdk/](agent-protocol-sdk) || Cross-chain SDKs | [sdk/](sdk), [solana-agent-sdk/](solana-agent-sdk), [agent-payments-sdk/](agent-payments-sdk), [agent-protocol-sdk/](agent-protocol-sdk) | Published | Cross-chain agent SDKs || MCP integration | [mcp-server/](mcp-server), [mcp-bridge/](mcp-bridge), [packages/*-mcp/](packages) | 37 npm servers + 7 hosted remote (44 total, incl. the free `/api/mcp-studio` 3D Studio), all in the [MCP registry](https://registry.modelcontextprotocol.io/?q=io.github.nirholas). Canonical metadata: [prompts/store-submissions/_generated/mcp-listing-source.json](prompts/store-submissions/_generated/mcp-listing-source.json) | Model Context Protocol surface, full server list in [docs/mcp.md](docs/mcp.md). Searchable index of every tool: [pages/mcp-tools.html](pages/mcp-tools.html) `→ /mcp-tools`, rendered from the generated [public/mcp-catalog.json](public/mcp-catalog.json) ([scripts/build-mcp-catalog.mjs](scripts/build-mcp-catalog.mjs), `npm run build:mcp-catalog`, staleness gated by `npm run audit:mcp-catalog`). Tool safety annotations are verified against each handler by [scripts/audit-mcp-safety.mjs](scripts/audit-mcp-safety.mjs) (`npm run audit:mcp-safety`, rules in [scripts/lib/mcp-safety-check.mjs](scripts/lib/mcp-safety-check.mjs), guarded-file list shared with the golden snapshot via [scripts/lib/mcp-tool-sources.mjs](scripts/lib/mcp-tool-sources.mjs)); docs [docs/mcp-safety.md](docs/mcp-safety.md) `→ /docs/mcp-safety`. Trust policy: [api/mcp-policy.js](api/mcp-policy.js) `-> GET /api/mcp-policy` turns those verified labels into a ready-to-paste client allowlist (profiles strict/balanced/open x formats claude/vscode/json), surfaced by the builder panel on `/mcp-tools`. Tests: [tests/mcp-safety-audit.test.js](tests/mcp-safety-audit.test.js), [tests/mcp-catalog.test.js](tests/mcp-catalog.test.js), [tests/api/mcp-policy.test.js](tests/api/mcp-policy.test.js) |diff --git a/api/_lib/pump-claims-push.js b/api/_lib/pump-claims-push.jsnew file mode 100644index 000000000..34d39b37c--- /dev/null+++ b/api/_lib/pump-claims-push.js@@ -0,0 +1,256 @@+// @ts-check+// Automatic first-claim delivery to Telegram: every time a pump.fun creator+// pulls their accrued creator fees out of the fee vault for the FIRST time,+// that claim gets its own message. Driven by /api/cron/pump-claims-push on+// Cloud Scheduler.+//+// A first claim is an on-chain, irreversible signal that a creator is live and+// engaged with their coin, which is why it is worth its own channel rather+// than a line in the holder changelog. The scan itself lives in+// ./pump-claims.js and is shared with GET /api/pump/first-claims.+//+// Destination: TELEGRAM_PUMP_CLAIMS_CHAT_ID. There is deliberately NO fallback+// to the holder channel (TELEGRAM_CHANGELOG_CHAT_ID): this feed is high-volume+// third-party coin activity and holder-facing release notes are not the same+// audience. An unset chat id reports { skipped: 'not_configured' }.+//+// State (app_settings key `pump_claims_push_telegram`):+// { lastTs: number|null, seen: string[] }+// `lastTs` is the block time of the newest claim posted; `seen` is a bounded+// ring of recently posted transaction signatures. Both are needed because the+// two failure modes are different:+//+// 1. Claims arriving inside the same second as the last posted one share+// `lastTs`, so a timestamp cursor alone would drop them. `seen` catches+// those exactly, by signature.+// 2. `seen` is bounded, so it cannot answer for a claim older than the ring.+// `lastTs` bounds the query window so the ring never has to.+//+// On first run (no state) the lane seeds from the current scan WITHOUT posting,+// so enabling this feature never dumps a backlog of history into the channel.++import { sql } from './db.js';+import { scanFirstClaims } from './pump-claims.js';++const TELEGRAM_LIMIT = 10; // per run; Bot API allows ~20 msg/min per chat+const TELEGRAM_PACE_MS = 3500;+// How far back each tick scans. The cron runs every 5 minutes, so a 30-minute+// window tolerates five consecutive missed ticks without losing a claim.+const SCAN_MINUTES = 30;+// Nothing older than this is ever posted, however far behind the state is. A+// catch-up drains a backlog; it must never replay history into the channel.+const CUTOFF_MINUTES = 180;+// Bounded at roughly the number of claims a very busy hour could produce, so+// the state row stays small while still covering the whole scan window.+const SEEN_LIMIT = 400;+const LOCK_KEY = 'pump_claims_push_lock';+const LOCK_TTL_S = 240;+const STATE_KEY = 'pump_claims_push_telegram';+// Bounded, and deliberately well under LOCK_TTL_S. The lock is what stops two+// ticks posting the same claim twice, but it only holds for its TTL: a request+// that hangs longer outlives its own lock and the next tick re-posts what the+// stalled one is still working through.+const TELEGRAM_TIMEOUT_MS = 20_000;++const LAMPORTS_PER_SOL = 1e9;++async function ensureTable() {+ await sql`+ CREATE TABLE IF NOT EXISTS app_settings (+ key text PRIMARY KEY,+ value jsonb NOT NULL,+ updated_at timestamptz NOT NULL DEFAULT now()+ )+ `;+}++async function getState(key) {+ const [row] = await sql`SELECT value FROM app_settings WHERE key = ${key}`;+ return row?.value ?? null;+}++async function setState(key, value) {+ await sql`+ INSERT INTO app_settings (key, value) VALUES (${key}, ${JSON.stringify(value)}::jsonb)+ ON CONFLICT (key) DO UPDATE SET value = excluded.value, updated_at = now()+ `;+}++export async function acquireLock() {+ await ensureTable();+ const rows = await sql`+ INSERT INTO app_settings (key, value)+ VALUES (${LOCK_KEY}, jsonb_build_object('until', extract(epoch from now()) + ${LOCK_TTL_S}))+ ON CONFLICT (key) DO UPDATE+ SET value = excluded.value, updated_at = now()+ WHERE (app_settings.value->>'until')::numeric < extract(epoch from now())+ RETURNING key+ `;+ return rows.length > 0;+}++export async function releaseLock() {+ await setState(LOCK_KEY, { until: 0 });+}++const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++/**+ * Returns the claims to post, oldest-first, from a newest-first scan result.+ *+ * Selection is by signature against `seen` (exact) and by age against the+ * cutoff (so a long outage drains recent claims and drops stale ones rather+ * than replaying an hour of history). `lastTs` is not used to select: it only+ * bounds the scan window upstream, because a claim can share a second with the+ * last one posted and would be lost by a strictly-greater timestamp compare.+ *+ * @param {Array<{creator:string, mint:string, signature:string, lamports:number, ts:number}>} claims+ * @param {{ seen?: string[] }} state+ * @param {number} [nowMs]+ */+export function newClaimsSince(claims, state = {}, nowMs = Date.now()) {+ const seen = new Set(state.seen || []);+ const oldestPostableTs = Math.floor(nowMs / 1000) - CUTOFF_MINUTES * 60;+ return claims+ .filter((c) => c.signature && !seen.has(c.signature))+ .filter((c) => Number.isFinite(c.ts) && c.ts >= oldestPostableTs)+ .sort((a, b) => a.ts - b.ts);+}++/** Appends signatures to the bounded ring, newest kept. */+export function rememberSignatures(seen = [], signatures = []) {+ const merged = [...seen, ...signatures];+ return merged.slice(Math.max(0, merged.length - SEEN_LIMIT));+}++const escapeHtml = (s) =>+ String(s).replace(/[<>&]/g, (c) => ({ '<': '<', '>': '>', '&': '&' })[c]);++/** Middle-truncates a base58 address so a message stays one line on mobile. */+export function shortAddress(addr) {+ const s = String(addr || '');+ return s.length > 12 ? `${s.slice(0, 4)}…${s.slice(-4)}` : s;+}++/** Lamports rendered as SOL with a precision that stays readable at any size. */+export function formatSol(lamports) {+ const sol = Number(lamports || 0) / LAMPORTS_PER_SOL;+ if (!Number.isFinite(sol) || sol <= 0) return '0 SOL';+ if (sol < 0.001) return '<0.001 SOL';+ if (sol < 1) return `${sol.toFixed(3)} SOL`;+ if (sol < 1000) return `${sol.toFixed(2)} SOL`;+ return `${Math.round(sol).toLocaleString('en-US')} SOL`;+}++// Every field below is derived from on-chain data supplied by a third party.+// Addresses are base58 and cannot carry markup, but they are escaped anyway so+// a malformed scan result can never break out of the HTML entity structure and+// smuggle a clickable link posted under the platform bot's identity.+/**+ * @param {{creator:string, mint:string, signature:string, lamports:number, ts:number}} claim+ */+export function formatTelegramMessage(claim) {+ const when = Number.isFinite(claim.ts)+ ? new Date(claim.ts * 1000).toISOString().replace('T', ' ').slice(0, 16) + ' UTC'+ : '';+ const lines = [+ '<b>First creator fee claim</b>',+ '',+ `Creator <code>${escapeHtml(claim.creator)}</code>`,+ ];+ if (claim.mint) lines.push(`Coin <code>${escapeHtml(claim.mint)}</code>`);+ lines.push('', `Claimed ${escapeHtml(formatSol(claim.lamports))}`);++ const refs = [+ `<a href="https://solscan.io/tx/${encodeURIComponent(claim.signature)}">tx ${escapeHtml(shortAddress(claim.signature))}</a>`,+ ];+ if (claim.mint) {+ refs.push(+ `<a href="https://pump.fun/coin/${encodeURIComponent(claim.mint)}">pump.fun</a>`,+ );+ }+ lines.push('', `${refs.join(' · ')}${when ? ` · ${escapeHtml(when)}` : ''}`);+ return lines.join('\n');+}++async function sendTelegram(botToken, chatId, text) {+ const res = await fetch(`https://api.telegram.org/bot${botToken}/sendMessage`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ chat_id: chatId,+ text,+ parse_mode: 'HTML',+ // The links are block explorers, not three.ws pages, and a preview+ // card per claim would bury the text in a high-volume feed.+ link_preview_options: { is_disabled: true },+ }),+ signal: AbortSignal.timeout(TELEGRAM_TIMEOUT_MS),+ });+ const body = await res.json().catch(() => ({}));+ if (!res.ok || !body.ok) {+ throw new Error(+ `Telegram sendMessage failed (${res.status}): ${body.description || 'unknown error'}`,+ );+ }+}++export async function pushTelegramLane({ scan = scanFirstClaims, now = Date.now } = {}) {+ const botToken = process.env.TELEGRAM_BOT_TOKEN;+ const chatId = process.env.TELEGRAM_PUMP_CLAIMS_CHAT_ID;+ if (!botToken || !chatId) return { skipped: 'not_configured' };++ const nowMs = now();+ const state = (await getState(STATE_KEY)) || { lastTs: null, seen: [] };+ // A resumed lane re-scans from its cursor so a gap wider than one window+ // still resolves, bounded by the cutoff so it can never replay history.+ const windowStart = Math.floor(nowMs / 1000) - SCAN_MINUTES * 60;+ const cutoffStart = Math.floor(nowMs / 1000) - CUTOFF_MINUTES * 60;+ const sinceTs = state.lastTs+ ? Math.max(cutoffStart, Math.min(windowStart, state.lastTs))+ : windowStart;++ const claims = await scan({ sinceTs, limit: 50 });++ if (!state.lastTs) {+ // Seed: record what is already on-chain so enabling the lane posts+ // nothing, then start posting from the next tick onward.+ await setState(STATE_KEY, {+ lastTs: claims.length ? Math.max(...claims.map((c) => c.ts)) : Math.floor(nowMs / 1000),+ seen: rememberSignatures([], claims.map((c) => c.signature)),+ });+ return { posted: 0, seeded: true, scanned: claims.length };+ }++ const pending = newClaimsSince(claims, state, nowMs);+ if (pending.length === 0) return { posted: 0, scanned: claims.length };++ // Oldest-first: a backlog larger than one run drains across the following+ // ticks in claim order. Taking the newest would strand everything older.+ const batch = pending.slice(0, TELEGRAM_LIMIT);+ const backlog = pending.length - batch.length;+ if (backlog > 0) {+ console.warn(+ `[pump-claims] ${backlog} claims still queued after this run; draining ${TELEGRAM_LIMIT}/tick`,+ );+ }++ let sent = 0;+ let { lastTs, seen } = state;+ try {+ for (const claim of batch) {+ await sendTelegram(botToken, chatId, formatTelegramMessage(claim));+ lastTs = Math.max(Number(lastTs) || 0, claim.ts);+ seen = rememberSignatures(seen, [claim.signature]);+ sent++;+ // Written per claim, not per run: a tick killed mid-batch (the Cloud+ // Run request deadline is shorter than a full paced run) resumes at+ // the next claim rather than repeating the ones already delivered.+ await setState(STATE_KEY, { lastTs, seen });+ await sleep(TELEGRAM_PACE_MS);+ }+ } catch (err) {+ return { posted: sent, backlog, error: String(err?.message || err) };+ }+ return { posted: sent, backlog, scanned: claims.length };+}diff --git a/api/cron/pump-claims-push.js b/api/cron/pump-claims-push.jsnew file mode 100644index 000000000..2868e0211--- /dev/null+++ b/api/cron/pump-claims-push.js@@ -0,0 +1,43 @@+// @ts-check+// GET /api/cron/pump-claims-push posts every new pump.fun FIRST creator-fee+// claim to Telegram as it lands.+//+// Runs every 5 minutes. Scans recent claims via the shared scanner in+// api/_lib/pump-claims.js, diffs them against the last-posted signatures in+// app_settings, and posts anything new, oldest-first, one message per claim.+//+// Destination: TELEGRAM_PUMP_CLAIMS_CHAT_ID. There is no fallback to the+// holder channel on purpose (see api/_lib/pump-claims-push.js).+//+// A lane whose credentials are absent reports { skipped: 'not_configured' }.+// Telegram: TELEGRAM_BOT_TOKEN + TELEGRAM_PUMP_CLAIMS_CHAT_ID+//+// The scan itself needs a claims source. With PUMPFUN_BOT_URL configured it+// reads the indexer; without it the scanner falls back to a direct RPC scan+// that cannot cover a useful time window on a program this busy, so the lane+// reports { scanned: 0 } indefinitely. See docs/pump-claims-channel.md.+//+// A DB lock (app_settings) keeps overlapping ticks from double-posting.++import { json, method, wrapCron } from '../_lib/http.js';+import { acquireLock, releaseLock, pushTelegramLane } from '../_lib/pump-claims-push.js';+import { requireCron } from '../_lib/cron-auth.js';++export default wrapCron(async (req, res) => {+ if (!method(req, res, ['GET'])) return;+ if (!requireCron(req, res)) return;++ if (!(await acquireLock())) {+ json(res, 200, { ok: true, skipped: 'locked' });+ return;+ }++ try {+ const telegram = await pushTelegramLane();+ const failed = Boolean(telegram.error);+ if (failed) console.warn('[cron] pump-claims-push lane error', { telegram });+ json(res, failed ? 502 : 200, { ok: !failed, telegram });+ } finally {+ await releaseLock().catch(() => {});+ }+});diff --git a/docs/pump-claims-channel.md b/docs/pump-claims-channel.mdnew file mode 100644index 000000000..8db65e6ef--- /dev/null+++ b/docs/pump-claims-channel.md@@ -0,0 +1,150 @@+# pump.fun first-claims Telegram channel++A live feed of **first-time pump.fun creator fee claims**, delivered to a+Telegram channel (`@pumpfunclaims`), one message per claim.++A "first claim" is the first time a creator ever pulls their accrued+creator/delegated rewards out of the fee vault. It is an on-chain, irreversible+signal that the creator is live and engaged with their coin, which is why it+gets its own channel rather than a line in the holder changelog.++## How it works++```+pump.fun program activity+ │+ ▼+scanFirstClaims() api/_lib/pump-claims.js+ ├── PUMPFUN_BOT_URL indexer (preferred)+ └── direct Solana RPC scan (fallback, see "Known limits")+ │+ ▼+pushTelegramLane() api/_lib/pump-claims-push.js+ ├── diff against app_settings['pump_claims_push_telegram']+ ├── oldest-first, 10 per tick, 3.5s apart+ └── Telegram sendMessage → TELEGRAM_PUMP_CLAIMS_CHAT_ID+ │+ ▼+GET /api/cron/pump-claims-push every 5 minutes (Cloud Scheduler)+```++The same scanner also backs `GET /api/pump/first-claims` and the+`pumpfun_first_claims` MCP tool, so the channel and the API never disagree.++## Configuration++| Variable | Required | Purpose |+|---|---|---|+| `TELEGRAM_BOT_TOKEN` | yes | Bot that posts. Create via [@BotFather](https://t.me/BotFather). |+| `TELEGRAM_PUMP_CLAIMS_CHAT_ID` | yes | `@pumpfunclaims`, or the `-100…` numeric id. |+| `PUMPFUN_BOT_URL` | yes in practice | pump.fun claims indexer. Without it the scan returns nothing (see below). |+| `PUMPFUN_BOT_TOKEN` | optional | Bearer token for the indexer, when it requires one. |++The bot **must be an administrator of the channel** with permission to post.+Telegram rejects `sendMessage` from a non-admin bot to a channel with+`403: Bot is not a member of the channel chat`.++There is deliberately **no fallback** to `TELEGRAM_CHANGELOG_CHAT_ID`. This feed+is high-volume third-party coin activity; the holder changelog is a different+audience. With `TELEGRAM_PUMP_CLAIMS_CHAT_ID` unset the lane reports+`{ skipped: 'not_configured' }` and posts nothing.++Set the variables on the running service (never with `--set-env-vars`, which+replaces the entire env set):++```bash+gcloud run services update three-ws-api \+ --region us-central1 --project aerial-vehicle-466722-p5 \+ --update-env-vars TELEGRAM_PUMP_CLAIMS_CHAT_ID=@pumpfunclaims+```++## Verifying it++```bash+# 1. Is the scan returning claims at all?+curl -s 'https://three.ws/api/pump/first-claims?sinceMinutes=60&limit=5'++# 2. Does the bot have channel access? (replace $TOKEN)+curl -s "https://api.telegram.org/bot$TOKEN/getChat?chat_id=@pumpfunclaims"++# 3. Watch the lane+gcloud logging read 'resource.type="cloud_run_revision"+ resource.labels.service_name="three-ws-api"+ textPayload:"pump-claims"' --freshness=1h+```++The cron returns its lane result in the response body, so a manual authenticated+call reports exactly what happened: `{ posted, scanned, backlog }`, or+`{ skipped }`, or `{ error }`.++## State and safety properties++State lives in `app_settings` under `pump_claims_push_telegram`:++```json+{ "lastTs": 1723661000, "seen": ["<tx signature>", "..."] }+```++- **First run seeds without posting.** Enabling the lane records what is already+ on-chain and starts posting from the next tick, so switching it on never dumps+ a backlog into the channel.+- **Dedupe is by transaction signature**, not by timestamp. Two claims landing in+ the same second are common; a timestamp-only cursor would silently drop the+ second one. `seen` is a bounded ring of 400 signatures; `lastTs` bounds the+ scan window so the ring never has to answer for anything older.+- **A three-hour cutoff** bounds any catch-up. A lane that has been down for a+ day drains recent claims and drops stale ones rather than replaying history.+- **State is written per message, not per run.** A tick killed mid-batch (the+ Cloud Run request deadline is shorter than a full paced run) resumes at the+ next claim instead of repeating delivered ones.+- **A DB lock** (`pump_claims_push_lock`, 240s TTL) stops overlapping ticks from+ double-posting. Every outbound request is bounded well under that TTL, which+ is what keeps the lock's guarantee true.+- **All message fields are HTML-escaped.** Claim data is third-party on-chain+ data; unescaped text could otherwise smuggle a clickable link posted under the+ platform bot's identity.++## Known limits: the RPC fallback cannot serve this feed++`scanFirstClaims` prefers the `PUMPFUN_BOT_URL` indexer and falls back to a+direct RPC scan of the pump program's recent signatures. **That fallback cannot+produce a useful result, and the channel will stay silent without the indexer.**++Measured against mainnet on 2026-08-14:++```+getSignaturesForAddress(pump program, limit: 200)+ → 200 signatures+ → wall-clock span covered: 0 seconds+ → 172 of 200 were failed transactions+```++The pump.fun program clears its 200-signature page in under one second, so the+fallback samples a fraction of a single second of chain activity no matter what+`sinceMinutes` the caller asks for. Two consequences:++1. A claim instruction is rare relative to buys and sells, so a sample that+ small almost never contains one.+2. "First ever claim" cannot be established from one second of history, which is+ the whole point of the feed.++Paginating backwards does not fix it: at roughly 200 transactions per second,+one hour of lookback is on the order of 700k signatures.++The supported source is an indexer. `PUMPFUN_BOT_URL` points at the upstream+`pumpfun-claims-bot`, and it is **not configured on the production service**,+which is why `GET /api/pump/first-claims` currently returns `{"items":[]}` for+every window. Set it and the channel starts posting with no code change.++If no indexer is available, the alternative that fits this repo is a Helius+enhanced-transaction webhook on the pump program filtered to the claim+discriminators, received at a sibling of+[api/pump/helius-webhook.js](../api/pump/helius-webhook.js). That path is not+built yet.++## Related++- [api/_lib/pump-claims.js](../api/_lib/pump-claims.js) - the shared scanner+- [api/_lib/pump-claims-push.js](../api/_lib/pump-claims-push.js) - the delivery lane+- [api/cron/pump-claims-push.js](../api/cron/pump-claims-push.js) - the cron entry point+- [api/_lib/commit-feed-push.js](../api/_lib/commit-feed-push.js) - the sibling commit feed this lane mirrorsdiff --git a/tests/pump-claims-push.test.js b/tests/pump-claims-push.test.jsnew file mode 100644index 000000000..910bc16a3--- /dev/null+++ b/tests/pump-claims-push.test.js@@ -0,0 +1,145 @@+import { describe, it, expect } from 'vitest';+import {+ newClaimsSince,+ rememberSignatures,+ formatSol,+ shortAddress,+ formatTelegramMessage,+} from '../api/_lib/pump-claims-push.js';++// Fixed clock so the cutoff arithmetic is deterministic.+const NOW_MS = 1_700_000_000_000;+const NOW_S = Math.floor(NOW_MS / 1000);++// Synthetic mint/creator placeholders only: no real third-party mainnet+// addresses belong in committed fixtures.+function claim(signature, ts, overrides = {}) {+ return {+ creator: 'THREEsynthCreator1111111111111111111111111',+ mint: 'THREEsynthMint11111111111111111111111111111',+ signature,+ lamports: 1e9,+ ts,+ ...overrides,+ };+}++describe('newClaimsSince selection', () => {+ it('returns unseen claims oldest-first', () => {+ const claims = [claim('c', NOW_S - 60), claim('a', NOW_S - 300), claim('b', NOW_S - 120)];+ const out = newClaimsSince(claims, { seen: [] }, NOW_MS);+ expect(out.map((c) => c.signature)).toEqual(['a', 'b', 'c']);+ });++ it('drops claims already posted, matched by signature', () => {+ const claims = [claim('a', NOW_S - 300), claim('b', NOW_S - 120)];+ const out = newClaimsSince(claims, { seen: ['a'] }, NOW_MS);+ expect(out.map((c) => c.signature)).toEqual(['b']);+ });++ it('keeps a claim sharing its second with the last posted one', () => {+ // The exact case a timestamp-only cursor loses: same ts, different tx.+ const ts = NOW_S - 100;+ const claims = [claim('a', ts), claim('b', ts)];+ const out = newClaimsSince(claims, { seen: ['a'], lastTs: ts }, NOW_MS);+ expect(out.map((c) => c.signature)).toEqual(['b']);+ });++ it('drops claims older than the cutoff so a catch-up never replays history', () => {+ const claims = [claim('old', NOW_S - 4 * 3600), claim('fresh', NOW_S - 60)];+ const out = newClaimsSince(claims, { seen: [] }, NOW_MS);+ expect(out.map((c) => c.signature)).toEqual(['fresh']);+ });++ it('ignores entries with no signature or an unusable timestamp', () => {+ const claims = [claim('', NOW_S - 60), claim('nan', Number.NaN), claim('ok', NOW_S - 60)];+ const out = newClaimsSince(claims, { seen: [] }, NOW_MS);+ expect(out.map((c) => c.signature)).toEqual(['ok']);+ });++ it('treats missing state as nothing seen', () => {+ const out = newClaimsSince([claim('a', NOW_S - 60)], {}, NOW_MS);+ expect(out).toHaveLength(1);+ });+});++describe('rememberSignatures bounded ring', () => {+ it('appends new signatures', () => {+ expect(rememberSignatures(['a'], ['b'])).toEqual(['a', 'b']);+ });++ it('caps the ring and keeps the newest entries', () => {+ const seen = Array.from({ length: 400 }, (_, i) => `s${i}`);+ const out = rememberSignatures(seen, ['new']);+ expect(out).toHaveLength(400);+ expect(out.at(-1)).toBe('new');+ expect(out).not.toContain('s0');+ });++ it('defaults both arguments', () => {+ expect(rememberSignatures()).toEqual([]);+ });+});++describe('formatSol', () => {+ it('renders whole SOL with two decimals', () => {+ expect(formatSol(2.5 * 1e9)).toBe('2.50 SOL');+ });++ it('renders sub-1 SOL with three decimals', () => {+ expect(formatSol(0.25 * 1e9)).toBe('0.250 SOL');+ });++ it('floors dust rather than showing 0.000 SOL', () => {+ expect(formatSol(1000)).toBe('<0.001 SOL');+ });++ it('groups large amounts', () => {+ expect(formatSol(12345 * 1e9)).toBe('12,345 SOL');+ });++ it('handles zero and garbage', () => {+ expect(formatSol(0)).toBe('0 SOL');+ expect(formatSol(Number.NaN)).toBe('0 SOL');+ });+});++describe('shortAddress', () => {+ it('middle-truncates a base58 address', () => {+ expect(shortAddress('ABCDEFGHIJKLMNOP')).toBe('ABCD…MNOP');+ });++ it('leaves a short string alone', () => {+ expect(shortAddress('ABCD')).toBe('ABCD');+ });++ it('handles null', () => {+ expect(shortAddress(null)).toBe('');+ });+});++describe('formatTelegramMessage', () => {+ it('includes the creator, amount, and both reference links', () => {+ const msg = formatTelegramMessage(claim('sig123', NOW_S));+ expect(msg).toContain('First creator fee claim');+ expect(msg).toContain('THREEsynthCreator1111111111111111111111111');+ expect(msg).toContain('1.00 SOL');+ expect(msg).toContain('https://solscan.io/tx/sig123');+ expect(msg).toContain('https://pump.fun/coin/THREEsynthMint11111111111111111111111111111');+ });++ it('omits the coin line and pump.fun link when the mint is unknown', () => {+ const msg = formatTelegramMessage(claim('sig123', NOW_S, { mint: '' }));+ expect(msg).not.toContain('Coin ');+ expect(msg).not.toContain('pump.fun');+ expect(msg).toContain('https://solscan.io/tx/sig123');+ });++ it('escapes HTML so a malformed scan result cannot inject markup', () => {+ const msg = formatTelegramMessage(+ claim('sig123', NOW_S, { creator: '<a href="https://evil.example">x</a>' }),+ );+ expect(msg).toContain('<a href=');+ expect(msg).not.toContain('<a href="https://evil.example"');+ });+});diff --git a/vercel.json b/vercel.jsonindex 57a1bfb19..a0614130f 100644--- a/vercel.json+++ b/vercel.json@@ -6017,6 +6017,10 @@"path": "/api/cron/commit-feed-push","schedule": "*/5 * * * *"},+ {+ "path": "/api/cron/pump-claims-push",+ "schedule": "*/5 * * * *"+ },{"path": "/api/cron/forge-off-crown","schedule": "7 0 * * 1"