Skip to content

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.

fix(pump): tell the trade tape when PumpPortal refuses the live subscription

nirholas9ad6c894e198
diff --git a/api/_lib/pumpfun-ws-feed.js b/api/_lib/pumpfun-ws-feed.js
index 49465b95d..e549b129f 100644
--- a/api/_lib/pumpfun-ws-feed.js
+++ b/api/_lib/pumpfun-ws-feed.js
@@ -5,7 +5,7 @@
import WebSocket from 'ws';
import { solPriceUsd as sharedSolPriceUsd } from './sol-price.js';
-import { pumpPortalWsUrl, handlePumpPortalAck } from './pumpportal.js';
+import { pumpPortalWsUrl, handlePumpPortalAck, isPumpPortalRefusal } from './pumpportal.js';
const RECONNECT_DELAY_MS = 2_000;
const MAX_RECONNECTS = 5;
@@ -86,9 +86,14 @@ async function fetchMeta(uri) {
* classes to subscribe to. `trades` requires `mints` (PumpPortal's
* subscribeTokenTrade is per-mint; there is no firehose for all trades).
* @param {string[]} [opts.mints=[]] — token mints to stream buy/sell trades for.
+ * @param {(notice: { code: string, message: string, detail: string }) => void} [opts.onNotice]
+ * called at most once per connection when the upstream refuses a
+ * subscription (PumpPortal gates per-token trades behind a funded API key).
+ * Live surfaces use it to tell their own viewers the stream is degraded
+ * rather than holding open a socket that will never deliver an event.
* @returns {Function} stop
*/
-export function connectPumpFunFeed({ onEvent, signal, kind = 'all', mints = [] }) {
+export function connectPumpFunFeed({ onEvent, signal, kind = 'all', mints = [], onNotice }) {
let active = true;
let ws = null;
let reconnects = 0;
@@ -98,6 +103,21 @@ export function connectPumpFunFeed({ onEvent, signal, kind = 'all', mints = [] }
const wantsTrades = (kind === 'all' || kind === 'trades') && tradeMints.length > 0;
const wantsMints = kind === 'all' || kind === 'mint';
+ // One notice per connection: a refusal is a standing condition of the upstream
+ // credential, so repeating it on every reconnect would spam the consumer's own
+ // clients with a fact they already have.
+ let _noticed = false;
+ function notifyRefused(text) {
+ if (_noticed || typeof onNotice !== 'function') return;
+ _noticed = true;
+ const detail = process.env.PUMPPORTAL_API_KEY
+ ? 'PUMPPORTAL_API_KEY is set but the upstream refused it (check the key and its SOL balance).'
+ : 'PUMPPORTAL_API_KEY is not configured on this deployment.';
+ try {
+ onNotice({ code: 'upstream_subscription_refused', message: text, detail });
+ } catch { /* a consumer's notice handler must never break the feed */ }
+ }
+
// Per-connection mint dedupe, shared between the WS and the REST fallback so a
// launch surfaced by one source is never re-emitted by the other.
const _seenMints = new Set();
@@ -200,6 +220,7 @@ export function connectPumpFunFeed({ onEvent, signal, kind = 'all', mints = [] }
if (!active) return;
let msg;
try { msg = JSON.parse(raw.toString()); } catch { return; }
+ if (isPumpPortalRefusal(msg)) notifyRefused(msg.message);
if (handlePumpPortalAck(msg, (line) => console.warn('[pumpportal-ws]', line))) return;
if (msg.txType === 'create' && wantsMints) {
diff --git a/api/_lib/pumpportal.js b/api/_lib/pumpportal.js
index c4154929a..d18fb097f 100644
--- a/api/_lib/pumpportal.js
+++ b/api/_lib/pumpportal.js
@@ -26,6 +26,20 @@ const REFUSAL_RE = /api key|only available|not authorized|unauthorized|exceed/i;
const REFUSAL_LOG_INTERVAL_MS = 5 * 60_000;
let _lastRefusalLogAt = 0;
+/**
+ * True when a parsed frame is a subscription refusal rather than data or a
+ * routine ack. Callers that serve a live stream use this to tell their own
+ * clients the feed is degraded, instead of holding a socket open that will
+ * never deliver an event.
+ *
+ * @param {object} msg parsed frame
+ * @returns {boolean}
+ */
+export function isPumpPortalRefusal(msg) {
+ const text = typeof msg?.message === 'string' ? msg.message : null;
+ return text != null && REFUSAL_RE.test(text);
+}
+
/**
* Handle a parsed PumpPortal frame if it is an ack/notice (`{ message }`).
* Returns true when the frame was an ack (caller should skip it), false when
@@ -39,7 +53,7 @@ let _lastRefusalLogAt = 0;
export function handlePumpPortalAck(msg, warn = console.warn) {
const text = typeof msg?.message === 'string' ? msg.message : null;
if (text == null) return false;
- if (REFUSAL_RE.test(text)) {
+ if (isPumpPortalRefusal(msg)) {
const now = Date.now();
if (now - _lastRefusalLogAt > REFUSAL_LOG_INTERVAL_MS) {
_lastRefusalLogAt = now;
diff --git a/api/pump/launch-og.js b/api/pump/launch-og.js
index 509694d8d..4ddfdf851 100644
--- a/api/pump/launch-og.js
+++ b/api/pump/launch-og.js
@@ -313,8 +313,11 @@ export default wrap(async (req, res) => {
let data;
try {
data = await buildCardData(mint);
- } catch {
- // Hard DB failure — serve a branded fallback card rather than 500.
+ } catch (err) {
+ // Hard DB failure: serve a branded fallback card rather than 500. Log it,
+ // because swallowing it silently made a real outage indistinguishable from
+ // a coin we simply have no data on: both render the same blank card.
+ console.warn('[launch-og] card data failed for %s: %s', mint, err?.message || err);
data = { name: '', symbol: '', logoBase64: null, qualityScore: null, category: '', isThreeWsLaunch: false, intel: null, outcome: null, liveMcap: null };
}
diff --git a/api/pump/smart-money.js b/api/pump/smart-money.js
index cb46a5113..94a630344 100644
--- a/api/pump/smart-money.js
+++ b/api/pump/smart-money.js
@@ -122,7 +122,10 @@ async function walletCard(res, wallet) {
WHERE network = ${NETWORK} AND wallet = ${wallet}
LIMIT 1
`;
- if (!rep) return json(res, 404, { error: 'not_found', message: 'no track record for this wallet yet' });
+ // Through the shared error() helper so this 404 carries the same
+ // { error, error_description } shape as every other error on this route.
+ // A client reading error_description got undefined here.
+ if (!rep) return error(res, 404, 'not_found', 'no track record for this wallet yet');
// Recent coins this wallet bought, with their outcome (graduated?) and metadata.
const recent = await sql`
diff --git a/api/pump/trades-stream.js b/api/pump/trades-stream.js
index 45e902c82..3a15edd96 100644
--- a/api/pump/trades-stream.js
+++ b/api/pump/trades-stream.js
@@ -7,14 +7,21 @@
// PumpPortal's subscribeTokenTrade is per-mint (there is no all-trades firehose),
// so a `mint` is required to receive trade events; without one we degrade to the
// public mint/graduation feed rather than emitting an empty stream.
+//
+// PumpPortal also gates subscribeTokenTrade behind an API key funded with at
+// least 0.02 SOL. When it refuses the subscription the socket stays open and
+// simply never delivers a trade, which reads to a viewer as a working-but-dead
+// tape. We forward that refusal as an SSE `notice` event so consumers can show
+// an honest degraded state instead of an empty panel and a lit "live" lamp.
-import { cors, method, rateLimited } from '../_lib/http.js';
+import { cors, method, error, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { connectPumpFunFeed } from '../_lib/pumpfun-ws-feed.js';
const MAX_DURATION_MS = 90_000;
const PING_INTERVAL_MS = 15_000;
const MAX_MINTS = 20;
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
export default async function handleTradesStream(req, res) {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
@@ -26,11 +33,18 @@ export default async function handleTradesStream(req, res) {
if (!rl.success) return rateLimited(res, rl);
const url = new URL(req.url, `http://${req.headers.host || 'x'}`);
- const mints = (url.searchParams.get('mint') || '')
+ const requested = (url.searchParams.get('mint') || '')
.split(',')
.map((m) => m.trim())
.filter(Boolean)
.slice(0, MAX_MINTS);
+ // Reject a malformed address at the boundary instead of opening a stream that
+ // subscribes upstream to a key that cannot match anything.
+ const invalid = requested.filter((m) => !BASE58_RE.test(m));
+ if (invalid.length) {
+ return error(res, 400, 'invalid_mint', `not a base58 Solana address: ${invalid[0]}`);
+ }
+ const mints = requested;
const kind = mints.length ? 'trades' : 'all';
res.writeHead(200, {
@@ -47,16 +61,19 @@ export default async function handleTradesStream(req, res) {
res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
};
+ // `open` first: it describes the stream a client is about to read, so it has
+ // to precede anything the feed itself can emit (a refusal notice included).
+ send('open', { kind, mints, source: 'pumpportal' });
+
const abort = new AbortController();
const stop = connectPumpFunFeed({
kind,
mints,
signal: abort.signal,
onEvent: ({ kind: evKind, data }) => send(evKind, data),
+ onNotice: (notice) => send('notice', { ...notice, kind, mints }),
});
- send('open', { kind, mints, source: 'pumpportal' });
-
const ping = setInterval(() => send('ping', { t: Date.now() }), PING_INTERVAL_MS);
const teardown = () => {
diff --git a/docs/terminal.md b/docs/terminal.md
index 410277fc2..2b4577f06 100644
--- a/docs/terminal.md
+++ b/docs/terminal.md
@@ -81,6 +81,28 @@ es.addEventListener('graduation', (e) => console.log('graduated', JSON.parse(e.d
// The stream self-closes about every 90s; reconnect on 'close'.
```
+Pass `?mint=<MINT>` (up to 20, comma separated) to receive that token's `trade`
+events instead of the global firehose. A mint that is not a base58 Solana
+address is rejected with a `400 invalid_mint` before the stream opens.
+
+Per-token trades come from PumpPortal's `subscribeTokenTrade`, which it gates
+behind an API key funded with at least 0.02 SOL (`PUMPPORTAL_API_KEY`). When
+that subscription is refused the socket stays open but no trade can ever
+arrive, so the server forwards the refusal as a `notice` event. Listen for it
+and show a degraded state rather than an idle-looking live tape:
+
+```javascript
+const trades = new EventSource('https://three.ws/api/pump/trades-stream?mint=<MINT>');
+trades.addEventListener('trade', (e) => console.log('trade', JSON.parse(e.data)));
+trades.addEventListener('notice', (e) => {
+ // { code: 'upstream_subscription_refused', message, detail, kind, mints }
+ console.warn('live trades unavailable', JSON.parse(e.data));
+});
+```
+
+Settled trades for graduated coins are unaffected: they come from
+`/api/pump/dex-trades`, which needs no PumpPortal credential.
+
## States and limits
- **Auth.** The page runs read-only signed out. Trading, `/api/sniper/history`, and the holdings and trade endpoints require a session or bearer token plus ownership of the agent. Signed out, the ticket links to `/login?next=%2Fterminal`.
diff --git a/prompts/swarm-100/api-pump-03.md b/prompts/swarm-100/api-pump-03.md
deleted file mode 100644
index 71db10bb9..000000000
--- a/prompts/swarm-100/api-pump-03.md
+++ /dev/null
@@ -1,110 +0,0 @@
-# API audit: api/pump batch 03 (10 files)
-
-How to run: paste this file's repo path into a fresh Claude Code chat in this
-repository and say "run this work order". This file is fully self-contained:
-it depends on no other prompt file anywhere. If neighboring files in
-prompts/swarm-100/ are gone, that work is done; if present, ignore them.
-Every claim below rots; step 0 re-measures, and what you measure wins.
-
-## Operating clause (binding)
-
-- Read CLAUDE.md first. Its rules override everything, including this file.
-- Finish 100% in this session. Never end the turn with a question, an option
- list, or an unexecuted plan. A judgment call goes in one line of the final
- report; it never becomes a question that halts work.
-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real
- funds or any irreversible on-chain write, git push or a production deploy,
- committing content that references a crypto project other than $THREE, and
- destroying unrecoverable data.
-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no
- commented-out code. Real APIs and real integrations only.
-- The em-dash and en-dash characters are banned in everything you write.
-- Concurrent agents share this worktree: stage explicit paths only (never a
- bare add-everything), and commit finished work promptly.
-- Before committing, run: npm run check:rules -- --paths <files you touched>.
- It must exit 0.
-
-## Step 0: re-derive the current state
-
-1. Confirm each file below still exists; deleted ones are done, skip them.
-2. For each, decide routability: grep its path in vercel.json and read how
- server/index.mjs maps filesystem handlers. Routed files get an endpoint
- audit; internal modules get a code and test audit.
-3. Start a local server for endpoint checks: node server/index.mjs with .env
- loaded, on a free PORT if 3000 is busy.
-
-## Task: audit these api files, then fix everything found
-
-Files in this batch:
-
-- api/pump/launch-og.js
-- api/pump/launch-prep.js
-- api/pump/launch-studio.js
-- api/pump/price-history.js
-- api/pump/quote-sdk.js
-- api/pump/safety.js
-- api/pump/search.js
-- api/pump/smart-money.js
-- api/pump/trades-stream.js
-- api/pump/trending.js
-
-For every routed handler:
-
-1. Exercise it with curl against the local server: the success path returns
- real data with the correct status; malformed input returns a 4xx JSON
- error, never a stack trace or an HTML error page; auth is enforced where
- the code intends it; CORS matches neighboring handlers.
-2. Hard-rule scan: no mock fallbacks, no fake-data arrays, no stubbed
- responses, no unfinished markers. Errors are handled at the boundary and
- internal code trusts itself.
-3. Do not spend funds or sign anything on-chain while probing. Payment and
- trading handlers get their validation and error paths exercised, never a
- live settlement.
-
-For every internal (non-routed) module:
-
-4. Something must import it; if nothing does, delete it as dead code (verify
- with a repo-wide grep first).
-5. Its main path and one failure path must be covered in tests/; add the
- missing test if not.
-
-## Definition of done
-
-- [ ] Every listed file has recorded evidence: a curl transcript for routed
- handlers, a passing test or a deletion for internal modules.
-- [ ] Zero hard-rule violations remain in these files.
-- [ ] vitest run passes; npm run check:rules -- --paths <touched files>
- exits 0.
-
-## Never blocked
-
-| Blocker | Resolution (act, do not ask) |
-|---|---|
-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |
-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |
-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |
-| Playwright browser missing | npx playwright install chromium |
-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |
-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |
-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |
-
-## Close out (required)
-
-1. Verify every Definition of done line with the actual command output in
- front of you. Never claim a line you did not verify.
-2. Commit with explicit paths and a subject that describes the diff (house
- style: type(scope): what changed and why a reader cares).
-3. Delete this prompt file in that same commit:
-
- git rm prompts/swarm-100/api-pump-03.md
-
- The shrinking directory is this campaign's only progress ledger; there is
- no progress log to update.
-4. Final report: what step 0 measured, what changed (file list), evidence per
- Definition of done line, and any one-line judgment calls. No trailing
- questions, no unexecuted plans.
-
-If a line genuinely cannot pass inside this session (an external party must
-respond, or an owner-gated action is the final step), finish everything else,
-leave this file in place, and state exactly which line remains and who owns
-it. Never delete this file on a partial.
diff --git a/public/changelog.json b/public/changelog.json
index 857f8e4f5..08a6e63f4 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-15T17:01:09.266Z",
+ "generated_at": "2026-08-15T17:03:10.552Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
diff --git a/public/features.json b/public/features.json
index 2cb823747..ac96e7019 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-15T17:01:09.222Z",
+ "generated_at": "2026-08-15T17:03:10.529Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/trades-tape.js b/src/trades-tape.js
index 39acd751a..20ddc4d25 100644
--- a/src/trades-tape.js
+++ b/src/trades-tape.js
@@ -88,10 +88,16 @@ export function mountTradeTape(host, opts = {}) {
let destroyed = false;
let sse = null;
let ageTimer = null;
+ // Set when the server tells us the upstream refused the live trade
+ // subscription. The seeded dex rows stay valid, so we keep them and only
+ // correct the claim that the tape is streaming.
+ let streamDegraded = false;
function render() {
if (!rows.length) {
- rowsEl.innerHTML = '<div class="tp-msg">No recent trades on this venue.</div>';
+ rowsEl.innerHTML = streamDegraded
+ ? '<div class="tp-msg">Live trades are unavailable for this coin right now. Showing settled trades only.</div>'
+ : '<div class="tp-msg">No recent trades on this venue.</div>';
return;
}
rowsEl.innerHTML = rows.map(rowHtml).join('');
@@ -132,9 +138,22 @@ export function mountTradeTape(host, opts = {}) {
if (destroyed || !d || d.mint !== mint) return;
if (add(d, { prepend: true })) render();
},
+ // The socket is up but the upstream refused the trade subscription,
+ // so no trade will ever arrive on it. Say so instead of showing a
+ // lit "live" lamp above a tape that can only ever stay still.
+ notice: () => {
+ if (destroyed) return;
+ streamDegraded = true;
+ liveEl.dataset.state = 'off';
+ liveEl.title = 'Live trade stream unavailable (settled trades only)';
+ render();
+ },
close: () => {},
},
- onState: (state) => { liveEl.dataset.state = state === 'live' ? 'on' : 'off'; },
+ onState: (state) => {
+ if (streamDegraded) return;
+ liveEl.dataset.state = state === 'live' ? 'on' : 'off';
+ },
});
sse.start();
}
diff --git a/tests/pump-trades-stream-handler.test.js b/tests/pump-trades-stream-handler.test.js
new file mode 100644
index 000000000..33bf6fb8a
--- /dev/null
+++ b/tests/pump-trades-stream-handler.test.js
@@ -0,0 +1,114 @@
+// Boundary tests for GET /api/pump/trades-stream (api/pump/trades-stream.js).
+//
+// Covers the two paths the live tape depends on:
+// - a malformed mint is rejected with a 4xx JSON error before any upstream
+// socket is opened (it can never match a trade, so opening one is waste)
+// - an upstream subscription refusal reaches the browser as an SSE `notice`
+// event, so a viewer is never shown a lit "live" lamp over a dead tape
+//
+// connectPumpFunFeed is stubbed so the test drives the handler's own contract
+// and never touches PumpPortal.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const feed = vi.hoisted(() => ({ calls: [], stop: vi.fn() }));
+
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: { mcpIp: vi.fn(async () => ({ success: true })) },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+vi.mock('../api/_lib/pumpfun-ws-feed.js', () => ({
+ connectPumpFunFeed: vi.fn((opts) => {
+ feed.calls.push(opts);
+ return feed.stop;
+ }),
+}));
+
+const { default: handler } = await import('../api/pump/trades-stream.js');
+
+const MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+function mockReq(search = '') {
+ const listeners = {};
+ return {
+ method: 'GET',
+ url: `/api/pump/trades-stream${search}`,
+ headers: { host: 'localhost' },
+ on: (ev, cb) => { listeners[ev] = cb; },
+ _listeners: listeners,
+ };
+}
+
+function mockRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ chunks: [],
+ ended: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ getHeader(k) { return this.headers[k.toLowerCase()]; },
+ writeHead(code, hdrs) { this.statusCode = code; Object.assign(this.headers, hdrs || {}); return this; },
+ write(chunk) { this.chunks.push(String(chunk)); return true; },
+ end(chunk) { if (chunk) this.chunks.push(String(chunk)); this.ended = true; },
+ get body() { return this.chunks.join(''); },
+ };
+}
+
+describe('GET /api/pump/trades-stream', () => {
+ beforeEach(() => { feed.calls.length = 0; });
+
+ it('rejects a malformed mint with a 400 and opens no upstream feed', async () => {
+ const res = mockRes();
+ await handler(mockReq('?mint=not-a-mint'), res);
+ expect(res.statusCode).toBe(400);
+ const body = JSON.parse(res.body);
+ expect(body.error).toBe('invalid_mint');
+ expect(body.error_description).toContain('not-a-mint');
+ expect(feed.calls).toHaveLength(0);
+ });
+
+ it('rejects the batch when any mint in a comma list is malformed', async () => {
+ const res = mockRes();
+ await handler(mockReq(`?mint=${MINT},bogus`), res);
+ expect(res.statusCode).toBe(400);
+ expect(feed.calls).toHaveLength(0);
+ });
+
+ it('streams a valid mint and forwards an upstream refusal as an SSE notice', async () => {
+ const req = mockReq(`?mint=${MINT}`);
+ const res = mockRes();
+ await handler(req, res);
+
+ expect(res.statusCode).toBe(200);
+ expect(res.headers['Content-Type']).toContain('text/event-stream');
+ expect(res.body).toContain('event: open');
+ expect(feed.calls).toHaveLength(1);
+ expect(feed.calls[0].kind).toBe('trades');
+ expect(feed.calls[0].mints).toEqual([MINT]);
+
+ feed.calls[0].onNotice({
+ code: 'upstream_subscription_refused',
+ message: 'only available when connecting with an API key',
+ detail: 'PUMPPORTAL_API_KEY is not configured on this deployment.',
+ });
+
+ const notice = res.body.split('\n\n').find((f) => f.startsWith('event: notice'));
+ expect(notice).toBeTruthy();
+ const payload = JSON.parse(notice.split('data: ')[1]);
+ expect(payload.code).toBe('upstream_subscription_refused');
+ expect(payload.mints).toEqual([MINT]);
+
+ req._listeners.close?.();
+ expect(feed.stop).toHaveBeenCalled();
+ });
+
+ it('falls back to the global feed when no mint is given', async () => {
+ const req = mockReq();
+ const res = mockRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(200);
+ expect(feed.calls[0].kind).toBe('all');
+ expect(feed.calls[0].mints).toEqual([]);
+ req._listeners.close?.();
+ });
+});
diff --git a/tests/pumpfun-ws-trades.test.js b/tests/pumpfun-ws-trades.test.js
index 08ae0fbae..f865e2af4 100644
--- a/tests/pumpfun-ws-trades.test.js
+++ b/tests/pumpfun-ws-trades.test.js
@@ -5,6 +5,7 @@
// - buy/sell messages emit normalized { kind:'trade' } events
// - a tracked mint's migration still surfaces as a graduation
// - no trade subscription is sent without mints
+// - an upstream subscription refusal reaches the caller via onNotice
import { describe, it, expect, vi, beforeEach } from 'vitest';
@@ -76,6 +77,40 @@ describe('connectPumpFunFeed — trades', () => {
stop();
});
+ it('reports an upstream subscription refusal through onNotice', async () => {
+ const notices = [];
+ const stop = connectPumpFunFeed({
+ kind: 'trades', mints: ['MINT1'], onEvent: () => {}, onNotice: (n) => notices.push(n),
+ });
+ const ws = FakeWS.instances[0];
+ ws.emit('open');
+ const refusal = "'subscribeTokenTrade' and 'subscribeAccountTrade' methods are only available when connecting with an API key funded with at least 0.02 SOL.";
+ ws.emit('message', JSON.stringify({ message: refusal }));
+ await flush();
+ expect(notices).toHaveLength(1);
+ expect(notices[0].code).toBe('upstream_subscription_refused');
+ expect(notices[0].message).toBe(refusal);
+ expect(notices[0].detail).toContain('PUMPPORTAL_API_KEY');
+ // A standing condition, not a per-message event: repeats stay silent.
+ ws.emit('message', JSON.stringify({ message: refusal }));
+ await flush();
+ expect(notices).toHaveLength(1);
+ stop();
+ });
+
+ it('does not raise a notice for a routine ack', async () => {
+ const notices = [];
+ const stop = connectPumpFunFeed({
+ kind: 'trades', mints: ['MINT1'], onEvent: () => {}, onNotice: (n) => notices.push(n),
+ });
+ const ws = FakeWS.instances[0];
+ ws.emit('open');
+ ws.emit('message', JSON.stringify({ message: 'Successfully subscribed to token trades.' }));
+ await flush();
+ expect(notices).toHaveLength(0);
+ stop();
+ });
+
it('ignores trades for non-tracked mints (no firehose leakage)', async () => {
const events = [];
const stop = connectPumpFunFeed({ kind: 'trades', mints: ['MINT1'], onEvent: (e) => events.push(e) });