nansen-cli 1.26.0 → 1.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/package.json +1 -1
- package/skills/nansen-alerts-webhook-listener/SKILL.md +386 -0
- package/skills/nansen-trading/SKILL.md +12 -1
- package/src/api.js +82 -14
- package/src/cli.js +56 -40
- package/src/index.js +1 -1
- package/src/schema.json +39 -6
- package/src/telemetry.js +8 -6
- package/src/trade-validation.js +58 -0
- package/src/trading.js +55 -93
- package/src/transfer.js +13 -10
- package/src/wallet.js +66 -117
- package/src/x402-svm.js +3 -23
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.27.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [#403](https://github.com/nansen-ai/nansen-cli/pull/403) [`fe53dbe`](https://github.com/nansen-ai/nansen-cli/commit/fe53dbe8cf743b970e145e7ad7a00470f16f28df) Thanks [@marius-reed](https://github.com/marius-reed)! - Add prediction market filtering (order_by, volume/liquidity/OI/trader/price/date filters, neg_risk, tags) and address-summary endpoint
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- [#402](https://github.com/nansen-ai/nansen-cli/pull/402) [`cfd94ce`](https://github.com/nansen-ai/nansen-cli/commit/cfd94ce1e1880e36fb0c97d0ecfe37e614898006) Thanks [@TimNooren](https://github.com/TimNooren)! - Enforce USDC or native token on one side of every swap
|
|
12
|
+
|
|
13
|
+
## 1.26.1
|
|
14
|
+
|
|
15
|
+
### Patch Changes
|
|
16
|
+
|
|
17
|
+
- [#392](https://github.com/nansen-ai/nansen-cli/pull/392) [`025993d`](https://github.com/nansen-ai/nansen-cli/commit/025993df798ddb406340511e0dada1f9a962be56) Thanks [@TimNooren](https://github.com/TimNooren)! - Add gas balance validation: rejects trades when the wallet lacks sufficient native token for gas fees.
|
|
18
|
+
|
|
3
19
|
## 1.26.0
|
|
4
20
|
|
|
5
21
|
### Minor Changes
|
package/package.json
CHANGED
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: nansen-alerts-webhook-listener
|
|
3
|
+
description: Set up a local webhook server to receive Nansen smart alerts in real-time with HMAC signature verification and public tunneling. Use when a user wants to listen for alerts on their local machine.
|
|
4
|
+
metadata:
|
|
5
|
+
openclaw:
|
|
6
|
+
requires:
|
|
7
|
+
env:
|
|
8
|
+
- NANSEN_API_KEY
|
|
9
|
+
bins:
|
|
10
|
+
- nansen
|
|
11
|
+
- node
|
|
12
|
+
primaryEnv: NANSEN_API_KEY
|
|
13
|
+
install:
|
|
14
|
+
- kind: node
|
|
15
|
+
package: nansen-cli
|
|
16
|
+
bins: [nansen]
|
|
17
|
+
allowed-tools: Bash(nansen:*), Bash(node:*), Bash(npx:*), Bash(ngrok:*), Write
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
# Alert Webhook Listener
|
|
21
|
+
|
|
22
|
+
Set up a local HTTP server to receive Nansen smart alert webhook payloads in real-time.
|
|
23
|
+
|
|
24
|
+
## How It Works
|
|
25
|
+
|
|
26
|
+
Nansen smart alerts support a **webhook** channel type. When an alert fires, Nansen sends an HTTP POST with a JSON payload to your webhook URL. This skill sets up:
|
|
27
|
+
|
|
28
|
+
1. A local HTTP server (Node.js, zero external dependencies) that receives and displays alert payloads
|
|
29
|
+
2. HMAC-SHA256 signature verification so only authentic Nansen payloads are accepted
|
|
30
|
+
3. A public tunnel so Nansen's servers can reach your local machine
|
|
31
|
+
|
|
32
|
+
**This skill does NOT create or modify alerts.** It sets up the listener infrastructure and then provides a summary of what the user needs to do to start receiving alerts.
|
|
33
|
+
|
|
34
|
+
**OpenClaw users:** If OpenClaw is running locally on the same machine, the webhook server can forward verified alert payloads to OpenClaw's Gateway (`/hooks/agent`), triggering an agent turn for each alert. Set the `OPENCLAW_GATEWAY_URL` env var to enable this. See the **OpenClaw Integration** section below.
|
|
35
|
+
|
|
36
|
+
## Security Warning
|
|
37
|
+
|
|
38
|
+
**Before proceeding, inform the user:**
|
|
39
|
+
|
|
40
|
+
> This skill starts an HTTP server on your machine and exposes it to the internet via a tunnel (ngrok or localtunnel). While the server only binds to localhost (`127.0.0.1`) — meaning no one on your local network can access it directly — the tunnel creates a public URL that **anyone on the internet** can send requests to.
|
|
41
|
+
>
|
|
42
|
+
> **Mitigations in place:**
|
|
43
|
+
> - HMAC-SHA256 signature verification rejects all requests not signed by Nansen
|
|
44
|
+
> - 1 MB body size limit prevents memory abuse
|
|
45
|
+
> - Only `POST /webhook` and `GET /health` are accepted; everything else returns 404
|
|
46
|
+
>
|
|
47
|
+
> **You should be aware that:**
|
|
48
|
+
> - The tunnel URL is publicly discoverable (ngrok URLs can be enumerated)
|
|
49
|
+
> - Unsigned requests still reach your machine — they're rejected, but the connection is made
|
|
50
|
+
> - Stop the tunnel when you're done to close the public endpoint
|
|
51
|
+
|
|
52
|
+
Wait for the user to confirm they want to proceed before continuing.
|
|
53
|
+
|
|
54
|
+
## Execution Plan
|
|
55
|
+
|
|
56
|
+
Follow these steps **in order**. Do not skip signature verification — it is mandatory.
|
|
57
|
+
|
|
58
|
+
### Step 0: Choose a tunnel provider
|
|
59
|
+
|
|
60
|
+
Before starting, ask the user which tunnel provider they want to use:
|
|
61
|
+
|
|
62
|
+
| | **ngrok** (recommended) | **localtunnel** |
|
|
63
|
+
|---|---|---|
|
|
64
|
+
| Stability | Stable — persistent connections with keepalive | Flaky — free relay drops idle connections without warning, tunnels die randomly |
|
|
65
|
+
| Install | `brew install ngrok` + free account at ngrok.com | Zero install (`npx localtunnel`) |
|
|
66
|
+
| HTTPS | Yes | Yes |
|
|
67
|
+
| Auth required | Yes (free authtoken from ngrok.com) | No |
|
|
68
|
+
|
|
69
|
+
**Recommend ngrok.** localtunnel is convenient but unreliable — in testing, tunnels silently exit after minutes, causing alerts to fail with "503 Tunnel Unavailable". ngrok maintains stable connections.
|
|
70
|
+
|
|
71
|
+
Check if ngrok is available:
|
|
72
|
+
```bash
|
|
73
|
+
which ngrok && ngrok version
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
If not installed, tell the user:
|
|
77
|
+
1. `brew install ngrok` (or download from ngrok.com)
|
|
78
|
+
2. Create a free account at ngrok.com and copy the authtoken
|
|
79
|
+
3. `ngrok config add-authtoken <token>`
|
|
80
|
+
|
|
81
|
+
If the user prefers localtunnel or can't install ngrok, proceed with localtunnel but warn them that the tunnel may drop and they'll need to restart it and update their alert's webhook URL.
|
|
82
|
+
|
|
83
|
+
### Step 1: Generate a webhook secret
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Store the output — you need it for both the server and the alert configuration. **Never log or echo the secret after this point.**
|
|
90
|
+
|
|
91
|
+
### Step 2: Write the webhook receiver script
|
|
92
|
+
|
|
93
|
+
Create `nansen-webhook-server.mjs` in the current working directory. Use **only** Node.js built-in modules (`node:http`, `node:crypto`). No `npm install` required.
|
|
94
|
+
|
|
95
|
+
**Requirements — do not deviate:**
|
|
96
|
+
|
|
97
|
+
| Requirement | Detail |
|
|
98
|
+
|---|---|
|
|
99
|
+
| Bind address | `127.0.0.1` only — **never** `0.0.0.0` |
|
|
100
|
+
| Default port | `9477` (override via `PORT` env var) |
|
|
101
|
+
| Webhook path | `POST /webhook` — reject all other method/path combos with 404 |
|
|
102
|
+
| Health check | `GET /health` → 200 `{"status":"ok"}` |
|
|
103
|
+
| Signature verification | Verify `x-nansen-signature` header using HMAC-SHA256 with timing-safe comparison. Reject 401 on mismatch. |
|
|
104
|
+
| Secret validation | Exit on startup if `WEBHOOK_SECRET` env var is missing or < 16 chars |
|
|
105
|
+
| Payload logging | Pretty-print valid JSON payloads to stdout with ISO timestamp |
|
|
106
|
+
| Request size limit | Reject bodies > 1 MB (413) to prevent memory abuse |
|
|
107
|
+
| Graceful shutdown | Handle `SIGINT` and `SIGTERM` — close server, then exit |
|
|
108
|
+
| OpenClaw forwarding | If `OPENCLAW_GATEWAY_URL` env var is set, forward verified payloads to `<url>/hooks/agent` via POST. Include `OPENCLAW_AUTH_TOKEN` as Bearer token if set. Log forward success/failure. |
|
|
109
|
+
| No dependencies | Only `node:http`, `node:https`, and `node:crypto` — nothing from npm |
|
|
110
|
+
|
|
111
|
+
**Signature verification — use timing-safe comparison:**
|
|
112
|
+
|
|
113
|
+
```javascript
|
|
114
|
+
import { createHmac, timingSafeEqual } from 'node:crypto';
|
|
115
|
+
|
|
116
|
+
function verifySignature(rawBody, signatureHeader, secret) {
|
|
117
|
+
if (!signatureHeader || !secret) return false;
|
|
118
|
+
// Nansen sends "sha256=<hex>" — strip the prefix before comparing
|
|
119
|
+
const sig = signatureHeader.startsWith('sha256=') ? signatureHeader.slice(7) : signatureHeader;
|
|
120
|
+
const expected = createHmac('sha256', secret).update(rawBody).digest('hex');
|
|
121
|
+
try {
|
|
122
|
+
return timingSafeEqual(Buffer.from(sig, 'utf8'), Buffer.from(expected, 'utf8'));
|
|
123
|
+
} catch {
|
|
124
|
+
return false; // length mismatch
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
**Full server template:**
|
|
130
|
+
|
|
131
|
+
```javascript
|
|
132
|
+
import { createServer } from 'node:http';
|
|
133
|
+
import { createHmac, timingSafeEqual } from 'node:crypto';
|
|
134
|
+
|
|
135
|
+
const PORT = parseInt(process.env.PORT || '9477', 10);
|
|
136
|
+
const SECRET = process.env.WEBHOOK_SECRET;
|
|
137
|
+
const MAX_BODY = 1_048_576; // 1 MB
|
|
138
|
+
|
|
139
|
+
// Optional: forward verified payloads to a local OpenClaw Gateway
|
|
140
|
+
const OPENCLAW_URL = process.env.OPENCLAW_GATEWAY_URL; // e.g. http://localhost:3000
|
|
141
|
+
const OPENCLAW_TOKEN = process.env.OPENCLAW_AUTH_TOKEN;
|
|
142
|
+
|
|
143
|
+
if (!SECRET || SECRET.length < 16) {
|
|
144
|
+
console.error('WEBHOOK_SECRET env var required (minimum 16 characters).');
|
|
145
|
+
console.error('Generate one: node -e "console.log(require(\'crypto\').randomBytes(32).toString(\'hex\'))"');
|
|
146
|
+
process.exit(1);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function verifySignature(rawBody, signatureHeader) {
|
|
150
|
+
if (!signatureHeader) return false;
|
|
151
|
+
// Nansen sends "sha256=<hex>" — strip the prefix before comparing
|
|
152
|
+
const sig = signatureHeader.startsWith('sha256=') ? signatureHeader.slice(7) : signatureHeader;
|
|
153
|
+
const expected = createHmac('sha256', SECRET).update(rawBody).digest('hex');
|
|
154
|
+
try {
|
|
155
|
+
return timingSafeEqual(Buffer.from(sig, 'utf8'), Buffer.from(expected, 'utf8'));
|
|
156
|
+
} catch {
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async function forwardToOpenClaw(payload) {
|
|
162
|
+
if (!OPENCLAW_URL) return;
|
|
163
|
+
const url = `${OPENCLAW_URL.replace(/\/+$/, '')}/hooks/agent`;
|
|
164
|
+
const headers = { 'Content-Type': 'application/json' };
|
|
165
|
+
if (OPENCLAW_TOKEN) headers['Authorization'] = `Bearer ${OPENCLAW_TOKEN}`;
|
|
166
|
+
try {
|
|
167
|
+
const res = await fetch(url, {
|
|
168
|
+
method: 'POST',
|
|
169
|
+
headers,
|
|
170
|
+
body: JSON.stringify(payload),
|
|
171
|
+
});
|
|
172
|
+
if (res.ok) {
|
|
173
|
+
console.log(`[${ts()}] Forwarded to OpenClaw (${res.status})`);
|
|
174
|
+
} else {
|
|
175
|
+
console.error(`[${ts()}] OpenClaw forward failed (${res.status})`);
|
|
176
|
+
}
|
|
177
|
+
} catch (err) {
|
|
178
|
+
console.error(`[${ts()}] OpenClaw forward error: ${err.message}`);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function ts() { return new Date().toISOString(); }
|
|
183
|
+
|
|
184
|
+
const server = createServer((req, res) => {
|
|
185
|
+
if (req.method === 'GET' && req.url === '/health') {
|
|
186
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
187
|
+
return res.end('{"status":"ok"}');
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
if (req.method !== 'POST' || req.url !== '/webhook') {
|
|
191
|
+
res.writeHead(404);
|
|
192
|
+
return res.end();
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
let size = 0;
|
|
196
|
+
const chunks = [];
|
|
197
|
+
|
|
198
|
+
req.on('data', (chunk) => {
|
|
199
|
+
size += chunk.length;
|
|
200
|
+
if (size > MAX_BODY) {
|
|
201
|
+
res.writeHead(413);
|
|
202
|
+
res.end('{"error":"Payload too large"}');
|
|
203
|
+
req.destroy();
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
chunks.push(chunk);
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
req.on('end', () => {
|
|
210
|
+
if (res.writableEnded) return;
|
|
211
|
+
|
|
212
|
+
const rawBody = Buffer.concat(chunks).toString('utf8');
|
|
213
|
+
const signature = req.headers['x-nansen-signature'];
|
|
214
|
+
|
|
215
|
+
if (!verifySignature(rawBody, signature)) {
|
|
216
|
+
console.error(`[${ts()}] REJECTED — invalid signature`);
|
|
217
|
+
res.writeHead(401, { 'Content-Type': 'application/json' });
|
|
218
|
+
return res.end('{"error":"Invalid signature"}');
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
let payload;
|
|
222
|
+
try {
|
|
223
|
+
payload = JSON.parse(rawBody);
|
|
224
|
+
console.log(`\n[${ts()}] Alert received:`);
|
|
225
|
+
console.log(JSON.stringify(payload, null, 2));
|
|
226
|
+
} catch {
|
|
227
|
+
console.error(`[${ts()}] WARNING — valid signature but malformed JSON`);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// Forward to OpenClaw if configured (fire-and-forget — don't block response)
|
|
231
|
+
if (payload) forwardToOpenClaw(payload);
|
|
232
|
+
|
|
233
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
234
|
+
res.end('{"received":true}');
|
|
235
|
+
});
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
for (const sig of ['SIGINT', 'SIGTERM']) {
|
|
239
|
+
process.on(sig, () => {
|
|
240
|
+
console.log(`\n${sig} — shutting down`);
|
|
241
|
+
server.close(() => process.exit(0));
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
server.listen(PORT, '127.0.0.1', () => {
|
|
246
|
+
console.log(`Webhook listener ready — http://127.0.0.1:${PORT}/webhook`);
|
|
247
|
+
if (OPENCLAW_URL) console.log(`OpenClaw forwarding → ${OPENCLAW_URL}/hooks/agent`);
|
|
248
|
+
console.log('Waiting for alerts… (Ctrl+C to stop)\n');
|
|
249
|
+
});
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
### Step 3: Start the server and tunnel
|
|
253
|
+
|
|
254
|
+
Start the server:
|
|
255
|
+
|
|
256
|
+
```bash
|
|
257
|
+
WEBHOOK_SECRET='<secret>' node nansen-webhook-server.mjs
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
Then start a public tunnel so Nansen's servers can reach it.
|
|
261
|
+
|
|
262
|
+
**ngrok (recommended):**
|
|
263
|
+
```bash
|
|
264
|
+
ngrok http 9477
|
|
265
|
+
```
|
|
266
|
+
Get the public URL from ngrok's output or its local API:
|
|
267
|
+
```bash
|
|
268
|
+
curl -s http://127.0.0.1:4040/api/tunnels | node -e "process.stdin.on('data',d=>console.log(JSON.parse(d).tunnels[0]?.public_url))"
|
|
269
|
+
```
|
|
270
|
+
The webhook URL is `https://<subdomain>.ngrok-free.dev/webhook`.
|
|
271
|
+
|
|
272
|
+
**localtunnel (fallback — unreliable):**
|
|
273
|
+
```bash
|
|
274
|
+
npx localtunnel --port 9477
|
|
275
|
+
```
|
|
276
|
+
Prints a URL like `https://xxx.loca.lt`. The webhook URL is `https://xxx.loca.lt/webhook`.
|
|
277
|
+
|
|
278
|
+
**Warning:** localtunnel's free relay silently drops connections after minutes. When this happens, all alerts fail with "503 Tunnel Unavailable" until you restart the tunnel and update the alert webhook URL. Use ngrok unless you have a reason not to.
|
|
279
|
+
|
|
280
|
+
**Note:** Tunnel URLs are ephemeral — they change every restart. For permanent setups, deploy the server to a host with a static URL.
|
|
281
|
+
|
|
282
|
+
### Step 4: Provide a next-steps summary
|
|
283
|
+
|
|
284
|
+
**Do NOT create or modify any alerts.** Instead, print a clear summary for the user explaining what was set up and what they need to do next.
|
|
285
|
+
|
|
286
|
+
The summary MUST include:
|
|
287
|
+
1. Confirmation of what was created (the server script path and the generated secret)
|
|
288
|
+
2. The commands to start the server and tunnel (with the actual secret filled in)
|
|
289
|
+
3. The exact `nansen alerts create` or `nansen alerts update` command they should run, with the `--webhook` and `--webhook-secret` flags filled in with the tunnel URL and secret — but leave the alert-specific flags (`--name`, `--type`, `--chains`, etc.) as placeholders for the user to fill in
|
|
290
|
+
4. A reminder that the server and tunnel must be running before the alert is created (Nansen validates the webhook endpoint on creation)
|
|
291
|
+
5. A note that tunnel URLs are ephemeral and will change on restart
|
|
292
|
+
|
|
293
|
+
Example summary format:
|
|
294
|
+
|
|
295
|
+
```
|
|
296
|
+
## Webhook listener ready
|
|
297
|
+
|
|
298
|
+
**Server script:** ./nansen-webhook-server.mjs
|
|
299
|
+
**Port:** 9477
|
|
300
|
+
|
|
301
|
+
### To start receiving alerts:
|
|
302
|
+
|
|
303
|
+
1. Start the server (keep this terminal open):
|
|
304
|
+
WEBHOOK_SECRET='<actual-secret>' node nansen-webhook-server.mjs
|
|
305
|
+
|
|
306
|
+
2. In a new terminal, start the tunnel:
|
|
307
|
+
ngrok http 9477 # recommended
|
|
308
|
+
# or: npx localtunnel --port 9477 (unreliable — tunnel drops silently)
|
|
309
|
+
|
|
310
|
+
3. Create an alert pointing to your webhook (fill in your alert details):
|
|
311
|
+
nansen alerts create \
|
|
312
|
+
--name '<your alert name>' \
|
|
313
|
+
--type <sm-token-flows|common-token-transfer|smart-contract-call> \
|
|
314
|
+
--chains <chains> \
|
|
315
|
+
--webhook 'https://<your-tunnel-url>/webhook' \
|
|
316
|
+
--webhook-secret '<actual-secret>' \
|
|
317
|
+
[type-specific flags...]
|
|
318
|
+
|
|
319
|
+
Or add the webhook to an existing alert:
|
|
320
|
+
nansen alerts update <alert-id> \
|
|
321
|
+
--webhook 'https://<your-tunnel-url>/webhook' \
|
|
322
|
+
--webhook-secret '<actual-secret>'
|
|
323
|
+
|
|
324
|
+
Note: The tunnel URL changes each time you restart. Update the alert
|
|
325
|
+
webhook URL if you restart the tunnel.
|
|
326
|
+
|
|
327
|
+
See `nansen alerts create --help` for full flag reference per alert type.
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
## Security Checklist
|
|
331
|
+
|
|
332
|
+
- **Always use a webhook secret** — the server refuses to start without one
|
|
333
|
+
- **Always verify signatures** — never accept unverified payloads
|
|
334
|
+
- **Bind to localhost only** — the tunnel handles public exposure; direct `0.0.0.0` binding exposes you to unauthenticated traffic
|
|
335
|
+
- **Use HTTPS** — both localtunnel and ngrok tunnel via HTTPS by default
|
|
336
|
+
- **Body size limit** — the 1 MB cap prevents memory exhaustion from oversized requests
|
|
337
|
+
- **Timing-safe comparison** — prevents timing side-channel attacks on the signature
|
|
338
|
+
|
|
339
|
+
## Troubleshooting
|
|
340
|
+
|
|
341
|
+
| Symptom | Fix |
|
|
342
|
+
|---|---|
|
|
343
|
+
| "Invalid signature" on every request | Ensure the **exact same secret** is in `WEBHOOK_SECRET` and `--webhook-secret` |
|
|
344
|
+
| "Failed to send welcome message" on alert create | Start the server and tunnel **before** creating the alert |
|
|
345
|
+
| No alerts arriving | Check `nansen alerts list --table` — is the alert enabled? Is the webhook URL correct (includes `/webhook`)? |
|
|
346
|
+
| Tunnel URL expired / tunnel died | Restart the tunnel, get the new URL, then `nansen alerts update <id> --webhook '<new-url>/webhook'`. If this keeps happening, switch from localtunnel to ngrok. |
|
|
347
|
+
| Port already in use | Set a different port: `PORT=9478 WEBHOOK_SECRET='...' node nansen-webhook-server.mjs` and update the tunnel accordingly |
|
|
348
|
+
|
|
349
|
+
## OpenClaw Integration
|
|
350
|
+
|
|
351
|
+
If the user is running OpenClaw locally on the same machine, the webhook server can forward verified alert payloads to OpenClaw's Gateway, triggering an agent turn for each alert.
|
|
352
|
+
|
|
353
|
+
**Flow:** `Nansen → ngrok → webhook server (signature check) → OpenClaw /hooks/agent`
|
|
354
|
+
|
|
355
|
+
### Additional env vars
|
|
356
|
+
|
|
357
|
+
| Var | Required | Purpose |
|
|
358
|
+
|-----|----------|---------|
|
|
359
|
+
| `OPENCLAW_GATEWAY_URL` | Yes | OpenClaw Gateway base URL (e.g. `http://localhost:3000`) |
|
|
360
|
+
| `OPENCLAW_AUTH_TOKEN` | If auth enabled | Bearer token for OpenClaw webhook endpoints |
|
|
361
|
+
|
|
362
|
+
### Start command (with OpenClaw forwarding)
|
|
363
|
+
|
|
364
|
+
```bash
|
|
365
|
+
WEBHOOK_SECRET='<secret>' \
|
|
366
|
+
OPENCLAW_GATEWAY_URL='http://localhost:3000' \
|
|
367
|
+
OPENCLAW_AUTH_TOKEN='<token>' \
|
|
368
|
+
node nansen-webhook-server.mjs
|
|
369
|
+
```
|
|
370
|
+
|
|
371
|
+
The server logs both the alert payload and the OpenClaw forward status. If OpenClaw is unreachable, the forward fails silently (the alert is still logged to stdout).
|
|
372
|
+
|
|
373
|
+
### Ask the user
|
|
374
|
+
|
|
375
|
+
Before enabling OpenClaw forwarding, ask:
|
|
376
|
+
1. Is OpenClaw running locally? What port?
|
|
377
|
+
2. Does their Gateway require auth? If so, what's the Bearer token?
|
|
378
|
+
|
|
379
|
+
If they don't know or aren't running OpenClaw, skip — the server works fine standalone.
|
|
380
|
+
|
|
381
|
+
## Notes
|
|
382
|
+
|
|
383
|
+
- The server uses zero npm dependencies — only Node.js built-ins
|
|
384
|
+
- One server can receive alerts from multiple Nansen alerts (as long as they share the same webhook secret)
|
|
385
|
+
- For production use, deploy to a cloud host with a static URL and run behind a reverse proxy with TLS
|
|
386
|
+
- The `x-nansen-signature` header format is `sha256=<HMAC-SHA256(secret, rawBody)>` — strip the `sha256=` prefix before comparing
|
|
@@ -33,7 +33,18 @@ nansen trade quote \
|
|
|
33
33
|
--amount 1000000000
|
|
34
34
|
```
|
|
35
35
|
|
|
36
|
-
Symbols resolve automatically: `SOL`, `ETH`, `USDC`, `USDT`, `WETH`. Raw addresses also work.
|
|
36
|
+
Symbols resolve automatically: `SOL`, `ETH`, `USDC`, `USDT`, `WETH`. Raw addresses also work. Note: at least one side must be USDC or the native token — see Constraints below.
|
|
37
|
+
|
|
38
|
+
## Constraints
|
|
39
|
+
|
|
40
|
+
**Swap constraint:** At least one side of every swap must be **USDC** or the chain's **native token** (SOL on Solana, ETH on Base). Arbitrary token-to-token swaps (e.g. WETH→USDT, BONK→JUP) are rejected.
|
|
41
|
+
|
|
42
|
+
- USDC (Solana): `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`
|
|
43
|
+
- USDC (Base): `0x833589fcd6edb6e08f4c7c32d4f71b54bda02913`
|
|
44
|
+
- Native SOL: `So11111111111111111111111111111111111111112`
|
|
45
|
+
- Native ETH: `0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee`
|
|
46
|
+
|
|
47
|
+
For cross-chain swaps, each token is checked against its own chain (from vs `--chain`, to vs `--to-chain`).
|
|
37
48
|
|
|
38
49
|
## Execute
|
|
39
50
|
|
package/src/api.js
CHANGED
|
@@ -60,6 +60,29 @@ export const ErrorCode = {
|
|
|
60
60
|
UNKNOWN: 'UNKNOWN', // Unclassified error
|
|
61
61
|
};
|
|
62
62
|
|
|
63
|
+
/**
|
|
64
|
+
* Error thrown by command handlers for user-facing failures (validation errors,
|
|
65
|
+
* missing args, etc.).
|
|
66
|
+
*
|
|
67
|
+
* Handlers must throw rather than calling log() + exit() directly, because
|
|
68
|
+
* direct exits bypass runCLI's catch block and skip telemetry tracking.
|
|
69
|
+
*
|
|
70
|
+
* runCLI outputs CommandError.message as plain text (not JSON-formatted like
|
|
71
|
+
* NansenError), then fires trackCommandFailed before exiting.
|
|
72
|
+
*
|
|
73
|
+
* When `data` is provided, runCLI outputs JSON.stringify(data) instead of the
|
|
74
|
+
* plain message — this preserves structured JSON output for errors that agents
|
|
75
|
+
* parse (e.g. PASSWORD_REQUIRED, API_KEY_REQUIRED).
|
|
76
|
+
*/
|
|
77
|
+
export class CommandError extends Error {
|
|
78
|
+
constructor(message, code = 'COMMAND_ERROR', data = null) {
|
|
79
|
+
super(message);
|
|
80
|
+
this.name = 'CommandError';
|
|
81
|
+
this.code = code;
|
|
82
|
+
this.data = data;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
63
86
|
/**
|
|
64
87
|
* Custom error class with structured error codes
|
|
65
88
|
*/
|
|
@@ -1207,11 +1230,11 @@ export class NansenAPI {
|
|
|
1207
1230
|
// ============= Prediction Market Endpoints =============
|
|
1208
1231
|
|
|
1209
1232
|
async pmOhlcv(params = {}) {
|
|
1210
|
-
const { marketId, sort, pagination } = params;
|
|
1233
|
+
const { marketId, orderBy, sort, pagination } = params;
|
|
1211
1234
|
if (!marketId) throw new NansenError('market_id is required. Run: nansen research pm market-screener --query "your search"', ErrorCode.MISSING_PARAM);
|
|
1212
1235
|
return this.request('/api/v1/prediction-market/ohlcv', {
|
|
1213
1236
|
market_id: marketId,
|
|
1214
|
-
sort,
|
|
1237
|
+
order_by: orderBy || sort,
|
|
1215
1238
|
pagination
|
|
1216
1239
|
});
|
|
1217
1240
|
}
|
|
@@ -1226,71 +1249,105 @@ export class NansenAPI {
|
|
|
1226
1249
|
}
|
|
1227
1250
|
|
|
1228
1251
|
async pmTopHolders(params = {}) {
|
|
1229
|
-
const { marketId, sort, pagination } = params;
|
|
1252
|
+
const { marketId, orderBy, sort, pagination } = params;
|
|
1230
1253
|
if (!marketId) throw new NansenError('market_id is required. Run: nansen research pm market-screener --query "your search"', ErrorCode.MISSING_PARAM);
|
|
1231
1254
|
return this.request('/api/v1/prediction-market/top-holders', {
|
|
1232
1255
|
market_id: marketId,
|
|
1233
|
-
sort,
|
|
1256
|
+
order_by: orderBy || sort,
|
|
1234
1257
|
pagination
|
|
1235
1258
|
});
|
|
1236
1259
|
}
|
|
1237
1260
|
|
|
1238
1261
|
async pmTradesByMarket(params = {}) {
|
|
1239
|
-
const { marketId, pagination } = params;
|
|
1262
|
+
const { marketId, orderBy, pagination } = params;
|
|
1240
1263
|
if (!marketId) throw new NansenError('market_id is required. Run: nansen research pm market-screener --query "your search"', ErrorCode.MISSING_PARAM);
|
|
1241
1264
|
return this.request('/api/v1/prediction-market/trades-by-market', {
|
|
1242
1265
|
market_id: marketId,
|
|
1266
|
+
order_by: orderBy,
|
|
1243
1267
|
pagination
|
|
1244
1268
|
});
|
|
1245
1269
|
}
|
|
1246
1270
|
|
|
1247
1271
|
async pmTradesByAddress(params = {}) {
|
|
1248
|
-
const { address, pagination } = params;
|
|
1272
|
+
const { address, orderBy, pagination } = params;
|
|
1249
1273
|
// Polymarket runs exclusively on Polygon
|
|
1250
1274
|
const validation = validateAddress(address, 'polygon');
|
|
1251
1275
|
if (!validation.valid) throw new NansenError(validation.error, validation.code);
|
|
1252
1276
|
return this.request('/api/v1/prediction-market/trades-by-address', {
|
|
1253
1277
|
address,
|
|
1278
|
+
order_by: orderBy,
|
|
1254
1279
|
pagination
|
|
1255
1280
|
});
|
|
1256
1281
|
}
|
|
1257
1282
|
|
|
1258
1283
|
async pmMarketScreener(params = {}) {
|
|
1259
|
-
const { sortBy = 'volume_24hr', query = '', status = '', pagination } = params;
|
|
1260
|
-
|
|
1284
|
+
const { orderBy, sortBy = 'volume_24hr', query = '', status = '', tags, minLiquidity, maxLiquidity, minUniqueTraders24h, maxUniqueTraders24h, minVolume24hr, maxVolume24hr, negRisk, minOpenInterest, maxOpenInterest, endDateBefore, endDateAfter, minPrice, maxPrice, pagination } = params;
|
|
1285
|
+
const body = {
|
|
1261
1286
|
sort_by: sortBy,
|
|
1262
1287
|
query,
|
|
1263
1288
|
status,
|
|
1264
1289
|
pagination
|
|
1265
|
-
}
|
|
1290
|
+
};
|
|
1291
|
+
if (orderBy) body.order_by = orderBy;
|
|
1292
|
+
if (tags && tags.length) body.tags = tags;
|
|
1293
|
+
if (minLiquidity != null) body.min_liquidity = minLiquidity;
|
|
1294
|
+
if (maxLiquidity != null) body.max_liquidity = maxLiquidity;
|
|
1295
|
+
if (minUniqueTraders24h != null) body.min_unique_traders_24h = minUniqueTraders24h;
|
|
1296
|
+
if (maxUniqueTraders24h != null) body.max_unique_traders_24h = maxUniqueTraders24h;
|
|
1297
|
+
if (minVolume24hr != null) body.min_volume_24hr = minVolume24hr;
|
|
1298
|
+
if (maxVolume24hr != null) body.max_volume_24hr = maxVolume24hr;
|
|
1299
|
+
if (negRisk != null) body.neg_risk = negRisk;
|
|
1300
|
+
if (minOpenInterest != null) body.min_open_interest = minOpenInterest;
|
|
1301
|
+
if (maxOpenInterest != null) body.max_open_interest = maxOpenInterest;
|
|
1302
|
+
if (endDateBefore) body.end_date_before = endDateBefore;
|
|
1303
|
+
if (endDateAfter) body.end_date_after = endDateAfter;
|
|
1304
|
+
if (minPrice != null) body.min_price = minPrice;
|
|
1305
|
+
if (maxPrice != null) body.max_price = maxPrice;
|
|
1306
|
+
return this.request('/api/v1/prediction-market/market-screener', body);
|
|
1266
1307
|
}
|
|
1267
1308
|
|
|
1268
1309
|
async pmEventScreener(params = {}) {
|
|
1269
|
-
const { sortBy = 'volume_24hr', query = '', status = '', pagination } = params;
|
|
1270
|
-
|
|
1310
|
+
const { orderBy, sortBy = 'volume_24hr', query = '', status = '', tags, minLiquidity, maxLiquidity, minUniqueTraders24h, maxUniqueTraders24h, minVolume24hr, maxVolume24hr, negRisk, minOpenInterest, maxOpenInterest, endDateBefore, endDateAfter, pagination } = params;
|
|
1311
|
+
const body = {
|
|
1271
1312
|
sort_by: sortBy,
|
|
1272
1313
|
query,
|
|
1273
1314
|
status,
|
|
1274
1315
|
pagination
|
|
1275
|
-
}
|
|
1316
|
+
};
|
|
1317
|
+
if (orderBy) body.order_by = orderBy;
|
|
1318
|
+
if (tags && tags.length) body.tags = tags;
|
|
1319
|
+
if (minLiquidity != null) body.min_liquidity = minLiquidity;
|
|
1320
|
+
if (maxLiquidity != null) body.max_liquidity = maxLiquidity;
|
|
1321
|
+
if (minUniqueTraders24h != null) body.min_unique_traders_24h = minUniqueTraders24h;
|
|
1322
|
+
if (maxUniqueTraders24h != null) body.max_unique_traders_24h = maxUniqueTraders24h;
|
|
1323
|
+
if (minVolume24hr != null) body.min_volume_24hr = minVolume24hr;
|
|
1324
|
+
if (maxVolume24hr != null) body.max_volume_24hr = maxVolume24hr;
|
|
1325
|
+
if (negRisk != null) body.neg_risk = negRisk;
|
|
1326
|
+
if (minOpenInterest != null) body.min_open_interest = minOpenInterest;
|
|
1327
|
+
if (maxOpenInterest != null) body.max_open_interest = maxOpenInterest;
|
|
1328
|
+
if (endDateBefore) body.end_date_before = endDateBefore;
|
|
1329
|
+
if (endDateAfter) body.end_date_after = endDateAfter;
|
|
1330
|
+
return this.request('/api/v1/prediction-market/event-screener', body);
|
|
1276
1331
|
}
|
|
1277
1332
|
|
|
1278
1333
|
async pmPnlByMarket(params = {}) {
|
|
1279
|
-
const { marketId, pagination } = params;
|
|
1334
|
+
const { marketId, orderBy, pagination } = params;
|
|
1280
1335
|
if (!marketId) throw new NansenError('market_id is required. Run: nansen research pm market-screener --query "your search"', ErrorCode.MISSING_PARAM);
|
|
1281
1336
|
return this.request('/api/v1/prediction-market/pnl-by-market', {
|
|
1282
1337
|
market_id: marketId,
|
|
1338
|
+
order_by: orderBy,
|
|
1283
1339
|
pagination
|
|
1284
1340
|
});
|
|
1285
1341
|
}
|
|
1286
1342
|
|
|
1287
1343
|
async pmPnlByAddress(params = {}) {
|
|
1288
|
-
const { address, pagination } = params;
|
|
1344
|
+
const { address, orderBy, pagination } = params;
|
|
1289
1345
|
// Polymarket runs exclusively on Polygon
|
|
1290
1346
|
const validation = validateAddress(address, 'polygon');
|
|
1291
1347
|
if (!validation.valid) throw new NansenError(validation.error, validation.code);
|
|
1292
1348
|
return this.request('/api/v1/prediction-market/pnl-by-address', {
|
|
1293
1349
|
address,
|
|
1350
|
+
order_by: orderBy,
|
|
1294
1351
|
pagination
|
|
1295
1352
|
});
|
|
1296
1353
|
}
|
|
@@ -1311,6 +1368,17 @@ export class NansenAPI {
|
|
|
1311
1368
|
});
|
|
1312
1369
|
}
|
|
1313
1370
|
|
|
1371
|
+
async pmAddressSummary(params = {}) {
|
|
1372
|
+
const { address, pagination } = params;
|
|
1373
|
+
// Polymarket runs exclusively on Polygon
|
|
1374
|
+
const validation = validateAddress(address, 'polygon');
|
|
1375
|
+
if (!validation.valid) throw new NansenError(validation.error, validation.code);
|
|
1376
|
+
return this.request('/api/v1/prediction-market/address-summary', {
|
|
1377
|
+
address,
|
|
1378
|
+
pagination
|
|
1379
|
+
});
|
|
1380
|
+
}
|
|
1381
|
+
|
|
1314
1382
|
// ============= Points Endpoints =============
|
|
1315
1383
|
|
|
1316
1384
|
async pointsLeaderboard(params = {}) {
|