-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathpumpfun.js
More file actions
256 lines (239 loc) · 9.86 KB
/
Copy pathpumpfun.js
File metadata and controls
256 lines (239 loc) · 9.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
/**
* GET /api/agents/pumpfun
* -----------------------
* Read-only proxy to the upstream pumpfun-claims-bot MCP server. Backs the
* `pumpfun-recent-claims` and `pumpfun-token-intel` skills, plus any external
* MCP client that wants enriched pump.fun intel without standing up its own
* indexer.
*
* Query:
* ?op=claims &limit=10
* ?op=graduations &limit=10
* ?op=token &mint=<base58>
* ?op=creator &wallet=<base58>
*
* Auth: session OR bearer (scope `mcp` or `profile`).
* Cache: per-op, short TTL handled in api/_lib/pumpfun-mcp.js.
*/
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
import { cors, json, method, error, wrap, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { pumpfunMcp, pumpfunBotEnabled } from '../_lib/pumpfun-mcp.js';
export default wrap(async (req, res) => {
// Dispatch pumpfun-feed and pumpfun-metadata via _handler param (set by vercel.json rewrite)
const _handler = req.query?._handler;
if (_handler === 'feed') return handleFeed(req, res);
if (_handler === 'metadata') return handleMetadata(req, res);
if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET'])) return;
const session = await getSessionUser(req);
const bearer = session ? null : await authenticateBearer(extractBearer(req));
if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
if (bearer && !hasScope(bearer.scope, 'mcp') && !hasScope(bearer.scope, 'profile')) {
return error(res, 403, 'insufficient_scope', 'requires mcp or profile scope');
}
const userId = session?.id ?? bearer.userId;
const rl = await limits.mcpUser(String(userId));
if (!rl.success) return rateLimited(res, rl);
const url = new URL(req.url, 'http://x');
const op = url.searchParams.get('op') || 'claims';
const limit = clamp(Number(url.searchParams.get('limit')) || 10, 1, 50);
// Soft-degrade to empty data when the upstream feed isn't configured —
// callers get a usable 200 rather than a noisy 503 on every poll.
if (!pumpfunBotEnabled()) {
const empty = op === 'token' || op === 'creator' ? {} : { items: [] };
return json(res, 200, empty);
}
let result;
switch (op) {
case 'claims':
result = await pumpfunMcp.recentClaims({ limit });
break;
case 'graduations':
result = await pumpfunMcp.graduations({ limit });
break;
case 'token': {
const mint = url.searchParams.get('mint');
if (!mint) return error(res, 400, 'validation_error', 'mint required');
result = await pumpfunMcp.tokenIntel({ mint });
break;
}
case 'creator': {
const wallet = url.searchParams.get('wallet');
if (!wallet) return error(res, 400, 'validation_error', 'wallet required');
result = await pumpfunMcp.creatorIntel({ wallet });
break;
}
default:
return error(res, 400, 'validation_error', 'unknown op');
}
if (!result.ok) {
return error(res, 502, 'upstream_error', result.error || 'pumpfun bot unavailable');
}
const payload = Array.isArray(result.data) ? { items: result.data } : result.data;
return json(res, 200, payload);
});
function clamp(n, lo, hi) {
return Math.max(lo, Math.min(hi, n));
}
// ── pumpfun-feed (SSE) ────────────────────────────────────────────────────────
import { connectPumpFunFeed, recentBuffered } from '../_lib/pumpfun-ws-feed.js';
const TIER_RANK = { notable: 1, influencer: 2, mega: 3 };
async function handleFeed(req, res) {
if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET'])) return;
const rl = await limits.mcpIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl, 'too many feed connections');
const url = new URL(req.url, 'http://x');
const kind = url.searchParams.get('kind') || 'all';
const mintParam = url.searchParams.get('mint');
const minTierParam = url.searchParams.get('minTier');
const minTier = TIER_RANK[minTierParam] || 0;
const mcMin = Number(url.searchParams.get('mcMin')) || 0;
const mcMax = Number(url.searchParams.get('mcMax')) || 0;
const minBuy = Number(url.searchParams.get('minBuy')) || 0;
const whale = Number(url.searchParams.get('whale')) || 0;
function passesFilters(ev) {
if (minTier && TIER_RANK[(ev?.tier || '').toLowerCase()] < minTier) return false;
const mc = ev?.usd_market_cap ?? ev?.market_cap_usd ?? ev?.market_cap ?? null;
if (mcMin && mc != null && mc < mcMin) return false;
if (mcMax && mc != null && mc > mcMax) return false;
const initBuy = ev?.initial_buy_sol ?? null;
if (minBuy && initBuy != null && initBuy < minBuy) return false;
const tradeSol = ev?.initial_buy_sol ?? ev?.amount_sol ?? ev?.sol_amount ?? null;
if (whale && tradeSol != null && tradeSol < whale) return false;
return true;
}
res.statusCode = 200;
res.setHeader('content-type', 'text/event-stream; charset=utf-8');
res.setHeader('cache-control', 'no-store');
res.setHeader('connection', 'keep-alive');
res.setHeader('x-accel-buffering', 'no');
res.flushHeaders?.();
const started = Date.now();
let active = true;
req.on('close', () => {
active = false;
});
const wsAbort = new AbortController();
req.on('close', () => wsAbort.abort());
const queue = [];
const wsKind = kind === 'claims' ? 'graduation' : kind;
// `trades` is per-mint on PumpPortal — require a mint and stream that token's
// buy/sell flow. Other kinds (mint/graduation/all) ignore the mint param.
const tradeMints = wsKind === 'trades' && mintParam ? [mintParam] : [];
const stopWs = connectPumpFunFeed({
kind: wsKind,
mints: tradeMints,
signal: wsAbort.signal,
onEvent: ({ kind: evKind, data }) => {
if (active) queue.push({ evKind, data });
},
});
_writeSse(res, 'open', { kind, minTier: minTierParam || null, source: 'websocket' });
// Replay the most recent buffered events so a freshly-opened feed is never
// blank. Newest first so the UI's `prepend` results in chronological order.
try {
const replay = recentBuffered({ kind: wsKind, limit: 10 });
// Emit oldest-first so each `prepend` puts the newest at the top.
for (const ev of replay.slice().reverse()) {
if (!passesFilters(ev.data)) continue;
_writeSse(res, ev.kind, { ...ev.data, replay: true });
}
} catch (err) {
console.warn('[pumpfun-feed] replay failed:', err?.message);
}
const seen = new Set();
let lastSig = null;
const tickClaims = pumpfunBotEnabled()
? async () => {
if (kind !== 'claims' && kind !== 'all') return;
const r = await pumpfunMcp.claimsSince({ sinceSig: lastSig, limit: 25 });
if (!r.ok) return;
const items = Array.isArray(r.data) ? r.data : r.data?.items || [];
for (const ev of items) {
const id = ev.tx_signature || ev.signature || ev.id;
if (!id || seen.has(id)) continue;
seen.add(id);
if (!passesFilters(ev)) continue;
lastSig = id;
_writeSse(res, 'claim', ev);
}
}
: null;
while (active && Date.now() - started < 90_000) {
while (queue.length > 0 && active) {
const { evKind, data } = queue.shift();
if (passesFilters(data)) _writeSse(res, evKind, data);
}
if (tickClaims) {
try {
await tickClaims();
} catch {}
}
_writeSse(res, 'ping', { t: Date.now() });
await new Promise((r) => setTimeout(r, 4000));
}
stopWs();
_writeSse(res, 'close', { reason: 'duration_limit' });
res.end();
}
function _writeSse(res, event, data) {
res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
}
// ── pumpfun-metadata ──────────────────────────────────────────────────────────
import { sql as _sql } from '../_lib/db.js';
import { env as _env } from '../_lib/env.js';
import { isUuid } from '../_lib/validate.js';
async function handleMetadata(req, res) {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET'])) return;
const rlMeta = await limits.publicIp(clientIp(req));
if (!rlMeta.success) return rateLimited(res, rlMeta);
const url = new URL(req.url, `http://${req.headers.host}`);
const id = url.searchParams.get('id');
if (!id) return error(res, 400, 'validation_error', 'id required');
// agent_identities.id is a uuid column — a malformed id otherwise leaks
// Postgres error 22P02 to the caller as a 500. Return a clean 404 instead.
if (!isUuid(id)) return error(res, 404, 'not_found', 'agent not found');
const [a] =
await _sql`select id, name, description, avatar_id, meta, wallet_address from agent_identities where id = ${id} and deleted_at is null limit 1`;
if (!a) return error(res, 404, 'not_found', 'agent not found');
const origin = _env.APP_ORIGIN;
const image = a.meta?.image_url || `${origin}/api/agents/${a.id}/og`;
// `.glb`-terminating proxy URL: marketplaces and glTF viewers that key off
// the file extension (not the Content-Type) need the trailing `.glb`.
const animation = a.avatar_id ? `${origin}/api/avatars/${a.avatar_id}/model.glb` : null;
const symbol =
String(a.name || 'AGENT')
.toUpperCase()
.replace(/[^A-Z0-9]/g, '')
.slice(0, 10) || 'AGENT';
return json(
res,
200,
{
name: a.name,
symbol,
description:
a.description ||
`${a.name} is a 3D AI agent on three.ws with onchain identity and signed action history.`,
image,
animation_url: animation,
external_url: `${origin}/agent/${a.id}`,
attributes: [
{ trait_type: 'platform', value: 'three.ws' },
{ trait_type: 'agent_id', value: a.id },
...(a.wallet_address ? [{ trait_type: 'owner', value: a.wallet_address }] : []),
],
properties: {
category: 'video',
files: [
...(animation ? [{ uri: animation, type: 'model/gltf-binary' }] : []),
{ uri: image, type: 'image/png' },
],
},
},
{ 'cache-control': 'public, max-age=300', 'access-control-allow-origin': '*' },
);
}