-
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathpumpfun-signals.test.js
More file actions
210 lines (188 loc) · 7.79 KB
/
Copy pathpumpfun-signals.test.js
File metadata and controls
210 lines (188 loc) · 7.79 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
import { describe, it, expect, beforeEach, vi } from 'vitest';
// ── hoisted mocks ─────────────────────────────────────────────────────────────
// vi.mock factories are hoisted above imports, so the doubles they reference must
// be created with vi.hoisted().
const h = vi.hoisted(() => ({
recentClaims: vi.fn(),
graduations: vi.fn(),
getClaims: vi.fn(),
getWhales: vi.fn(),
getMints: vi.fn(),
getSignals: vi.fn(),
sql: vi.fn(),
state: { botEnabled: true },
}));
vi.mock('../api/_lib/db.js', () => ({ sql: (...a) => h.sql(...a) }));
vi.mock('../api/_lib/pumpfun-mcp.js', () => ({
pumpfunMcp: {
recentClaims: (...a) => h.recentClaims(...a),
graduations: (...a) => h.graduations(...a),
},
pumpfunBotEnabled: () => h.state.botEnabled,
}));
vi.mock('../api/_lib/channel-feed-sources.js', () => ({
getClaims: (...a) => h.getClaims(...a),
getWhales: (...a) => h.getWhales(...a),
getMints: (...a) => h.getMints(...a),
getSignals: (...a) => h.getSignals(...a),
}));
vi.mock('../api/_lib/env.js', () => ({
env: { APP_ORIGIN: 'http://test', ISSUER: 'http://test', MCP_RESOURCE: 'http://test' },
}));
const { default: dispatcher } = await import('../api/cron/[name].js');
const handler = (req, res) =>
dispatcher({ ...req, query: { ...(req.query || {}), name: 'pumpfun-signals' } }, res);
// ── faithful in-memory Postgres double ────────────────────────────────────────
// The previous test returned [{id:1}] for every sql call, which masked the
// tx_signature-unique bug. This double enforces the real unique(tx_signature,
// kind) constraint and persists cursor state across calls so cursor behaviour is
// actually exercised.
let cursorState; // Map<source, last_seen_ms>
let insertedKeys; // Set<"tx:kind">
let insertedRows; // [{ wallet, agent_asset, kind, weight, tx_signature }]
let cursorWrites; // [{ source, last_seen_ms, last_signature }]
let linkedRows; // rows returned by the user_wallets → agent_identities lookup
function installSqlRouter() {
h.sql.mockImplementation((strings, ...vals) => {
const q = Array.isArray(strings) ? strings.join(' ? ') : String(strings);
if (/from pumpfun_signals_cursor/.test(q)) {
return Promise.resolve(
[...cursorState.entries()].map(([source, last_seen_ms]) => ({ source, last_seen_ms })),
);
}
if (/into pumpfun_signals_cursor/.test(q)) {
const [source, ms, sig] = vals;
cursorState.set(source, Math.max(cursorState.get(source) ?? 0, Number(ms) || 0));
cursorWrites.push({ source, last_seen_ms: Number(ms) || 0, last_signature: sig ?? null });
return Promise.resolve([]);
}
if (/from user_wallets/.test(q)) {
return Promise.resolve(linkedRows);
}
if (/into pumpfun_signals\b/.test(q)) {
// values: (wallet, agent_asset, kind, weight, payload, tx_signature)
const [wallet, agent_asset, kind, weight, , tx_signature] = vals;
const key = `${tx_signature}:${kind}`;
if (insertedKeys.has(key)) return Promise.resolve([]); // unique(tx_signature, kind)
insertedKeys.add(key);
insertedRows.push({ wallet, agent_asset, kind, weight, tx_signature });
return Promise.resolve([{ id: insertedKeys.size }]);
}
return Promise.resolve([]);
});
}
function mockRes() {
return {
statusCode: 200,
headers: {},
body: null,
setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
getHeader(k) { return this.headers[k.toLowerCase()]; },
end(b) { this.body = b; },
};
}
const SECRET = 'topsecret';
async function run() {
process.env.CRON_SECRET = SECRET;
const req = { headers: { authorization: `Bearer ${SECRET}` }, method: 'POST' };
const res = mockRes();
await handler(req, res);
return { res, body: JSON.parse(res.body) };
}
describe('pumpfun-signals cron', () => {
beforeEach(() => {
cursorState = new Map();
insertedKeys = new Set();
insertedRows = [];
cursorWrites = [];
linkedRows = [];
h.state.botEnabled = true;
h.recentClaims.mockReset().mockResolvedValue({ ok: true, data: [] });
h.graduations.mockReset().mockResolvedValue({ ok: true, data: [] });
h.getClaims.mockReset().mockResolvedValue([]);
h.getWhales.mockReset().mockResolvedValue([]);
h.getMints.mockReset().mockResolvedValue([]);
h.getSignals.mockReset().mockResolvedValue([]);
installSqlRouter();
delete process.env.CRON_SECRET;
});
it('writes typed signals only for linked wallets, one row per (tx, kind)', async () => {
h.recentClaims.mockResolvedValue({
ok: true,
data: [
{
tx_signature: 'sig1', signature: 'sig1', timestamp: 1000,
claimer: 'WALLET_A', first_time_claim: true, tier: 'influencer',
github_account_age_days: 5,
},
{ tx_signature: 'sig2', signature: 'sig2', timestamp: 1001, claimer: 'WALLET_UNKNOWN', first_time_claim: true },
],
});
linkedRows = [{ address: 'WALLET_A', agent_asset: 'AGENT_A' }];
const { body } = await run();
expect(body.sources.claims).toBe(2);
expect(body.skipped_unlinked).toBeGreaterThanOrEqual(1); // WALLET_UNKNOWN
// WALLET_A: first_claim + influencer + new_account — three DISTINCT rows
// for one tx, which the old single-column tx_signature unique forbade.
expect(body.inserted).toBe(3);
expect(insertedRows.map((r) => r.kind).sort()).toEqual(['first_claim', 'influencer', 'new_account']);
expect(insertedRows.every((r) => r.agent_asset === 'AGENT_A')).toBe(true);
});
it('cursor skips already-seen events on the next run', async () => {
h.recentClaims.mockResolvedValue({
ok: true,
data: [
{ tx_signature: 'c1', signature: 'c1', timestamp: 100, claimer: 'W', first_time_claim: true },
{ tx_signature: 'c2', signature: 'c2', timestamp: 200, claimer: 'W', first_time_claim: true },
],
});
linkedRows = [{ address: 'W', agent_asset: 'A' }];
const first = await run();
expect(first.body.inserted).toBe(2);
expect(first.body.skipped_by_cursor).toBe(0);
// cursor advanced to the newest event (200s → 200000ms) for the claims lane
expect(cursorState.get('claims')).toBe(200000);
const second = await run();
// Nothing new persists: c1 is strictly older than the cursor (skipped), c2
// is at the boundary and collides on (tx, kind).
expect(second.body.inserted).toBe(0);
expect(second.body.skipped_by_cursor).toBeGreaterThanOrEqual(1);
});
it('emits whale_buy and launch signals from the redis lanes', async () => {
h.getWhales.mockResolvedValue([
{ signature: 'w1', timestamp: 10, mint: 'M1', amount_sol: 12.5, buyer: 'WB' },
]);
h.getMints.mockResolvedValue([
{ signature: 'm1', timestamp: 11, mint: 'M2', name: 'Tok', symbol: 'TK', creator: 'WC' },
]);
linkedRows = [
{ address: 'WB', agent_asset: 'AB' },
{ address: 'WC', agent_asset: 'AC' },
];
const { body } = await run();
expect(body.inserted).toBe(2);
const byKind = Object.fromEntries(insertedRows.map((r) => [r.kind, r]));
expect(byKind.whale_buy?.agent_asset).toBe('AB');
expect(byKind.launch?.agent_asset).toBe('AC');
});
it('runs without the upstream bot — graduations still emit, claims are not fetched', async () => {
h.state.botEnabled = false;
h.graduations.mockResolvedValue({
ok: true,
data: [{ tx_signature: 'g1', signature: 'g1', timestamp: 7, mint: 'GM', symbol: 'GS', name: 'GN', creator: 'GW' }],
});
linkedRows = [{ address: 'GW', agent_asset: 'GA' }];
const { body } = await run();
expect(h.recentClaims).not.toHaveBeenCalled();
expect(body.bot).toBe(false);
expect(body.inserted).toBe(1);
expect(insertedRows[0]).toMatchObject({ kind: 'graduation', agent_asset: 'GA' });
});
it('rejects without cron secret when CRON_SECRET set', async () => {
process.env.CRON_SECRET = SECRET;
const req = { headers: {}, method: 'POST' };
const res = mockRes();
await handler(req, res);
expect(res.statusCode).toBe(401);
});
});