nansen-cli 1.45.0 → 2.0.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 +172 -0
- package/README.md +158 -18
- package/docs/browser-login.md +117 -0
- package/package.json +11 -2
- package/scripts/postinstall.js +35 -30
- package/skills/nansen-agent-guide/SKILL.md +13 -2
- package/skills/nansen-alerts-webhook-listener/SKILL.md +5 -2
- package/skills/nansen-dca-tracker/SKILL.md +10 -2
- package/skills/nansen-defi-positions/SKILL.md +5 -2
- package/skills/nansen-exit-signals/SKILL.md +10 -2
- package/skills/nansen-fund-tracker/SKILL.md +10 -2
- package/skills/nansen-general-search/SKILL.md +10 -2
- package/skills/nansen-holder-analysis/SKILL.md +10 -2
- package/skills/nansen-limit-orders/SKILL.md +6 -3
- package/skills/nansen-perp-screener/SKILL.md +10 -2
- package/skills/nansen-perp-trader-profile/SKILL.md +10 -2
- package/skills/nansen-polymarket-deep-dive/SKILL.md +10 -2
- package/skills/nansen-polymarket-insider-scan/SKILL.md +10 -2
- package/skills/nansen-polymarket-trader-profile/SKILL.md +10 -2
- package/skills/nansen-portfolio-tracker/SKILL.md +10 -2
- package/skills/nansen-prediction-markets/SKILL.md +10 -2
- package/skills/nansen-sm-cross-chain-flows/SKILL.md +10 -2
- package/skills/nansen-smart-alerts/SKILL.md +9 -4
- package/skills/nansen-smart-money-alpha/SKILL.md +10 -2
- package/skills/nansen-smart-money-tracker/SKILL.md +10 -2
- package/skills/nansen-smart-money-trend/SKILL.md +10 -2
- package/skills/nansen-token-research/SKILL.md +10 -2
- package/skills/nansen-token-screener/SKILL.md +14 -4
- package/skills/nansen-token-transfer-analysis/SKILL.md +10 -2
- package/skills/nansen-trading/SKILL.md +27 -2
- package/skills/nansen-wallet-batch/SKILL.md +10 -2
- package/skills/nansen-wallet-clustering/SKILL.md +10 -2
- package/skills/nansen-wallet-deep-dive/SKILL.md +10 -2
- package/skills/nansen-wallet-keychain-migration/SKILL.md +23 -15
- package/skills/nansen-wallet-manager/SKILL.md +26 -10
- package/skills/nansen-wallet-profiler/SKILL.md +10 -2
- package/skills/nansen-web-fetcher/SKILL.md +5 -2
- package/skills/nansen-web-searcher/SKILL.md +5 -2
- package/src/api.js +319 -129
- package/src/auth-browser.js +16 -0
- package/src/auth-credentials.js +73 -0
- package/src/auth-device.js +242 -0
- package/src/auth-key-input.js +46 -0
- package/src/auth-login.js +90 -0
- package/src/auth-state.js +487 -0
- package/src/auth-store-native.js +20 -0
- package/src/auth-store-worker.js +64 -0
- package/src/auth-store.js +140 -0
- package/src/auto-paginate.js +272 -0
- package/src/bridge.js +309 -85
- package/src/cache-inspect.js +345 -0
- package/src/chain-ids.js +1 -2
- package/src/cli.js +779 -286
- package/src/commands/agent.js +20 -9
- package/src/commands/alerts.js +1 -1
- package/src/commands/completion.js +2 -15
- package/src/commands/mcp.js +22 -20
- package/src/commands/research.js +4 -2
- package/src/cost-cache.js +16 -2
- package/src/debug.js +348 -0
- package/src/doctor.js +22 -45
- package/src/ens.js +3 -1
- package/src/execute-guard.js +116 -0
- package/src/hl-action.js +41 -13
- package/src/limit-order.js +9 -1
- package/src/mcp-client-config.js +169 -0
- package/src/mcp-client-config.json +17 -0
- package/src/mcp-verify.js +6 -5
- package/src/perp.js +61 -9
- package/src/privy.js +12 -12
- package/src/query-options.js +38 -6
- package/src/response-meta.js +57 -2
- package/src/rpc-urls.js +9 -11
- package/src/schema.json +309 -30
- package/src/semver.js +23 -4
- package/src/swap-simulation.js +35 -30
- package/src/telemetry.js +20 -0
- package/src/trading.js +806 -40
- package/src/transfer.js +75 -9
- package/src/update-check.js +9 -1
- package/src/wallet.js +240 -20
- package/src/walletconnect-trading.js +29 -8
- package/src/walletconnect-x402.js +9 -5
- package/src/x402-svm.js +123 -64
- package/src/x402.js +46 -14
package/src/transfer.js
CHANGED
|
@@ -55,7 +55,18 @@ function parseAmount(amountStr, decimals) {
|
|
|
55
55
|
const parts = str.split('.');
|
|
56
56
|
const whole = parts[0] || '0';
|
|
57
57
|
let frac = (parts[1] || '').padEnd(decimals, '0').slice(0, decimals);
|
|
58
|
-
|
|
58
|
+
const raw = BigInt(whole) * (10n ** BigInt(decimals)) + BigInt(frac);
|
|
59
|
+
// Zero base units would still be signed and broadcast: a native send that
|
|
60
|
+
// pays gas to move nothing, a token transfer of 0, or a limit order created
|
|
61
|
+
// with inputAmount "0". Refuse both a literal zero and a positive amount
|
|
62
|
+
// that truncates to zero at this token's precision.
|
|
63
|
+
if (raw === 0n) {
|
|
64
|
+
if (/^0+(\.0+)?$/.test(str)) throw new Error('Amount must be greater than zero');
|
|
65
|
+
throw new Error(
|
|
66
|
+
`Amount ${str} is below the smallest unit of this token (${decimals} decimals) and would send nothing. Use at least ${decimals === 0 ? '1' : '0.' + '0'.repeat(decimals - 1) + '1'}.`,
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
return raw;
|
|
59
70
|
}
|
|
60
71
|
|
|
61
72
|
function formatAmount(rawAmount, decimals) {
|
|
@@ -76,17 +87,47 @@ async function rpcCall(url, method, params = []) {
|
|
|
76
87
|
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
|
|
77
88
|
});
|
|
78
89
|
const data = await response.json();
|
|
79
|
-
if (data.error)
|
|
90
|
+
if (data.error) {
|
|
91
|
+
const err = new Error(friendlyRpcError(data.error, method));
|
|
92
|
+
// Classified from the raw RPC text, before any rewording, so callers can
|
|
93
|
+
// branch on it without depending on the friendly message's wording.
|
|
94
|
+
err.transactionWouldFail = isTransactionFailureMessage(data.error);
|
|
95
|
+
throw err;
|
|
96
|
+
}
|
|
80
97
|
return data.result;
|
|
81
98
|
}
|
|
82
99
|
|
|
100
|
+
/**
|
|
101
|
+
* True when an RPC error says the transaction itself cannot succeed
|
|
102
|
+
* (insufficient funds, execution reverted), as opposed to the node failing
|
|
103
|
+
* to answer.
|
|
104
|
+
*/
|
|
105
|
+
function isTransactionFailureMessage(error) {
|
|
106
|
+
const lower = String(error?.message || JSON.stringify(error)).toLowerCase();
|
|
107
|
+
return lower.includes('insufficient funds')
|
|
108
|
+
|| lower.includes('insufficient lamports')
|
|
109
|
+
// geth/op-geth phrase every EVM revert as "execution reverted[: reason]";
|
|
110
|
+
// a bare "reverted" would also catch unrelated wording.
|
|
111
|
+
|| lower.includes('execution reverted');
|
|
112
|
+
}
|
|
113
|
+
|
|
83
114
|
/**
|
|
84
115
|
* Convert raw RPC errors into actionable messages.
|
|
116
|
+
*
|
|
117
|
+
* rpcCall serves both rails, so the method name decides which chain's advice
|
|
118
|
+
* applies: EVM JSON-RPC methods are `eth_*`, Solana's are bare camelCase.
|
|
119
|
+
* geth rejects an underfunded transaction with "insufficient funds for gas *
|
|
120
|
+
* price + value", which used to match the Solana branch and tell a Base or
|
|
121
|
+
* Ethereum user to top up SOL.
|
|
85
122
|
*/
|
|
86
|
-
function friendlyRpcError(error) {
|
|
123
|
+
function friendlyRpcError(error, method = '') {
|
|
87
124
|
const msg = error.message || JSON.stringify(error);
|
|
88
125
|
const lower = msg.toLowerCase();
|
|
126
|
+
const isEvm = typeof method === 'string' && method.toLowerCase().startsWith('eth_');
|
|
89
127
|
|
|
128
|
+
if (isEvm && lower.includes('insufficient funds')) {
|
|
129
|
+
return `Insufficient native balance to cover gas and value for this transaction. Top up the wallet with the chain's native gas token (ETH on most EVM chains). RPC said: ${msg}`;
|
|
130
|
+
}
|
|
90
131
|
if (lower.includes('no record of a prior credit') || lower.includes('accountnotfound')) {
|
|
91
132
|
return 'Insufficient SOL for transaction fees. Send at least 0.01 SOL to your wallet.';
|
|
92
133
|
}
|
|
@@ -107,6 +148,17 @@ function friendlyRpcError(error) {
|
|
|
107
148
|
}
|
|
108
149
|
|
|
109
150
|
|
|
151
|
+
/**
|
|
152
|
+
* eth_estimateGas fails for two very different reasons: the node could not run
|
|
153
|
+
* the estimate (transient — fall back to a default gas limit), or it ran the
|
|
154
|
+
* call and the transaction cannot succeed (insufficient funds, execution
|
|
155
|
+
* reverted). Broadcasting the second kind with a default gas limit only burns
|
|
156
|
+
* gas on a transaction the node already said will fail, so let it propagate.
|
|
157
|
+
*/
|
|
158
|
+
function isDoomedTransactionError(err) {
|
|
159
|
+
return err?.transactionWouldFail === true;
|
|
160
|
+
}
|
|
161
|
+
|
|
110
162
|
function bigIntToHex(n) {
|
|
111
163
|
if (n === 0n) return '0x';
|
|
112
164
|
const hex = n.toString(16);
|
|
@@ -203,7 +255,10 @@ async function buildEvmTransaction({ to, amount, token, privateKey, chain, max =
|
|
|
203
255
|
{ from, to, value: '0x1' },
|
|
204
256
|
]);
|
|
205
257
|
estGasLimit = BigInt(dummyEstimate) * 120n / 100n;
|
|
206
|
-
} catch {
|
|
258
|
+
} catch (err) {
|
|
259
|
+
// A node that rejects even a 1-wei transfer to this recipient is
|
|
260
|
+
// telling us the send cannot succeed; do not paper over it.
|
|
261
|
+
if (isDoomedTransactionError(err)) throw err;
|
|
207
262
|
estGasLimit = 21000n;
|
|
208
263
|
}
|
|
209
264
|
// Reserve: L2 gas (gasLimit * maxFee) + L1 data fee buffer
|
|
@@ -231,7 +286,8 @@ async function buildEvmTransaction({ to, amount, token, privateKey, chain, max =
|
|
|
231
286
|
const gasEstimate = await rpcCall(rpcUrl, 'eth_estimateGas', [estimateParams]);
|
|
232
287
|
// Add 20% buffer for safety
|
|
233
288
|
gasLimit = BigInt(gasEstimate) * 120n / 100n;
|
|
234
|
-
} catch {
|
|
289
|
+
} catch (err) {
|
|
290
|
+
if (isDoomedTransactionError(err)) throw err;
|
|
235
291
|
// Fallback to safe defaults if estimation fails
|
|
236
292
|
gasLimit = token ? 100000n : 21000n;
|
|
237
293
|
}
|
|
@@ -334,7 +390,16 @@ export async function getTokenInfo(rpcUrl, mint) {
|
|
|
334
390
|
if (!info || !info.value) throw new Error(`Token mint ${mint} not found`);
|
|
335
391
|
const owner = info.value.owner;
|
|
336
392
|
const decimals = info.value.data?.parsed?.info?.decimals;
|
|
337
|
-
|
|
393
|
+
// The decimals scale every human-readable --amount into base units, so a
|
|
394
|
+
// guess is never safe. When the RPC cannot jsonParse the mint (an owner
|
|
395
|
+
// program it does not know, or raw base64 data) the account is not a mint
|
|
396
|
+
// we can size a transfer for — say so instead of assuming 9 decimals.
|
|
397
|
+
if (!Number.isInteger(decimals) || decimals < 0) {
|
|
398
|
+
throw new Error(
|
|
399
|
+
`Could not determine decimals for token mint ${mint}: the RPC did not return parsed token data (owner ${owner ?? 'unknown'}). Check that the address is an SPL token mint, or try a different Solana RPC.`,
|
|
400
|
+
);
|
|
401
|
+
}
|
|
402
|
+
return { tokenProgram: owner, decimals };
|
|
338
403
|
}
|
|
339
404
|
|
|
340
405
|
/**
|
|
@@ -876,7 +941,8 @@ async function sendTokensViaWalletConnect({ to, amount, chain, token, max, dryRu
|
|
|
876
941
|
{ from: wcAddress, to, value: '0x1' },
|
|
877
942
|
]);
|
|
878
943
|
estGasLimit = BigInt(dummyEstimate) * 120n / 100n;
|
|
879
|
-
} catch {
|
|
944
|
+
} catch (err) {
|
|
945
|
+
if (isDoomedTransactionError(err)) throw err;
|
|
880
946
|
estGasLimit = 21000n;
|
|
881
947
|
}
|
|
882
948
|
const feeHistory = await rpcCall(rpcUrl, 'eth_feeHistory', [4, 'latest', [50]]);
|
|
@@ -910,7 +976,8 @@ async function sendTokensViaWalletConnect({ to, amount, chain, token, max, dryRu
|
|
|
910
976
|
if (txValue && txValue !== '0') estimateParams.value = '0x' + BigInt(txValue).toString(16);
|
|
911
977
|
const gasEstimate = await rpcCall(rpcUrl, 'eth_estimateGas', [estimateParams]);
|
|
912
978
|
gasLimit = (BigInt(gasEstimate) * 120n / 100n).toString(); // 20% buffer
|
|
913
|
-
} catch {
|
|
979
|
+
} catch (err) {
|
|
980
|
+
if (isDoomedTransactionError(err)) throw err;
|
|
914
981
|
gasLimit = token ? '100000' : '21000'; // fallback
|
|
915
982
|
}
|
|
916
983
|
|
|
@@ -957,7 +1024,6 @@ function getExplorerUrl(chain, txHash) {
|
|
|
957
1024
|
bnb: 'https://bscscan.com/tx/',
|
|
958
1025
|
avalanche: 'https://snowtrace.io/tx/',
|
|
959
1026
|
linea: 'https://lineascan.build/tx/',
|
|
960
|
-
scroll: 'https://scrollscan.com/tx/',
|
|
961
1027
|
mantle: 'https://mantlescan.xyz/tx/',
|
|
962
1028
|
};
|
|
963
1029
|
const base = explorers[chain] || explorers.ethereum;
|
package/src/update-check.js
CHANGED
|
@@ -17,6 +17,14 @@ const CACHE_FILE = path.join(CONFIG_DIR, 'update-check.json');
|
|
|
17
17
|
const STALE_MS = 24 * 60 * 60 * 1000; // 24 hours
|
|
18
18
|
const PACKAGE_NAME = 'nansen-cli';
|
|
19
19
|
|
|
20
|
+
/** How long a recorded update check stays fresh. */
|
|
21
|
+
export const UPDATE_CHECK_TTL_MS = STALE_MS;
|
|
22
|
+
|
|
23
|
+
/** Absolute path of the update check cache file, for `nansen cache stats` and `clear`. */
|
|
24
|
+
export function getUpdateCheckFile() {
|
|
25
|
+
return CACHE_FILE;
|
|
26
|
+
}
|
|
27
|
+
|
|
20
28
|
/**
|
|
21
29
|
* Compare two semver strings. Returns true if latest > current.
|
|
22
30
|
* Exported so `nansen doctor` reports upgrade state with identical semantics.
|
|
@@ -150,7 +158,7 @@ export function scheduleUpdateCheck() {
|
|
|
150
158
|
// Check staleness
|
|
151
159
|
if (fs.existsSync(CACHE_FILE)) {
|
|
152
160
|
const { checkedAt } = JSON.parse(fs.readFileSync(CACHE_FILE, 'utf8'));
|
|
153
|
-
if (checkedAt && Date.now() - checkedAt < STALE_MS) return;
|
|
161
|
+
if (Number.isFinite(checkedAt) && checkedAt !== 0 && Date.now() - checkedAt < STALE_MS) return;
|
|
154
162
|
}
|
|
155
163
|
|
|
156
164
|
const child = childProcess.spawn(process.execPath, ['-e', buildCheckScript(CONFIG_DIR, CACHE_FILE)], {
|
package/src/wallet.js
CHANGED
|
@@ -207,9 +207,87 @@ export function generateSolanaWallet() {
|
|
|
207
207
|
|
|
208
208
|
// ============= Storage =============
|
|
209
209
|
|
|
210
|
+
/**
|
|
211
|
+
* Create a private directory (and any missing parents) owner-only. mkdir's
|
|
212
|
+
* mode is filtered through the process umask — a 0277 umask leaves 0500, so
|
|
213
|
+
* the owner could not create files inside — so each directory this creates
|
|
214
|
+
* has its mode pinned afterwards. Existing directories are left untouched.
|
|
215
|
+
*/
|
|
216
|
+
export function mkdirPrivateSync(dir) {
|
|
217
|
+
const missing = [];
|
|
218
|
+
for (let cur = dir; !fs.existsSync(cur); cur = path.dirname(cur)) {
|
|
219
|
+
missing.unshift(cur);
|
|
220
|
+
if (path.dirname(cur) === cur) break;
|
|
221
|
+
}
|
|
222
|
+
for (const d of missing) {
|
|
223
|
+
try {
|
|
224
|
+
fs.mkdirSync(d, { mode: 0o700 });
|
|
225
|
+
} catch (err) {
|
|
226
|
+
// Another nansen process may have created it between the existence
|
|
227
|
+
// check and here; the chmod below still applies.
|
|
228
|
+
if (err.code !== 'EEXIST') throw err;
|
|
229
|
+
}
|
|
230
|
+
fs.chmodSync(d, 0o700);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
210
234
|
function ensureWalletsDir() {
|
|
211
|
-
|
|
212
|
-
|
|
235
|
+
mkdirPrivateSync(getWalletsDir());
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Write a wallet-subsystem JSON file (config.json or a <name>.json key file)
|
|
240
|
+
* so that a concurrent reader always sees either the previous complete file
|
|
241
|
+
* or the new complete file, never a truncated one: write to a pid-suffixed
|
|
242
|
+
* temp file, pin its mode to 0600 on the fd (writeFileSync's mode option is
|
|
243
|
+
* filtered through the umask), then rename over the target. Mirrors the
|
|
244
|
+
* writeAtomic helpers in cost-cache.js / update-check.js, which the key files
|
|
245
|
+
* — the highest-value files this CLI owns — never got.
|
|
246
|
+
*/
|
|
247
|
+
// Every wallet-subsystem path is built from getWalletsDir() plus a name that
|
|
248
|
+
// validateWalletName() already confined to [a-zA-Z0-9_-]; this re-checks the
|
|
249
|
+
// resolved path so the helpers below can never be pointed outside that
|
|
250
|
+
// directory by a future caller.
|
|
251
|
+
function assertWalletsDirPath(filePath) {
|
|
252
|
+
const dir = path.resolve(getWalletsDir());
|
|
253
|
+
const resolved = path.resolve(filePath);
|
|
254
|
+
if (path.dirname(resolved) !== dir) {
|
|
255
|
+
throw new Error(`Refusing to access ${filePath}: not inside the wallets directory`);
|
|
256
|
+
}
|
|
257
|
+
return resolved;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export function writeWalletJsonAtomic(filePath, value) {
|
|
261
|
+
filePath = assertWalletsDirPath(filePath);
|
|
262
|
+
const tmp = `${filePath}.${process.pid}.tmp`;
|
|
263
|
+
let fd;
|
|
264
|
+
try {
|
|
265
|
+
fd = fs.openSync(tmp, 'w', 0o600);
|
|
266
|
+
fs.fchmodSync(fd, 0o600);
|
|
267
|
+
fs.writeFileSync(fd, JSON.stringify(value, null, 2));
|
|
268
|
+
fs.closeSync(fd);
|
|
269
|
+
fd = undefined;
|
|
270
|
+
fs.renameSync(tmp, filePath);
|
|
271
|
+
} catch (err) {
|
|
272
|
+
if (fd !== undefined) {
|
|
273
|
+
try { fs.closeSync(fd); } catch { /* already closed */ }
|
|
274
|
+
}
|
|
275
|
+
try { fs.unlinkSync(tmp); } catch { /* temp file may not exist */ }
|
|
276
|
+
throw err;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Read and parse a wallet-subsystem JSON file. A file that exists but does
|
|
282
|
+
* not parse (torn write, disk error, manual edit) is reported by name instead
|
|
283
|
+
* of surfacing as a bare SyntaxError from deep inside a wallet command.
|
|
284
|
+
*/
|
|
285
|
+
export function readWalletJson(filePath) {
|
|
286
|
+
const raw = fs.readFileSync(assertWalletsDirPath(filePath), 'utf8');
|
|
287
|
+
try {
|
|
288
|
+
return JSON.parse(raw);
|
|
289
|
+
} catch (err) {
|
|
290
|
+
throw new Error(`${filePath} is not valid JSON (${err.message}). Restore it from a backup before running wallet commands.`, { cause: err });
|
|
213
291
|
}
|
|
214
292
|
}
|
|
215
293
|
|
|
@@ -227,12 +305,12 @@ export function getWalletConfig() {
|
|
|
227
305
|
return { defaultWallet: null, passwordHash: null };
|
|
228
306
|
}
|
|
229
307
|
warnIfInsecurePerms(getWalletConfigPath());
|
|
230
|
-
return
|
|
308
|
+
return readWalletJson(getWalletConfigPath());
|
|
231
309
|
}
|
|
232
310
|
|
|
233
311
|
function saveWalletConfig(config) {
|
|
234
312
|
ensureWalletsDir();
|
|
235
|
-
|
|
313
|
+
writeWalletJsonAtomic(getWalletConfigPath(), config);
|
|
236
314
|
}
|
|
237
315
|
|
|
238
316
|
const WALLET_NAME_RE = /^[a-zA-Z0-9_-]{1,64}$/;
|
|
@@ -390,17 +468,27 @@ export function listWallets() {
|
|
|
390
468
|
const config = getWalletConfig();
|
|
391
469
|
const files = fs.readdirSync(getWalletsDir()).filter(f => f.endsWith('.json') && f !== 'config.json');
|
|
392
470
|
|
|
393
|
-
const wallets =
|
|
394
|
-
|
|
395
|
-
|
|
471
|
+
const wallets = [];
|
|
472
|
+
for (const f of files) {
|
|
473
|
+
const filePath = path.join(getWalletsDir(), f);
|
|
474
|
+
let data;
|
|
475
|
+
try {
|
|
476
|
+
data = readWalletJson(filePath);
|
|
477
|
+
} catch (err) {
|
|
478
|
+
// One damaged file must not hide every other wallet — report it and
|
|
479
|
+
// keep listing the rest.
|
|
480
|
+
console.error(`⚠️ Skipping ${filePath}: ${err.message}`);
|
|
481
|
+
continue;
|
|
482
|
+
}
|
|
483
|
+
wallets.push({
|
|
396
484
|
name: data.name,
|
|
397
485
|
provider: data.provider || 'local',
|
|
398
486
|
evm: data.evm?.address || null,
|
|
399
487
|
solana: data.solana?.address || null,
|
|
400
488
|
createdAt: data.createdAt,
|
|
401
489
|
isDefault: data.name === config.defaultWallet,
|
|
402
|
-
};
|
|
403
|
-
}
|
|
490
|
+
});
|
|
491
|
+
}
|
|
404
492
|
|
|
405
493
|
return { wallets, defaultWallet: config.defaultWallet };
|
|
406
494
|
}
|
|
@@ -432,7 +520,7 @@ export function createWallet(name, password) {
|
|
|
432
520
|
.filter(f => f.endsWith('.json') && f !== 'config.json')
|
|
433
521
|
.filter(f => {
|
|
434
522
|
try {
|
|
435
|
-
const data =
|
|
523
|
+
const data = readWalletJson(path.join(walletsDir, f));
|
|
436
524
|
return !data.provider || data.provider === 'local';
|
|
437
525
|
} catch { return true; }
|
|
438
526
|
});
|
|
@@ -461,7 +549,7 @@ export function createWallet(name, password) {
|
|
|
461
549
|
},
|
|
462
550
|
};
|
|
463
551
|
|
|
464
|
-
|
|
552
|
+
writeWalletJsonAtomic(walletFile, wallet);
|
|
465
553
|
|
|
466
554
|
// Set as default if it's the first wallet
|
|
467
555
|
if (!config.defaultWallet) {
|
|
@@ -483,7 +571,7 @@ export function createWallet(name, password) {
|
|
|
483
571
|
export function showWallet(name) {
|
|
484
572
|
const walletFile = requireWalletFile(name);
|
|
485
573
|
|
|
486
|
-
const data =
|
|
574
|
+
const data = readWalletJson(walletFile);
|
|
487
575
|
const config = getWalletConfig();
|
|
488
576
|
const isPrivy = data.provider === 'privy';
|
|
489
577
|
|
|
@@ -509,7 +597,7 @@ export function showWallet(name) {
|
|
|
509
597
|
export function exportWallet(name, password) {
|
|
510
598
|
const walletFile = requireWalletFile(name);
|
|
511
599
|
|
|
512
|
-
const data =
|
|
600
|
+
const data = readWalletJson(walletFile);
|
|
513
601
|
if (data.provider && data.provider !== 'local') {
|
|
514
602
|
throw new Error(`${data.provider} wallets don't support key export. Keys are managed by the provider.`);
|
|
515
603
|
}
|
|
@@ -551,7 +639,7 @@ export function setDefaultWallet(name) {
|
|
|
551
639
|
export async function deleteWallet(name, password) {
|
|
552
640
|
const walletFile = requireWalletFile(name);
|
|
553
641
|
|
|
554
|
-
const data =
|
|
642
|
+
const data = readWalletJson(walletFile);
|
|
555
643
|
const config = getWalletConfig();
|
|
556
644
|
|
|
557
645
|
if (data.provider && data.provider !== 'local') {
|
|
@@ -564,7 +652,9 @@ export async function deleteWallet(name, password) {
|
|
|
564
652
|
|
|
565
653
|
fs.unlinkSync(walletFile);
|
|
566
654
|
|
|
567
|
-
const remaining = fs.readdirSync(getWalletsDir())
|
|
655
|
+
const remaining = fs.readdirSync(getWalletsDir())
|
|
656
|
+
.filter(f => f.endsWith('.json') && f !== 'config.json')
|
|
657
|
+
.filter(f => { try { readWalletJson(path.join(getWalletsDir(), f)); return true; } catch { return false; } });
|
|
568
658
|
|
|
569
659
|
if (remaining.length === 0) {
|
|
570
660
|
config.defaultWallet = null;
|
|
@@ -580,6 +670,25 @@ export async function deleteWallet(name, password) {
|
|
|
580
670
|
|
|
581
671
|
// ============= CLI Command Builder =============
|
|
582
672
|
|
|
673
|
+
/**
|
|
674
|
+
* Every `nansen wallet` subcommand the dispatcher below accepts, in the order
|
|
675
|
+
* they are advertised to users. `help` is deliberately absent: it is the
|
|
676
|
+
* fallback, not a capability. The top-level help banner builds its wallet line
|
|
677
|
+
* from this list, and command-surface.test.js checks the handlers, README and
|
|
678
|
+
* src/schema.json against it so the four cannot drift apart.
|
|
679
|
+
*/
|
|
680
|
+
export const WALLET_SUBCOMMANDS = [
|
|
681
|
+
'create',
|
|
682
|
+
'list',
|
|
683
|
+
'show',
|
|
684
|
+
'export',
|
|
685
|
+
'default',
|
|
686
|
+
'delete',
|
|
687
|
+
'send',
|
|
688
|
+
'forget-password',
|
|
689
|
+
'secure',
|
|
690
|
+
];
|
|
691
|
+
|
|
583
692
|
/**
|
|
584
693
|
* Build wallet command handlers for integration into CLI.
|
|
585
694
|
*/
|
|
@@ -759,7 +868,45 @@ export function buildWalletCommands(deps = {}) {
|
|
|
759
868
|
'export': async () => {
|
|
760
869
|
const name = options.name || args[1];
|
|
761
870
|
if (!name) {
|
|
762
|
-
throw new CommandError('Usage: nansen wallet export <name>', 'MISSING_ARGS');
|
|
871
|
+
throw new CommandError('Usage: nansen wallet export <name> [--reveal | --file <path>]', 'MISSING_ARGS');
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
// Bare `--file` parses as flags.file, a repeated or JSON-array `--file`
|
|
875
|
+
// arrives as a non-string, and `--file ""` (an unset shell variable) is
|
|
876
|
+
// an empty path that would only fail at open time — reject all of them
|
|
877
|
+
// before any secret is decrypted.
|
|
878
|
+
const wantsFile = options.file !== undefined || flags.file;
|
|
879
|
+
if (wantsFile && (typeof options.file !== 'string' || options.file === '')) {
|
|
880
|
+
throw new CommandError('--file requires a path: nansen wallet export <name> --file <path>', 'INVALID_INPUT');
|
|
881
|
+
}
|
|
882
|
+
if (wantsFile && flags.reveal) {
|
|
883
|
+
throw new CommandError('Choose one of --reveal or --file <path>, not both.', 'INVALID_INPUT');
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
// Default: redacted. No decryption, no password — secrets never
|
|
887
|
+
// materialize unless the caller explicitly asked for them.
|
|
888
|
+
if (!flags.reveal && !wantsFile) {
|
|
889
|
+
try {
|
|
890
|
+
const result = showWallet(name);
|
|
891
|
+
if (result.provider !== 'local') {
|
|
892
|
+
throw new Error(`${result.provider} wallets don't support key export. Keys are managed by the provider.`);
|
|
893
|
+
}
|
|
894
|
+
log(`\n Wallet "${result.name}" — private keys are NOT shown by default.\n`);
|
|
895
|
+
log(` EVM:`);
|
|
896
|
+
log(` Address: ${result.evm}`);
|
|
897
|
+
log(` Private Key: [REDACTED]`);
|
|
898
|
+
log(` Solana:`);
|
|
899
|
+
log(` Address: ${result.solana}`);
|
|
900
|
+
log(` Private Key: [REDACTED]`);
|
|
901
|
+
log('');
|
|
902
|
+
log(' To export the private keys:');
|
|
903
|
+
log(` nansen wallet export ${result.name} --file <path> safer: writes a file only you can read (0600)`);
|
|
904
|
+
log(` nansen wallet export ${result.name} --reveal prints them in plaintext to stdout`);
|
|
905
|
+
log('');
|
|
906
|
+
return;
|
|
907
|
+
} catch (err) {
|
|
908
|
+
throw new CommandError(`❌ ${err.message}`, 'EXPORT_FAILED');
|
|
909
|
+
}
|
|
763
910
|
}
|
|
764
911
|
|
|
765
912
|
const config = getWalletConfig();
|
|
@@ -769,6 +916,69 @@ export function buildWalletCommands(deps = {}) {
|
|
|
769
916
|
}
|
|
770
917
|
try {
|
|
771
918
|
const result = exportWallet(name, password);
|
|
919
|
+
|
|
920
|
+
if (wantsFile) {
|
|
921
|
+
// Exclusive create first, write second: unlink-on-failure below
|
|
922
|
+
// is only safe on a file THIS invocation created — a blind 'wx'
|
|
923
|
+
// writeFileSync can fail (e.g. EMFILE) without telling us whether
|
|
924
|
+
// the path pre-existed. Failures are thrown as CommandErrors with
|
|
925
|
+
// purpose-specific codes (FILE_EXISTS / FILE_WRITE_FAILED) so agents
|
|
926
|
+
// branch on the code instead of the message; the raw fs error
|
|
927
|
+
// (key-free, but noisy) stays attached as `cause`, out of the envelope.
|
|
928
|
+
let fd;
|
|
929
|
+
try {
|
|
930
|
+
fd = fs.openSync(options.file, 'wx', 0o600);
|
|
931
|
+
} catch (err) {
|
|
932
|
+
if (err.code === 'EEXIST' || err.code === 'EISDIR') {
|
|
933
|
+
// Linux reports an existing directory (or symlink) as EEXIST; macOS
|
|
934
|
+
// can report a directory as EISDIR. Both mean "already there", so
|
|
935
|
+
// neither advises deleting it.
|
|
936
|
+
throw new CommandError(`Path already exists: ${options.file} — refusing to overwrite. Choose a path that does not exist yet.`, 'FILE_EXISTS', null, { cause: err });
|
|
937
|
+
}
|
|
938
|
+
throw new CommandError(`Could not create ${options.file} (${err.code || 'open failed'}). Nothing was written.`, 'FILE_WRITE_FAILED', null, { cause: err });
|
|
939
|
+
}
|
|
940
|
+
// Linear lifecycle: pin the mode, exactly one write attempt,
|
|
941
|
+
// exactly one close attempt (a failed closeSync may still have
|
|
942
|
+
// released the fd, so it is never retried), then a single
|
|
943
|
+
// failure gate.
|
|
944
|
+
let ioErr = null;
|
|
945
|
+
try {
|
|
946
|
+
// The 0o600 passed to openSync is filtered through the process
|
|
947
|
+
// umask (a 0277 umask leaves 0400), so pin the final mode on
|
|
948
|
+
// the fd we own. Runs before any key bytes land, so a failure
|
|
949
|
+
// here takes the same unlink path as a failed write.
|
|
950
|
+
fs.fchmodSync(fd, 0o600);
|
|
951
|
+
fs.writeFileSync(fd, JSON.stringify(result, null, 2) + '\n');
|
|
952
|
+
} catch (err) {
|
|
953
|
+
ioErr = err;
|
|
954
|
+
}
|
|
955
|
+
try {
|
|
956
|
+
fs.closeSync(fd);
|
|
957
|
+
} catch (err) {
|
|
958
|
+
ioErr = ioErr || err;
|
|
959
|
+
}
|
|
960
|
+
if (ioErr) {
|
|
961
|
+
// A failure mid-write or at close (e.g. ENOSPC) can leave a
|
|
962
|
+
// partial file holding key fragments — remove what we created.
|
|
963
|
+
let disk = 'Nothing was left on disk.';
|
|
964
|
+
try {
|
|
965
|
+
fs.unlinkSync(options.file);
|
|
966
|
+
} catch (rmErr) {
|
|
967
|
+
if (rmErr.code !== 'ENOENT') {
|
|
968
|
+
disk = `A partial file may remain at ${options.file} — delete it manually.`;
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
throw new CommandError(`Could not write ${options.file} (${ioErr.code || 'write failed'}). ${disk}`, 'FILE_WRITE_FAILED', null, { cause: ioErr });
|
|
972
|
+
}
|
|
973
|
+
log(`\n✓ Private keys for "${result.name}" written to ${options.file} (permissions 0600).`);
|
|
974
|
+
log(' Delete the file as soon as the keys are imported elsewhere.');
|
|
975
|
+
log('');
|
|
976
|
+
return;
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
if (deps.isTTY ?? process.stdout.isTTY) {
|
|
980
|
+
process.stderr.write('⚠️ Printing private keys to an interactive terminal. They will remain in your scrollback and may be captured by screen sharing or terminal logging. Prefer --file <path>.\n');
|
|
981
|
+
}
|
|
772
982
|
log(`\n⚠️ Private keys for "${result.name}" — do not share!\n`);
|
|
773
983
|
log(` EVM:`);
|
|
774
984
|
log(` Address: ${result.evm.address}`);
|
|
@@ -779,6 +989,9 @@ export function buildWalletCommands(deps = {}) {
|
|
|
779
989
|
log('');
|
|
780
990
|
return;
|
|
781
991
|
} catch (err) {
|
|
992
|
+
// --file failures already carry their own code; only exportWallet
|
|
993
|
+
// (decrypt / lookup) failures need the generic wrap.
|
|
994
|
+
if (err instanceof CommandError) throw err;
|
|
782
995
|
throw new CommandError(`❌ ${err.message}`, 'EXPORT_FAILED');
|
|
783
996
|
}
|
|
784
997
|
},
|
|
@@ -809,7 +1022,7 @@ export function buildWalletCommands(deps = {}) {
|
|
|
809
1022
|
// dir and cannot traverse. deleteWallet() re-validates below.
|
|
810
1023
|
let isPrivy = false;
|
|
811
1024
|
try {
|
|
812
|
-
const data =
|
|
1025
|
+
const data = readWalletJson(getWalletFile(name));
|
|
813
1026
|
if (data.provider === 'privy') isPrivy = true;
|
|
814
1027
|
} catch { /* invalid/missing name; deleteWallet will validate and throw */ }
|
|
815
1028
|
|
|
@@ -871,7 +1084,7 @@ export function buildWalletCommands(deps = {}) {
|
|
|
871
1084
|
// getWalletFile() runs validateWalletName(), confining the path to
|
|
872
1085
|
// the wallets dir; an invalid name throws and is ignored here, and
|
|
873
1086
|
// the real wallet load downstream validates again.
|
|
874
|
-
const data =
|
|
1087
|
+
const data = readWalletJson(getWalletFile(walletName));
|
|
875
1088
|
if (data.provider === 'privy') isPrivyWallet = true;
|
|
876
1089
|
}
|
|
877
1090
|
} catch { /* ignore */ }
|
|
@@ -1019,7 +1232,10 @@ COMMANDS:
|
|
|
1019
1232
|
Create a new wallet pair (EVM + Solana)
|
|
1020
1233
|
list List all wallets
|
|
1021
1234
|
show <name> Show wallet addresses
|
|
1022
|
-
export <name>
|
|
1235
|
+
export <name> [--reveal | --file <path>]
|
|
1236
|
+
Export private keys (local wallets only, requires password).
|
|
1237
|
+
Redacted by default: --reveal prints plaintext to stdout,
|
|
1238
|
+
--file writes them to a new file only you can read (0600)
|
|
1023
1239
|
default <name> Set the default wallet
|
|
1024
1240
|
delete <name> Delete a wallet
|
|
1025
1241
|
send --to <address> --amount <number> --chain <evm|solana> [--token <address>] [--wallet <name>] [--max] [--dry-run]
|
|
@@ -1037,6 +1253,8 @@ OPTIONS:
|
|
|
1037
1253
|
--token <address> Token contract/mint address (optional, sends native if omitted)
|
|
1038
1254
|
--wallet <name> Wallet to use (optional, uses default if omitted; use "walletconnect" or "wc" for WalletConnect, EVM only)
|
|
1039
1255
|
--max Send entire balance (deducts gas for native transfers)
|
|
1256
|
+
--reveal Export: print private keys in plaintext to stdout (explicit acknowledgement)
|
|
1257
|
+
--file <path> Export: write private keys to <path> (created 0600, refuses to overwrite)
|
|
1040
1258
|
--unsafe-no-password Skip encryption — private keys stored UNENCRYPTED on disk (local only)
|
|
1041
1259
|
--human Enable interactive prompts (for human terminal use only)
|
|
1042
1260
|
|
|
@@ -1060,7 +1278,9 @@ EXAMPLES:
|
|
|
1060
1278
|
NANSEN_WALLET_PASSWORD=mypass nansen wallet create --name trading
|
|
1061
1279
|
nansen wallet create --name agent-wallet --provider privy
|
|
1062
1280
|
nansen wallet list
|
|
1063
|
-
nansen wallet export trading
|
|
1281
|
+
nansen wallet export trading # redacted (addresses only)
|
|
1282
|
+
nansen wallet export trading --file backup.json # keys → 0600 file, nothing on stdout
|
|
1283
|
+
nansen wallet export trading --reveal # keys → stdout (plaintext)
|
|
1064
1284
|
nansen wallet default trading
|
|
1065
1285
|
nansen wallet send --to 0x742d35Cc... --amount 1.5 --chain evm
|
|
1066
1286
|
nansen wallet send --to 9WzDXw... --amount 0.1 --chain solana --token So11...
|
|
@@ -15,24 +15,45 @@ import { encodeApproveCalldata } from './trade-validation.js';
|
|
|
15
15
|
const SOLANA_MAINNET_CHAIN = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';
|
|
16
16
|
|
|
17
17
|
/**
|
|
18
|
-
* Extract the first JSON
|
|
19
|
-
* The CLI may print status messages before the JSON result
|
|
18
|
+
* Extract the first JSON object from walletconnect CLI output.
|
|
19
|
+
* The CLI may print status messages before the JSON result, and may
|
|
20
|
+
* pretty-print the result across several lines. Shared with the x402
|
|
21
|
+
* payment path so both read the CLI's output the same way.
|
|
20
22
|
*/
|
|
21
|
-
function parseWcJson(output) {
|
|
23
|
+
export function parseWcJson(output) {
|
|
22
24
|
const lines = output.split('\n');
|
|
23
25
|
const startIdx = lines.findIndex(l => l.trimStart().startsWith('{'));
|
|
24
26
|
if (startIdx === -1) throw new Error('No JSON output from walletconnect');
|
|
25
27
|
|
|
26
|
-
// Handle multi-line JSON: collect lines until braces balance
|
|
27
|
-
|
|
28
|
+
// Handle multi-line JSON: collect lines until braces balance. A brace
|
|
29
|
+
// inside a string value ("... retried } ok") is not structural, so track
|
|
30
|
+
// string and escape state while scanning — counting it would end the object
|
|
31
|
+
// early and fail to parse a perfectly valid result.
|
|
32
|
+
let depth = 0;
|
|
33
|
+
let inString = false;
|
|
34
|
+
let escaped = false;
|
|
28
35
|
const jsonLines = [];
|
|
29
36
|
for (let i = startIdx; i < lines.length; i++) {
|
|
30
37
|
jsonLines.push(lines[i]);
|
|
31
38
|
for (const ch of lines[i]) {
|
|
32
|
-
if (
|
|
33
|
-
|
|
39
|
+
if (escaped) {
|
|
40
|
+
escaped = false;
|
|
41
|
+
} else if (inString) {
|
|
42
|
+
if (ch === '\\') escaped = true;
|
|
43
|
+
else if (ch === '"') inString = false;
|
|
44
|
+
} else if (ch === '"') {
|
|
45
|
+
inString = true;
|
|
46
|
+
} else if (ch === '{') {
|
|
47
|
+
depth++;
|
|
48
|
+
} else if (ch === '}') {
|
|
49
|
+
depth--;
|
|
50
|
+
}
|
|
34
51
|
}
|
|
35
|
-
|
|
52
|
+
// A JSON string cannot contain a raw newline, so any unterminated quote is
|
|
53
|
+
// a line-local anomaly rather than a string continuing onto the next line.
|
|
54
|
+
inString = false;
|
|
55
|
+
escaped = false;
|
|
56
|
+
if (depth === 0) break;
|
|
36
57
|
}
|
|
37
58
|
return JSON.parse(jsonLines.join('\n'));
|
|
38
59
|
}
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
import crypto from 'crypto';
|
|
9
9
|
import { NansenError, ErrorCode } from './api.js';
|
|
10
10
|
import { wcExec } from './walletconnect-exec.js';
|
|
11
|
-
import { getWalletConnectAddress } from './walletconnect-trading.js';
|
|
11
|
+
import { getWalletConnectAddress, parseWcJson } from './walletconnect-trading.js';
|
|
12
12
|
import { evaluatePaymentRequirement, resolvePaymentAmount, resolvePayTo } from './x402-policy.js';
|
|
13
13
|
|
|
14
14
|
/**
|
|
@@ -201,10 +201,14 @@ export async function handleX402Payment(paymentRequirements) {
|
|
|
201
201
|
let signResult;
|
|
202
202
|
try {
|
|
203
203
|
const output = await wcExec('walletconnect', ['sign-typed-data', typedDataJson], 120000);
|
|
204
|
-
// walletconnect may print status messages before the
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
204
|
+
// walletconnect may print status messages before the result and may
|
|
205
|
+
// pretty-print it over several lines. Reading only the first line that
|
|
206
|
+
// starts with "{" used to throw on a multi-line result — after the user
|
|
207
|
+
// had already approved and signed the payment in their wallet.
|
|
208
|
+
signResult = parseWcJson(output);
|
|
209
|
+
if (typeof signResult?.signature !== 'string' || signResult.signature.length === 0) {
|
|
210
|
+
throw new Error('walletconnect sign-typed-data returned no signature');
|
|
211
|
+
}
|
|
208
212
|
} catch (err) {
|
|
209
213
|
throw new NansenError(
|
|
210
214
|
`x402 payment signing failed: ${err.message}`,
|