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: add Helius webhook support for pump.fun wallet monitoring and create webhook endpoint
nirholas308c97d3267b
diff --git a/api/_lib/helius.js b/api/_lib/helius.jsnew file mode 100644index 000000000..529192f7f--- /dev/null+++ b/api/_lib/helius.js@@ -0,0 +1,121 @@+// Helius webhook helpers for pump.fun wallet monitoring.+//+// Replaces 5s polling (pumpfun-copy-trade) and reduces RPC pressure on the+// browser-side WalletMonitor. Helius pushes enhanced txns to our endpoint+// within ~1-2s of confirmation. Free tier: 100k webhook events/mo.+//+// Docs: https://docs.helius.dev/webhooks-and-websockets/webhooks+//+// Env:+// HELIUS_API_KEY — required to register webhooks+// HELIUS_WEBHOOK_AUTH — shared secret echoed in 'authorization' header+// on every push; required to authenticate inbound++const PUMP_PROGRAM = '6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P';+const PUMP_AMM_PROGRAM = 'pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA';++const HELIUS_API = 'https://api.helius.xyz/v0/webhooks';++function apiKey() {+ const k = process.env.HELIUS_API_KEY;+ if (!k) throw new Error('HELIUS_API_KEY not set');+ return k;+}++export function heliusEnabled() {+ return Boolean(process.env.HELIUS_API_KEY && process.env.HELIUS_WEBHOOK_AUTH);+}++/**+ * Create a webhook that pushes pump.fun txns for `wallets` to `webhookURL`.+ * Idempotent at the caller level — Helius will create a new one each call.+ * @param {{ wallets: string[], webhookURL: string, network?: 'mainnet'|'devnet' }} opts+ */+export async function createWebhook({ wallets, webhookURL, network = 'mainnet' }) {+ const r = await fetch(`${HELIUS_API}?api-key=${apiKey()}`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ webhookURL,+ transactionTypes: ['Any'],+ accountAddresses: wallets,+ webhookType: network === 'devnet' ? 'enhancedDevnet' : 'enhanced',+ authHeader: process.env.HELIUS_WEBHOOK_AUTH,+ }),+ });+ if (!r.ok) throw new Error(`helius create webhook failed: ${r.status} ${await r.text()}`);+ return r.json();+}++/** Replace `accountAddresses` on an existing webhook (use to add/remove wallets in batch). */+export async function updateWebhookWallets(webhookID, wallets) {+ const r = await fetch(`${HELIUS_API}/${webhookID}?api-key=${apiKey()}`, {+ method: 'PUT',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ accountAddresses: wallets }),+ });+ if (!r.ok) throw new Error(`helius update failed: ${r.status} ${await r.text()}`);+ return r.json();+}++export async function listWebhooks() {+ const r = await fetch(`${HELIUS_API}?api-key=${apiKey()}`);+ if (!r.ok) throw new Error(`helius list failed: ${r.status}`);+ return r.json();+}++export async function deleteWebhook(webhookID) {+ const r = await fetch(`${HELIUS_API}/${webhookID}?api-key=${apiKey()}`, { method: 'DELETE' });+ if (!r.ok && r.status !== 404) throw new Error(`helius delete failed: ${r.status}`);+}++/**+ * Parse pump.fun trades from a Helius enhanced txn payload. Returns one entry+ * per qualifying instruction, [] if the txn doesn't touch pump.fun.+ *+ * @param {object} tx — single Helius enhanced txn object (one element of the+ * POST body array)+ * @returns {Array<{ side:'buy'|'sell', mint:string, sol:number, wallet:string, signature:string, slot:number, ts:number }>}+ */+export function parsePumpTrades(tx) {+ if (!tx || !Array.isArray(tx.instructions)) return [];+ const signature = tx.signature;+ const slot = tx.slot ?? 0;+ const ts = tx.timestamp ?? Math.floor(Date.now() / 1000);+ const fee = tx.feePayer;++ const out = [];+ for (const ix of tx.instructions) {+ if (ix.programId !== PUMP_PROGRAM && ix.programId !== PUMP_AMM_PROGRAM) continue;+ const side = matchSide(ix);+ if (!side) continue;++ const transfers = tx.tokenTransfers || [];+ const native = tx.nativeTransfers || [];+ const mint = transfers.find((t) => t.fromUserAccount === fee || t.toUserAccount === fee)?.mint;+ const lamports = native+ .filter((n) => n.fromUserAccount === fee || n.toUserAccount === fee)+ .reduce((acc, n) => acc + (n.amount || 0), 0);++ if (!mint) continue;+ out.push({+ side,+ mint,+ sol: Math.abs(lamports) / 1e9,+ wallet: fee,+ signature,+ slot,+ ts,+ });+ }+ return out;+}++function matchSide(ix) {+ // Helius decodes pump.fun ixs by name when it can.+ const name = (ix.parsed?.type || ix.innerInstructions?.[0]?.parsed?.type || '').toLowerCase();+ if (name.includes('buy')) return 'buy';+ if (name.includes('sell')) return 'sell';+ // Fallback: discriminator-free heuristic via inner logs would go here.+ return null;+}diff --git a/api/pump/helius-webhook.js b/api/pump/helius-webhook.jsnew file mode 100644index 000000000..70a59bc28--- /dev/null+++ b/api/pump/helius-webhook.js@@ -0,0 +1,57 @@+// POST /api/pump/helius-webhook+// ------------------------------+// Inbound receiver for Helius enhanced-txn webhooks. Helius pushes a JSON+// array of decoded txns whenever a monitored wallet has activity. We filter+// to pump.fun buys/sells and persist to `pump_agent_trades` so the wallet+// monitor UI / copy-trade skill can consume from DB instead of polling RPC.+//+// Auth: shared-secret in 'authorization' header (set via HELIUS_WEBHOOK_AUTH).+// Body: array of Helius enhanced txn objects.+//+// To register the webhook, run once from a server-side script:+// import { createWebhook } from '../_lib/helius.js';+// await createWebhook({+// wallets: [...],+// webhookURL: `${env.APP_ORIGIN}/api/pump/helius-webhook`,+// });++import { sql } from '../_lib/db.js';+import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';+import { parsePumpTrades } from '../_lib/helius.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;+ if (!method(req, res, ['POST'])) return;++ const expected = process.env.HELIUS_WEBHOOK_AUTH;+ if (!expected) return error(res, 503, 'not_configured', 'helius webhook auth not set');+ if (req.headers.authorization !== expected) {+ return error(res, 401, 'unauthorized', 'bad auth header');+ }++ const body = await readJson(req);+ const txns = Array.isArray(body) ? body : [];++ const trades = txns.flatMap(parsePumpTrades);+ if (trades.length === 0) return json(res, 200, { received: txns.length, trades: 0 });++ let inserted = 0;+ for (const t of trades) {+ const r = await sql`+ insert into pump_agent_trades (+ mint_id, user_id, wallet, direction, route,+ sol_amount, tx_signature, network+ )+ select+ m.id, null, ${t.wallet}, ${t.side}, 'bonding_curve',+ ${Math.round(t.sol * 1e9)}, ${t.signature}, 'mainnet'+ from pump_agent_mints m+ where m.mint = ${t.mint}+ on conflict (tx_signature, network) do nothing+ returning id+ `;+ if (r.length) inserted++;+ }++ return json(res, 200, { received: txns.length, trades: trades.length, inserted });+});diff --git a/vercel.json b/vercel.jsonindex f3125ff5e..9c5186831 100644--- a/vercel.json+++ b/vercel.json@@ -111,6 +111,7 @@{ "src": "/api/pump/deliver-telegram", "dest": "/api/pump/[action]?action=deliver-telegram" },{ "src": "/api/pump/first-claims", "dest": "/api/pump/[action]?action=first-claims" },{ "src": "/api/pump/vanity-keygen", "dest": "/api/pump/[action]?action=vanity-keygen" },+ { "src": "/api/pump/helius-webhook", "dest": "/api/pump/helius-webhook" },{ "src": "/api/avatars/presign", "dest": "/api/avatars/[id]" },{ "src": "/api/avatars/public", "dest": "/api/avatars/[id]" },{ "src": "/api/avatars/regenerate-status", "dest": "/api/avatars/[id]" },