nansen-cli 1.0.3 → 1.1.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/CLAUDE.md ADDED
@@ -0,0 +1,185 @@
1
+ # CLAUDE.md
2
+
3
+ AI assistant guide for contributing to nansen-cli.
4
+
5
+ ## What This Is
6
+
7
+ A CLI for the [Nansen API](https://docs.nansen.ai), designed specifically for AI agents. All output is structured JSON. 30 endpoints across Smart Money, Profiler, Token God Mode, and Portfolio.
8
+
9
+ ## Quick Start
10
+
11
+ ```bash
12
+ npm install
13
+ npm test # Run mocked tests (no API key needed)
14
+ npm run test:live # Run against live API (needs NANSEN_API_KEY)
15
+ ```
16
+
17
+ ## Project Structure
18
+
19
+ ```
20
+ src/
21
+ ├── index.js # Thin CLI entry point (imports cli.js)
22
+ ├── cli.js # CLI logic: parsing, routing, formatting, schema
23
+ ├── api.js # NansenAPI class, all HTTP calls, validation
24
+ └── __tests__/
25
+ ├── unit.test.js # Core logic tests (validation, parsing, formatting)
26
+ ├── api.test.js # API method tests with mocked fetch
27
+ ├── cli.test.js # CLI integration tests (subprocess)
28
+ ├── cli.internal.test.js # CLI unit tests (direct imports for coverage)
29
+ └── coverage.test.js # Endpoint coverage verification
30
+ ```
31
+
32
+ **Three files, clear separation:**
33
+ - `index.js` = Entry point (thin wrapper)
34
+ - `cli.js` = CLI layer (parsing, routing, output formatting, schema)
35
+ - `api.js` = API layer (HTTP, validation, config)
36
+
37
+ ## Code Conventions
38
+
39
+ - **ES modules** (`import`/`export`, not `require`)
40
+ - **Async/await** for all API calls
41
+ - **All output is JSON** (for AI agent consumption)
42
+ - **No external dependencies** (just Node.js built-ins + vitest for tests)
43
+
44
+ ## Adding a New Endpoint
45
+
46
+ 1. **Add API method in `src/api.js`:**
47
+ ```javascript
48
+ async newEndpoint(params = {}) {
49
+ const { chain = 'solana', filters = {}, orderBy, pagination } = params;
50
+ return this.request('/api/v1/endpoint-path', {
51
+ chain,
52
+ filters,
53
+ order_by: orderBy,
54
+ pagination
55
+ });
56
+ }
57
+ ```
58
+
59
+ 2. **Add CLI handler in `src/index.js`:**
60
+ ```javascript
61
+ // In the appropriate command handler (smart-money, profiler, token, portfolio)
62
+ 'new-subcommand': () => api.newEndpoint({ chains, filters, orderBy, pagination }),
63
+ ```
64
+
65
+ 3. **Add tests:**
66
+ - `api.test.js` — Mock the fetch, verify request body
67
+ - `cli.test.js` — Test CLI invocation
68
+ - `coverage.test.js` — Add to `DOCUMENTED_ENDPOINTS`
69
+
70
+ 4. **Update `README.md`** with docs
71
+
72
+ ## Testing
73
+
74
+ ```bash
75
+ npm test # All tests, mocked
76
+ npm run test:watch # Watch mode
77
+ npm run test:coverage # With coverage report
78
+ NANSEN_API_KEY=xxx npm run test:live # Live API tests
79
+ ```
80
+
81
+ **Test philosophy:**
82
+ - Unit tests don't need API key (use mocked fetch)
83
+ - Live tests are opt-in via `NANSEN_LIVE_TEST=1`
84
+ - Coverage test ensures all documented endpoints have implementations
85
+
86
+ ## Common Patterns
87
+
88
+ ### Address Validation
89
+ ```javascript
90
+ // Validates EVM (0x...) or Solana (Base58) addresses
91
+ const validation = validateAddress(address, chain);
92
+ if (!validation.valid) throw new Error(validation.error);
93
+ ```
94
+
95
+ ### Date Ranges
96
+ ```javascript
97
+ // Most endpoints accept days param, converted to date range
98
+ const to = new Date().toISOString().split('T')[0];
99
+ const from = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
100
+ ```
101
+
102
+ ### Retry Behavior
103
+ - **Enabled by default** with 3 attempts
104
+ - Retries on: 429, 500, 502, 503, 504, network errors
105
+ - Exponential backoff with jitter (1s base, 30s max)
106
+ - Respects `retry-after` headers
107
+ - Disable with `--no-retry` or `options.retry = false`
108
+ - Success responses include `_meta.retriedAttempts` if retried
109
+
110
+ ### Response Format
111
+ ```javascript
112
+ // Success
113
+ { "success": true, "data": { ... } }
114
+
115
+ // Error
116
+ { "success": false, "error": "message", "code": "ERROR_CODE", "status": 401, "details": { ... } }
117
+ ```
118
+
119
+ ### Schema Discovery
120
+ ```bash
121
+ nansen schema # Full schema (commands, options, types)
122
+ nansen schema smart-money # Schema for specific command
123
+ ```
124
+ Returns JSON with all commands, subcommands, option types/defaults, return fields, supported chains, and smart money labels. No API key required.
125
+
126
+ ### Field Filtering
127
+ ```bash
128
+ nansen smart-money netflow --fields token_symbol,net_flow_usd,chain
129
+ ```
130
+ Reduces response size by including only specified fields. Works with nested data structures.
131
+
132
+ ### Error Codes
133
+ Structured error codes for programmatic handling:
134
+
135
+ | Code | Description |
136
+ |------|-------------|
137
+ | `UNAUTHORIZED` | Invalid or missing API key (401) |
138
+ | `FORBIDDEN` | Valid key but insufficient permissions (403) |
139
+ | `RATE_LIMITED` | Too many requests (429) |
140
+ | `INVALID_ADDRESS` | Address format validation failed |
141
+ | `INVALID_TOKEN` | Token address validation failed |
142
+ | `INVALID_CHAIN` | Unsupported or invalid chain |
143
+ | `INVALID_PARAMS` | Generic parameter validation error |
144
+ | `MISSING_PARAM` | Required parameter not provided |
145
+ | `NOT_FOUND` | Resource not found (404) |
146
+ | `TOKEN_NOT_FOUND` | Token doesn't exist |
147
+ | `ADDRESS_NOT_FOUND` | Address has no data |
148
+ | `SERVER_ERROR` | Nansen API internal error (500+) |
149
+ | `SERVICE_UNAVAILABLE` | API temporarily down (503) |
150
+ | `NETWORK_ERROR` | Connection failed |
151
+ | `TIMEOUT` | Request timed out |
152
+ | `UNKNOWN` | Unclassified error |
153
+
154
+ ## API Reference
155
+
156
+ ### Chains
157
+ `ethereum`, `solana`, `base`, `bnb`, `arbitrum`, `polygon`, `optimism`, `avalanche`, `linea`, `scroll`, `zksync`, `mantle`, `ronin`, `sei`, `plasma`, `sonic`, `unichain`, `monad`, `hyperevm`, `iotaevm`
158
+
159
+ ### Smart Money Labels
160
+ `Fund`, `Smart Trader`, `30D Smart Trader`, `90D Smart Trader`, `180D Smart Trader`, `Smart HL Perps Trader`
161
+
162
+ ### Endpoints by Category
163
+
164
+ **Smart Money (6):** netflow, dex-trades, perp-trades, holdings, dcas, historical-holdings
165
+
166
+ **Profiler (11):** balance, labels, transactions, pnl, search, historical-balances, related-wallets, counterparties, pnl-summary, perp-positions, perp-trades
167
+
168
+ **Token God Mode (12):** screener, holders, flows, dex-trades, pnl, who-bought-sold, flow-intelligence, transfers, jup-dca, perp-trades, perp-positions, perp-pnl-leaderboard
169
+
170
+ **Portfolio (1):** defi-holdings
171
+
172
+ ## Gotchas
173
+
174
+ - **Perp endpoints** work with Hyperliquid (use `--symbol BTC` not `--token`)
175
+ - **JUP DCA** is Solana-only
176
+ - **Beta endpoints** (`/api/beta/...`) may have different pagination
177
+ - **EVM vs Solana addresses** — validation auto-detects based on chain param
178
+
179
+ ## PR Checklist
180
+
181
+ - [ ] Tests pass (`npm test`)
182
+ - [ ] New endpoints have tests in all 3 test files
183
+ - [ ] README.md updated if adding user-facing features
184
+ - [ ] CHANGELOG.md updated for releases
185
+ - [ ] No new dependencies (keep it lightweight)
package/README.md CHANGED
@@ -2,9 +2,12 @@
2
2
 
3
3
  [![npm version](https://img.shields.io/npm/v/nansen-cli.svg)](https://www.npmjs.com/package/nansen-cli)
4
4
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
- [![Tests](https://img.shields.io/badge/tests-138%20passing-brightgreen.svg)]()
5
+ [![Tests](https://img.shields.io/badge/tests-342%20passing-brightgreen.svg)]()
6
+ [![Coverage](https://img.shields.io/badge/coverage-80%25-brightgreen.svg)]()
6
7
 
7
- Command-line interface for the [Nansen API](https://docs.nansen.ai). Designed for AI agents with structured JSON output.
8
+ > **Built by agents, for agents.** We prioritize the best possible AI agent experience.
9
+
10
+ Command-line interface for the [Nansen API](https://docs.nansen.ai) with structured JSON output, designed for AI agents and automation.
8
11
 
9
12
  ## Installation
10
13
 
@@ -120,12 +123,27 @@ Deep analytics for any token.
120
123
  |------------|-------------|
121
124
  | `defi` | DeFi holdings across protocols |
122
125
 
126
+ ### `schema` - Schema Discovery
127
+
128
+ Output JSON schema for agent introspection. No API key required.
129
+
130
+ ```bash
131
+ # Get full schema
132
+ nansen schema --pretty
133
+
134
+ # Get schema for specific command
135
+ nansen schema smart-money --pretty
136
+ ```
137
+
138
+ Returns command definitions, option types/defaults, supported chains, and smart money labels.
139
+
123
140
  ## Options
124
141
 
125
142
  | Option | Description |
126
143
  |--------|-------------|
127
144
  | `--pretty` | Format JSON output for readability |
128
145
  | `--table` | Format output as human-readable table |
146
+ | `--fields <list>` | Comma-separated fields to include (reduces response size) |
129
147
  | `--chain <chain>` | Blockchain to query |
130
148
  | `--chains <json>` | Multiple chains as JSON array |
131
149
  | `--limit <n>` | Number of results |
@@ -144,12 +162,14 @@ Deep analytics for any token.
144
162
 
145
163
  ## AI Agent Integration
146
164
 
147
- The CLI is designed for AI agents and automation:
165
+ This CLI is built specifically for AI agents. Every design decision prioritizes agent usability.
148
166
 
149
- - **Structured Output**: All responses are JSON with consistent schema
150
- - **Error Handling**: Errors include status codes and actionable details
167
+ **Why agents love it:**
168
+ - **Structured Output**: All responses are JSON with consistent schema — no parsing HTML or unstructured text
169
+ - **Predictable Errors**: Errors include status codes and actionable details agents can handle programmatically
170
+ - **Zero Config**: Works with just an API key — no complex setup
151
171
  - **Composable**: Commands can be chained with shell pipes
152
- - **Discoverable**: `help` commands at every level
172
+ - **Discoverable**: `help` commands at every level for agent introspection
153
173
 
154
174
  ```json
155
175
  // Success response
@@ -165,11 +185,19 @@ The CLI is designed for AI agents and automation:
165
185
  {
166
186
  "success": false,
167
187
  "error": "API error message",
188
+ "code": "UNAUTHORIZED",
168
189
  "status": 401,
169
190
  "details": {...}
170
191
  }
171
192
  ```
172
193
 
194
+ **Roadmap** (see [TODO.md](TODO.md)):
195
+ - ~~Rate limit handling with auto-retry~~ ✅
196
+ - ~~Structured error codes for programmatic handling~~ ✅
197
+ - ~~Schema discovery endpoint (`nansen schema`)~~ ✅
198
+ - ~~Field filtering to reduce response size~~ ✅
199
+ - Response caching and batch queries
200
+
173
201
  ## Examples
174
202
 
175
203
  ```bash
@@ -190,6 +218,13 @@ nansen token perp-positions --symbol BTC --pretty
190
218
 
191
219
  # Get top PnL traders for a token, sorted by realized PnL
192
220
  nansen token pnl --token JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN --chain solana --days 30 --sort pnl_usd:desc --table
221
+
222
+ # Filter response to specific fields (reduces tokens for AI agents)
223
+ nansen smart-money netflow --chain solana --fields token_symbol,net_flow_usd,chain
224
+
225
+ # Get schema for agent introspection
226
+ nansen schema --pretty
227
+ nansen schema token --pretty
193
228
  ```
194
229
 
195
230
  ## Development
@@ -207,6 +242,8 @@ NANSEN_API_KEY=your-key npm run test:live
207
242
 
208
243
  See [CONTRIBUTING.md](CONTRIBUTING.md) for development guidelines.
209
244
 
245
+ **AI contributors:** See [CLAUDE.md](CLAUDE.md) for agent-specific guidance on contributing to this repo.
246
+
210
247
  ## API Coverage
211
248
 
212
249
  | Category | Endpoints | Coverage |
package/TODO.md ADDED
@@ -0,0 +1,47 @@
1
+ # TODO
2
+
3
+ > **Built by agents, for agents.** We prioritize improvements that create the best possible AI agent experience.
4
+
5
+ ## Medium Priority
6
+
7
+ ### Response Caching
8
+ - [ ] Add optional local cache (SQLite or file-based)
9
+ - [ ] Configurable TTL (default 60-300s)
10
+ - [ ] `--no-cache` flag to bypass
11
+ - [ ] `--cache-ttl` flag to override
12
+
13
+ ### Batch Queries
14
+ - [ ] Support multiple addresses: `--addresses '[...]'`
15
+ - [ ] Support multiple tokens: `--tokens '[...]'`
16
+ - [ ] Reduce N calls to 1 call
17
+
18
+ ## Test Quality
19
+
20
+ ### Remaining Items
21
+ - [ ] Test config priority chain (ENV > ~/.nansen > local config.json) — needs `loadConfig()` exported
22
+ - [ ] Add snapshot tests for `--help` output
23
+ - [ ] Document magic test addresses (e.g. Binance hot wallet)
24
+ - [ ] Test Bitcoin address validation
25
+ - [ ] Test stdin pipe mode for API key input
26
+ - [ ] Remove duplicated `parseArgs` in unit.test.js (now exported from cli.js)
27
+ - [ ] Reduce cli.test.js subprocess tests to ~10 smoke tests
28
+
29
+ ## Nice to Have
30
+
31
+ ### Streaming Output
32
+ - [ ] `--stream` flag for large result sets
33
+ - [ ] Output as JSON lines (newline-delimited JSON)
34
+ - [ ] Enable incremental processing by agents
35
+
36
+ ### Shell Completions
37
+ - [ ] Bash completions
38
+ - [ ] Zsh completions
39
+ - [ ] Fish completions
40
+
41
+ ### Distribution
42
+ - [ ] Homebrew formula (`brew install nansen-cli`)
43
+ - [ ] Docker image
44
+
45
+ ---
46
+
47
+ *Last updated: 2026-02-06*
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nansen-cli",
3
- "version": "1.0.3",
3
+ "version": "1.1.0",
4
4
  "description": "Command-line interface for Nansen API - designed for AI agents",
5
5
  "main": "src/index.js",
6
6
  "type": "module",