nansen-cli 2.4.0 → 2.6.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.
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Flag names for telemetry events.
3
+ *
4
+ * The argument parser turns a dash-leading value given as a separate argument
5
+ * (`--webhook-secret -abc123`) into a flag named after the value. Telemetry
6
+ * therefore sends only option names the CLI defines for the command being run
7
+ * and replaces every other name with a fixed placeholder, so no user-supplied
8
+ * text can reach analytics through the `flags` list.
9
+ */
10
+
11
+ import { resolveResearchCommand } from './input-validation.js';
12
+
13
+ export const UNKNOWN_FLAG = '--<unknown>';
14
+
15
+ // Single-letter switches the CLI reads directly (help, version, pretty, table,
16
+ // stream, yes). They are not listed as options in the schema.
17
+ const SHORT_SWITCHES = ['h', 'v', 'p', 't', 's', 'y'];
18
+
19
+ // Deprecated top-level commands that run a `trade` subcommand.
20
+ const TRADE_SHORTCUTS = new Set(['quote', 'execute', 'bridge-status']);
21
+
22
+ function addOptionNames(known, options) {
23
+ if (!options || typeof options !== 'object') return;
24
+ for (const [name, spec] of Object.entries(options)) {
25
+ known.add(name);
26
+ if (Array.isArray(spec?.aliases)) {
27
+ for (const alias of spec.aliases) known.add(alias);
28
+ }
29
+ }
30
+ }
31
+
32
+ /** Schema entry for the command line, or null when none matches. */
33
+ function schemaLeaf(schema, command, subArgs) {
34
+ try {
35
+ const research = resolveResearchCommand(schema, command, subArgs);
36
+ if (research) return research.leaf;
37
+ } catch {
38
+ // Unknown research category or subcommand: fall through to the plain walk.
39
+ }
40
+ let node = null;
41
+ let path = subArgs;
42
+ if (Object.hasOwn(schema.commands, command)) {
43
+ node = schema.commands[command];
44
+ } else if (TRADE_SHORTCUTS.has(command) && schema.commands.trade?.subcommands) {
45
+ node = schema.commands.trade;
46
+ path = [command, ...subArgs];
47
+ }
48
+ for (const arg of path) {
49
+ const subs = node?.subcommands;
50
+ if (!subs || typeof arg !== 'string' || !Object.hasOwn(subs, arg)) break;
51
+ node = subs[arg];
52
+ }
53
+ return node;
54
+ }
55
+
56
+ /**
57
+ * Option names (without dashes) that telemetry may report for this command:
58
+ * the matched schema entry's options, the global options and the CLI's own
59
+ * valueless switches.
60
+ */
61
+ export function knownTelemetryFlags(schema, command, subArgs = [], switches = []) {
62
+ const known = new Set([...switches, ...SHORT_SWITCHES]);
63
+ addOptionNames(known, schema.globalOptions);
64
+ addOptionNames(known, schemaLeaf(schema, command, subArgs)?.options);
65
+ return known;
66
+ }
67
+
68
+ /**
69
+ * Map `--name` entries to themselves when the CLI defines them for this
70
+ * command, and to UNKNOWN_FLAG otherwise.
71
+ */
72
+ export function telemetryFlagNames({ schema, command, subArgs = [], switches = [] }, names) {
73
+ const known = knownTelemetryFlags(schema, command, subArgs, switches);
74
+ return names.map(name => (known.has(String(name).replace(/^--/, '')) ? name : UNKNOWN_FLAG));
75
+ }
package/src/trading.js CHANGED
@@ -322,10 +322,14 @@ function fromStandardResponse(body, chainType) {
322
322
  * `ambiguousBroadcast` is the default for every failure after the signed payload
323
323
  * is handed to fetch. An HTTP status describes the response, not whether the
324
324
  * backend forwarded the transaction before producing it: 408/429 and even an
325
- * intermediary-generated 400/409 can arrive after processing began. Until the
326
- * execute API has a documented, authenticated field that explicitly guarantees
327
- * pre-broadcast rejection, no response from this endpoint may authorize signing
328
- * the next candidate.
325
+ * intermediary-generated 400/409 can arrive after processing began, so no
326
+ * non-2xx response may authorize signing the next candidate.
327
+ *
328
+ * The one exception is the standard route's documented pre-broadcast rejection:
329
+ * a 400 carrying a code from STANDARD_PRE_BROADCAST_CODES and no transaction
330
+ * identifier (see isStandardPreBroadcastRejection). That is the same "failed, no
331
+ * transaction" statement the route makes in a 200 body, so it gets the same
332
+ * treatment.
329
333
  */
330
334
  function ambiguousBroadcast(message, { status, details } = {}) {
331
335
  // Deliberately never carries broadcastRuledOut. BROADCAST_FAILED is classified
@@ -333,6 +337,49 @@ function ambiguousBroadcast(message, { status, details } = {}) {
333
337
  return Object.assign(new Error(message), { code: 'BROADCAST_FAILED', status, details });
334
338
  }
335
339
 
340
+ /**
341
+ * Codes the trading API documents as returned before any broadcast on
342
+ * `/execution/standard`. The route answers them as `400 { code, message }` and
343
+ * releases its single-flight lock on the quote, because the swap never left the
344
+ * backend. Kept as an explicit list rather than a pattern: adding a code here
345
+ * lets the candidate loop sign the next quote after it, so it must be a
346
+ * deliberate edit drawn from the API's own published list.
347
+ *
348
+ * A subset of that list, not a copy. `APPROVAL_BROADCAST_FAILED` is left out:
349
+ * the API returns it only when an approval is bundled into the request, and the
350
+ * CLI never bundles one (approvals go out as their own executeTransaction
351
+ * call). The code also says the swap was not sent, not that the approval was
352
+ * not: the API notes the approval may still sit in a mempool. A response with
353
+ * it is therefore unexpected here and stays ambiguous.
354
+ */
355
+ const STANDARD_PRE_BROADCAST_CODES = Object.freeze([
356
+ 'QUOTE_EXPIRED',
357
+ 'INPUT_TRANSFER_FAILED',
358
+ 'SIMULATION_FAILED',
359
+ 'SIMULATION_MIN_RETURN_NOT_REACHED',
360
+ 'INSUFFICIENT_BALANCE',
361
+ ]);
362
+
363
+ const isAbsentTxId = (value) => value === undefined || value === null || value === '';
364
+
365
+ /**
366
+ * True only for the standard route's documented "never broadcast" answer: a 400
367
+ * whose JSON body names a listed code, carries no transaction identifier and
368
+ * has no `success` other than `false`. Anything short of all of that stays ambiguous.
369
+ */
370
+ function isStandardPreBroadcastRejection(status, parsed, body) {
371
+ return status === 400
372
+ && parsed
373
+ && isReadableBody(body)
374
+ && typeof body.code === 'string'
375
+ && STANDARD_PRE_BROADCAST_CODES.includes(body.code)
376
+ && isAbsentTxId(body.txHash)
377
+ && isAbsentTxId(body.signature)
378
+ // The documented body has no `success`; an explicit `false` says the same.
379
+ // Any other value is not this shape, so it stays ambiguous.
380
+ && (body.success === undefined || body.success === false);
381
+ }
382
+
336
383
  /**
337
384
  * A JSON body the branches below can read fields off. JSON.parse also succeeds
338
385
  * on `null`, an array and a bare string or number, none of which carry the
@@ -524,10 +571,26 @@ export async function executeTransaction(params, { retries = 2, retryDelayMs = 1
524
571
  );
525
572
  }
526
573
 
527
- // A non-2xx status does not prove the signed transaction stayed put. The
528
- // backend or an intermediary may have produced the response after forwarding
529
- // it, so preserve any structured error only as diagnostic detail and fail
530
- // closed. Do not allow the candidate loop to sign another transaction.
574
+ // The standard route's documented pre-broadcast rejection. Returned as the
575
+ // same "Failed, no hash" result a 200 `success: false` body produces, so the
576
+ // candidate loop releases the claim and tries the next quote exactly as it
577
+ // already does for that body.
578
+ //
579
+ // First attempt only: a retry follows a 5xx or a dropped connection whose
580
+ // outcome is unknown, and a later "never broadcast" speaks for the retry,
581
+ // not for the earlier POST that may have gone out.
582
+ if (isStandard && attempt === 0 && isStandardPreBroadcastRejection(res.status, parsed, body)) {
583
+ return fromStandardResponse(
584
+ { ...body, success: false, txHash: undefined, signature: undefined },
585
+ chainConfigFor(params.chain)?.type,
586
+ );
587
+ }
588
+
589
+ // Every other non-2xx status does not prove the signed transaction stayed
590
+ // put. The backend or an intermediary may have produced the response after
591
+ // forwarding it, so preserve any structured error only as diagnostic detail
592
+ // and fail closed. Do not allow the candidate loop to sign another
593
+ // transaction.
531
594
  if (!res.ok) {
532
595
  const readableBody = parsed && isReadableBody(body);
533
596
  throw ambiguousBroadcast(
package/src/transfer.js CHANGED
@@ -46,6 +46,49 @@ function validateSolanaAddress(address) {
46
46
  } catch { return { valid: false, error: 'Invalid Solana address' }; }
47
47
  }
48
48
 
49
+ // ============= Token Symbols =============
50
+
51
+ // Well-known stablecoin symbols `wallet send --token` accepts in place of a
52
+ // contract address or mint, per chain the command supports. `evm` signs for
53
+ // chain ID 1, so it takes the Ethereum addresses. Base and Solana match the
54
+ // `trade` symbol map (trading.js TOKEN_SYMBOLS), so a symbol means the same
55
+ // token in both commands.
56
+ const ETHEREUM_STABLECOINS = {
57
+ USDC: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
58
+ USDT: '0xdAC17F958D2ee523a2206206994597C13D831ec7',
59
+ };
60
+ const SEND_TOKEN_SYMBOLS = {
61
+ ethereum: ETHEREUM_STABLECOINS,
62
+ evm: ETHEREUM_STABLECOINS,
63
+ base: {
64
+ USDC: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
65
+ USDT: '0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2',
66
+ },
67
+ solana: {
68
+ USDC: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
69
+ USDT: 'Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB',
70
+ },
71
+ };
72
+
73
+ /**
74
+ * Turn a `--token` value into a token address for `chain`. A known symbol
75
+ * (case-insensitive) maps to its address; an address passes through as given.
76
+ * Anything else fails here, before an RPC call, instead of reaching the node as
77
+ * a malformed address (which answered with a bare "Invalid params").
78
+ */
79
+ function resolveSendToken(token, chain) {
80
+ if (token == null) return null;
81
+ const symbols = SEND_TOKEN_SYMBOLS[chain] || {};
82
+ const known = symbols[String(token).toUpperCase()];
83
+ if (known) return known;
84
+ const check = chain === 'solana' ? validateSolanaAddress(token) : validateEvmAddress(token);
85
+ if (check.valid) return token;
86
+ const kind = chain === 'solana' ? 'mint address' : 'contract address';
87
+ const names = Object.keys(symbols);
88
+ const choices = names.length ? `, or one of: ${names.join(', ')}` : '';
89
+ throw new Error(`Unknown token "${token}" on ${chain}. Pass the token's ${kind}${choices}. Omit --token to send the native currency.`);
90
+ }
91
+
49
92
  // ============= Amount Parsing =============
50
93
 
51
94
  function parseAmount(amountStr, decimals) {
@@ -80,7 +123,7 @@ function formatAmount(rawAmount, decimals) {
80
123
 
81
124
  // ============= RPC =============
82
125
 
83
- async function rpcCall(url, method, params = []) {
126
+ async function rpcCall(url, method, params = [], context = {}) {
84
127
  const response = await fetch(url, {
85
128
  method: 'POST',
86
129
  headers: { 'Content-Type': 'application/json' },
@@ -88,7 +131,7 @@ async function rpcCall(url, method, params = []) {
88
131
  });
89
132
  const data = await response.json();
90
133
  if (data.error) {
91
- const err = new Error(friendlyRpcError(data.error, method));
134
+ const err = new Error(friendlyRpcError(data.error, method, context));
92
135
  // Classified from the raw RPC text, before any rewording, so callers can
93
136
  // branch on it without depending on the friendly message's wording.
94
137
  err.transactionWouldFail = isTransactionFailureMessage(data.error);
@@ -119,8 +162,11 @@ function isTransactionFailureMessage(error) {
119
162
  * geth rejects an underfunded transaction with "insufficient funds for gas *
120
163
  * price + value", which used to match the Solana branch and tell a Base or
121
164
  * Ethereum user to top up SOL.
165
+ *
166
+ * `context.nativeSolSend` marks the broadcast of a plain SOL transfer, the only
167
+ * transaction whose account indices this function can interpret.
122
168
  */
123
- function friendlyRpcError(error, method = '') {
169
+ function friendlyRpcError(error, method = '', context = {}) {
124
170
  const msg = error.message || JSON.stringify(error);
125
171
  const lower = msg.toLowerCase();
126
172
  const isEvm = typeof method === 'string' && method.toLowerCase().startsWith('eth_');
@@ -131,6 +177,17 @@ function friendlyRpcError(error, method = '') {
131
177
  if (lower.includes('no record of a prior credit') || lower.includes('accountnotfound')) {
132
178
  return 'Insufficient SOL for transaction fees. Send at least 0.01 SOL to your wallet.';
133
179
  }
180
+ // Solana names the account short of rent by its index in the transaction.
181
+ // Index 0 is this wallet (the fee payer), where topping up is the fix. In a
182
+ // native SOL send any other index is the recipient, which as a new address
183
+ // must receive at least the rent-exempt minimum, so adding SOL to the wallet
184
+ // would not help. SPL transfers lay out their accounts differently (ATAs,
185
+ // mint, token program), so they keep the generic advice below.
186
+ const rentAccount = context.nativeSolSend
187
+ && lower.match(/results in an account \((\d+)\) with insufficient funds for rent/);
188
+ if (rentAccount && rentAccount[1] !== '0') {
189
+ return `The transfer would leave account ${rentAccount[1]} (the recipient of a SOL send) below Solana's rent-exempt minimum. A new address must receive at least 0.00089088 SOL. RPC said: ${msg}`;
190
+ }
134
191
  if (lower.includes('insufficient lamports') || lower.includes('insufficient funds')) {
135
192
  return 'Insufficient SOL balance for this transaction. Top up your wallet with SOL.';
136
193
  }
@@ -293,15 +350,18 @@ async function buildEvmTransaction({ to, amount, token, privateKey, chain, max =
293
350
  }
294
351
 
295
352
  // RLP: [chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, accessList]
353
+ // `to` and `data` are byte strings, not integers: pass Buffers so rlpEncode
354
+ // keeps their leading zero bytes (a hex string has them stripped, which
355
+ // shortened an address such as 0x0000000000085d47... below 20 bytes).
296
356
  const txFields = [
297
357
  bigIntToHex(BigInt(chainId)),
298
358
  bigIntToHex(nonce),
299
359
  bigIntToHex(maxPriorityFee),
300
360
  bigIntToHex(maxFee),
301
361
  bigIntToHex(gasLimit),
302
- txTo,
362
+ Buffer.from(txTo.replace(/^0x/, ''), 'hex'),
303
363
  bigIntToHex(txValue),
304
- txData.length > 0 ? '0x' + txData.toString('hex') : '0x',
364
+ txData,
305
365
  [], // accessList
306
366
  ];
307
367
 
@@ -644,20 +704,20 @@ async function validateErc20Token(rpcUrl, tokenAddress) {
644
704
 
645
705
  // ============= Broadcasting =============
646
706
 
647
- async function broadcastTransaction(signedTx, chain) {
707
+ async function broadcastTransaction(signedTx, chain, token = null) {
648
708
  if (chain === 'solana') {
649
709
  return rpcCall(CHAIN_RPCS.solana, 'sendTransaction', [signedTx, {
650
710
  encoding: 'base64',
651
711
  skipPreflight: false,
652
712
  preflightCommitment: 'confirmed',
653
- }]);
713
+ }], { nativeSolSend: !token });
654
714
  }
655
715
  return rpcCall(CHAIN_RPCS[chain] || CHAIN_RPCS.evm, 'eth_sendRawTransaction', [signedTx]);
656
716
  }
657
717
 
658
718
  // ============= Public API =============
659
719
 
660
- export { parseAmount, formatAmount, signEd25519, encodeCompactU16, base58Decode, base58DecodePubkey, deriveATA, isOnEd25519Curve, validateEvmAddress, validateSolanaAddress, bigIntToHex };
720
+ export { parseAmount, formatAmount, signEd25519, encodeCompactU16, base58Decode, base58DecodePubkey, deriveATA, isOnEd25519Curve, validateEvmAddress, validateSolanaAddress, bigIntToHex, resolveSendToken };
661
721
 
662
722
  /**
663
723
  * Send tokens via Privy server wallet. EVM uses Privy's sendTransaction (handles gas/nonce).
@@ -700,7 +760,7 @@ async function sendTokensViaPrivy({ to, amount, chain, token, max, dryRun, walle
700
760
 
701
761
  const signResult = await client.signSolanaTransaction(walletId, unsignedTransaction);
702
762
  const signedTx = signResult.data?.signed_transaction || signResult.signed_transaction;
703
- const txHash = await broadcastTransaction(signedTx, chain);
763
+ const txHash = await broadcastTransaction(signedTx, chain, token);
704
764
  const confirmation = await waitForSolanaConfirmation(CHAIN_RPCS.solana, txHash);
705
765
 
706
766
  return {
@@ -779,6 +839,7 @@ export async function sendTokens({ to, amount, chain, token = null, wallet = nul
779
839
  const validate = chain === 'solana' ? validateSolanaAddress : validateEvmAddress;
780
840
  const v = validate(to);
781
841
  if (!v.valid) throw new Error(`Invalid recipient: ${v.error}`);
842
+ token = resolveSendToken(token, chain);
782
843
 
783
844
  if (walletconnect) {
784
845
  if (chain === 'solana') {
@@ -870,7 +931,7 @@ export async function sendTokens({ to, amount, chain, token = null, wallet = nul
870
931
  };
871
932
  }
872
933
 
873
- const txHash = await broadcastTransaction(result.signedTransaction, chain);
934
+ const txHash = await broadcastTransaction(result.signedTransaction, chain, token);
874
935
 
875
936
  // Wait for confirmation
876
937
  let confirmation;
@@ -998,7 +1059,7 @@ async function sendTokensViaWalletConnect({ to, amount, chain, token, max, dryRu
998
1059
 
999
1060
  const txHash = await (async () => {
1000
1061
  if (wcResult.txHash) return wcResult.txHash;
1001
- if (wcResult.signedTransaction) return broadcastTransaction(wcResult.signedTransaction, chain);
1062
+ if (wcResult.signedTransaction) return broadcastTransaction(wcResult.signedTransaction, chain, token);
1002
1063
  throw new Error('No transaction hash or signed transaction returned from WalletConnect');
1003
1064
  })();
1004
1065
 
package/src/wallet.js CHANGED
@@ -454,10 +454,19 @@ export function withWalletLock(fn, { waitMs = WALLET_LOCK_WAIT_MS } = {}) {
454
454
 
455
455
  const WALLET_NAME_RE = /^[a-zA-Z0-9_-]{1,64}$/;
456
456
 
457
- function validateWalletName(name) {
457
+ // `wallet send` and limit orders treat these as WalletConnect, so a local
458
+ // wallet with one of these names could never be selected.
459
+ const WALLETCONNECT_NAMES = new Set(['walletconnect', 'wc']);
460
+
461
+ export function validateWalletName(name, { creating = false } = {}) {
458
462
  if (!name || !WALLET_NAME_RE.test(name)) {
459
463
  throw new Error('Wallet name must be 1-64 characters: letters, numbers, hyphens, underscores only');
460
464
  }
465
+ // config.json is the wallet settings file in the same directory. Compared
466
+ // case-insensitively because the macOS and Windows filesystems are.
467
+ if (name.toLowerCase() === 'config' || (creating && WALLETCONNECT_NAMES.has(name))) {
468
+ throw new Error(`"${name}" is a reserved name and cannot be used for a wallet`);
469
+ }
461
470
  }
462
471
 
463
472
  function getWalletFile(name) {
@@ -638,6 +647,7 @@ export function listWallets() {
638
647
  * the CLI saves the password there so a racing create can't overwrite it.
639
648
  */
640
649
  export function createWallet(name, password, { beforeCommit } = {}) {
650
+ validateWalletName(name, { creating: true });
641
651
  const walletFile = getWalletFile(name);
642
652
  // Key generation and encryption (two scrypt runs) need no shared state, so
643
653
  // they run before the lock to keep it short.
@@ -1182,7 +1192,7 @@ export function buildWalletCommands(deps = {}) {
1182
1192
  },
1183
1193
 
1184
1194
  'send': async () => {
1185
- rejectBlankOption(options.token, 'token', '<token-address>');
1195
+ rejectBlankOption(options.token, 'token', '<symbol|address>');
1186
1196
  rejectBlankOption(options.wallet, 'wallet', '<name>');
1187
1197
  const { sendTokens } = await import('./transfer.js');
1188
1198
 
@@ -1196,7 +1206,7 @@ export function buildWalletCommands(deps = {}) {
1196
1206
  }
1197
1207
 
1198
1208
  if (!options.chain) {
1199
- throw new CommandError('--chain <evm|solana> is required', 'MISSING_ARGS');
1209
+ throw new CommandError('--chain <evm|ethereum|base|solana> is required', 'MISSING_ARGS');
1200
1210
  }
1201
1211
 
1202
1212
  if (!['evm', 'solana', 'ethereum', 'base'].includes(options.chain)) {
@@ -1252,7 +1262,7 @@ export function buildWalletCommands(deps = {}) {
1252
1262
  log(` From: ${result.from}`);
1253
1263
  log(` To: ${options.to}`);
1254
1264
  log(` Amount: ${result.amount || (isMax ? 'max' : String(options.amount))}`);
1255
- log(` Token: ${options.token || '(native)'}`);
1265
+ log(` Token: ${result.token || '(native)'}`);
1256
1266
  log(` Chain: ${options.chain}`);
1257
1267
  if (result.estimatedFee) log(` Fee: ${result.estimatedFee}`);
1258
1268
  log('');
@@ -1266,7 +1276,7 @@ export function buildWalletCommands(deps = {}) {
1266
1276
  log(` From: ${result.from}`);
1267
1277
  log(` To: ${result.to}`);
1268
1278
  log(` Amount: ${result.amount}`);
1269
- log(` Token: ${result.token}`);
1279
+ log(` Token: ${result.token || '(native)'}`);
1270
1280
  if (result.blockNumber) log(` Block: ${result.blockNumber}`);
1271
1281
  log(` Status: ${result.confirmed ? 'confirmed' : 'pending'}`);
1272
1282
  log(` Explorer: ${result.explorer}`);
@@ -1363,8 +1373,15 @@ USAGE:
1363
1373
  nansen wallet <command> [options]
1364
1374
 
1365
1375
  COMMANDS:
1366
- create [--name <label>] [--provider <local|privy>] [--unsafe-no-password]
1367
- Create a new wallet pair (EVM + Solana)
1376
+ create [--name <label>] [--provider <local|privy>] [--unsafe-no-password] [--human]
1377
+ Create a new wallet pair (EVM + Solana). A local wallet needs a
1378
+ password of at least 12 characters: set NANSEN_WALLET_PASSWORD
1379
+ (a password saved by an earlier create is reused); when neither
1380
+ exists, --human prompts for one. Without one it fails with
1381
+ PASSWORD_REQUIRED (it never prompts on its own). The password is
1382
+ then saved to the OS keychain, or to ~/.nansen/wallets/.credentials
1383
+ (plaintext) when no keychain is available. If neither can be
1384
+ written, keep NANSEN_WALLET_PASSWORD set for later commands
1368
1385
  list List all wallets
1369
1386
  show <name> Show wallet addresses
1370
1387
  export <name> [--reveal | --file <path>]
@@ -1373,10 +1390,11 @@ COMMANDS:
1373
1390
  --file writes them to a new file only you can read (0600)
1374
1391
  default <name> Set the default wallet
1375
1392
  delete <name> Delete a wallet
1376
- send --to <address> --amount <number> --chain <evm|solana> [--token <address>] [--wallet <name>] [--max] [--dry-run]
1393
+ send --to <address> --amount <number> --chain <evm|ethereum|base|solana> [--token <symbol|address>] [--wallet <name>] [--max] [--dry-run]
1377
1394
  Send tokens or native currency (--max sends entire balance, --dry-run previews without sending)
1378
1395
  forget-password Remove saved password from all stores
1379
- secure Migrate password from insecure storage to OS keychain
1396
+ secure Move a password from ~/.nansen/wallets/.credentials or NANSEN_WALLET_PASSWORD
1397
+ into the OS keychain (wallet create already uses the keychain when it can)
1380
1398
 
1381
1399
  OPTIONS:
1382
1400
  --name <label> Wallet name (default: "default")
@@ -1384,19 +1402,23 @@ OPTIONS:
1384
1402
  "privy" creates server-side wallets via Privy API
1385
1403
  --to <address> Recipient address (required for send)
1386
1404
  --amount <number> Amount to send in human-readable format (required unless --max)
1387
- --chain <evm|solana> Blockchain to use (required for send)
1388
- --token <address> Token contract/mint address (optional, sends native if omitted)
1405
+ --chain <chain> Blockchain to use (required for send): evm (Ethereum), ethereum, base, solana
1406
+ --token <symbol|address> Token to send: USDC, USDT, or a token contract/mint address
1407
+ (optional, sends native if omitted)
1389
1408
  --wallet <name> Wallet to use (optional, uses default if omitted; use "walletconnect" or "wc" for WalletConnect, EVM only)
1390
1409
  --max Send entire balance (deducts gas for native transfers)
1391
1410
  --reveal Export: print private keys in plaintext to stdout (explicit acknowledgement)
1392
1411
  --file <path> Export: write private keys to <path> (created 0600, refuses to overwrite)
1393
1412
  --unsafe-no-password Skip encryption — private keys stored UNENCRYPTED on disk (local only)
1394
1413
  --human Enable interactive prompts (for human terminal use only)
1414
+ --dry-run Send: preview the transaction without broadcasting
1395
1415
 
1396
1416
  PASSWORD RESOLUTION (automatic, in order):
1397
1417
  1. NANSEN_WALLET_PASSWORD env var
1398
1418
  2. OS keychain (saved automatically on wallet create)
1399
- 3. Interactive prompt (only with --human flag)
1419
+ 3. ~/.nansen/wallets/.credentials (plaintext fallback, saved on wallet create when no
1420
+ keychain is available; run \`nansen wallet secure\` to move it to the keychain)
1421
+ 4. Interactive prompt (only with --human flag)
1400
1422
 
1401
1423
  ENVIRONMENT:
1402
1424
  NANSEN_WALLET_PASSWORD Wallet encryption password
@@ -1428,6 +1450,7 @@ EXAMPLES:
1428
1450
  nansen wallet default trading
1429
1451
  nansen wallet send --to 0x742d35Cc... --amount 1.5 --chain evm
1430
1452
  nansen wallet send --to 9WzDXw... --amount 0.1 --chain solana --token So11...
1453
+ nansen wallet send --to 0x742d35Cc... --amount 25 --chain base --token USDC
1431
1454
  nansen wallet forget-password
1432
1455
  `);
1433
1456
  return;
@@ -47,6 +47,18 @@ function parseChainId(network) {
47
47
  return match ? Number(match[1]) : null;
48
48
  }
49
49
 
50
+ // The local signer (x402-evm.js) authorizes for an hour; a server-supplied
51
+ // timeout never gets a longer window than that.
52
+ const MAX_PAYMENT_TIMEOUT_SECONDS = 3600;
53
+
54
+ function paymentTimeoutSeconds(maxTimeoutSeconds) {
55
+ const seconds = typeof maxTimeoutSeconds === 'string' && /^\d+$/.test(maxTimeoutSeconds)
56
+ ? Number(maxTimeoutSeconds)
57
+ : maxTimeoutSeconds;
58
+ if (!Number.isSafeInteger(seconds) || seconds <= 0) return 120;
59
+ return Math.min(seconds, MAX_PAYMENT_TIMEOUT_SECONDS);
60
+ }
61
+
50
62
  /**
51
63
  * Build EIP-712 typed data for TransferWithAuthorization (EIP-3009).
52
64
  */
@@ -112,7 +124,7 @@ export function buildEIP712TypedData({ fromAddress, requirement }) {
112
124
  to: payTo,
113
125
  value: amount,
114
126
  validAfter: now - 600, // 10 min in the past to tolerate clock skew between client and verifier
115
- validBefore: now + (maxTimeoutSeconds || 120),
127
+ validBefore: now + paymentTimeoutSeconds(maxTimeoutSeconds),
116
128
  nonce,
117
129
  },
118
130
  };
@@ -1,53 +0,0 @@
1
- ---
2
- name: nansen-web-fetcher
3
- description: Fetch and analyze content from one or more URLs using AI (Gemini 2.5 Flash). Use when you have specific URLs and need to extract or summarize their content. Pairs well with `nansen web search` results.
4
- metadata:
5
- openclaw:
6
- requires:
7
- bins:
8
- - nansen
9
- primaryEnv: NANSEN_API_KEY
10
- install:
11
- - kind: node
12
- package: nansen-cli
13
- bins: [nansen]
14
- allowed-tools: Bash(nansen:*)
15
- ---
16
- ## Authentication
17
-
18
- Nansen account API calls accept a selected `nansen:api` browser session or conventional API key with the same permissions. `NANSEN_API_KEY` takes precedence; optional `primaryEnv` preserves configured-key injection. Run `nansen auth status` for offline selection. Cached access expiry alone permits automatic renewal during an authorized task. Stop on anonymous selection, invalid state, blocked/uncertain renewal or actual auth failure; never drop a credential or fall back to anonymous x402 payment. Browser login does not grant wallet signing, privileged service identity or a persistent MCP integration key. Preserve all confirmation, signing, sanctions and geographic checks below. Browser login is enabled in production within the [documented platform scope](https://github.com/nansen-ai/nansen-cli/blob/main/docs/browser-login.md#preview-platform-scope).
19
-
20
-
21
-
22
- # Web Fetch
23
-
24
- Fetch and analyze content from one or more URLs using Gemini 2.5 Flash with URL context.
25
-
26
- ```bash
27
- nansen web fetch https://nansen.ai --question "What products does Nansen offer?"
28
- nansen web fetch --url https://example.com --url https://other.com --question "Compare these two sites"
29
- nansen web fetch https://docs.uniswap.org/contracts/v4/overview --question "What changed in v4?"
30
- ```
31
-
32
- Positional args and `--url` flags can be combined — all become URLs to fetch.
33
-
34
- | Flag | Values | Default | Purpose |
35
- |------|--------|---------|---------|
36
- | `--url` | URL | — | URL to fetch (repeatable for multiple URLs, up to 20) |
37
- | `--question` | string | **required** | Question to answer about the URL content |
38
- | `--pretty` | flag | off | Human-readable JSON |
39
-
40
- Returns:
41
- - `analysis` — AI-generated answer to your question
42
- - `retrieved_urls` — URLs successfully fetched
43
- - `failed_urls` — URLs that could not be retrieved
44
-
45
- **Tip:** Combine with `web search` — search first to find relevant URLs, then fetch to get full content.
46
-
47
- ```bash
48
- # Find and analyze in two steps
49
- nansen web search "uniswap v4 launch" --num-results 3 --fields link
50
- nansen web fetch https://blog.uniswap.org/... --question "What are the key changes?"
51
- ```
52
-
53
- **Note:** 30s timeout. Paywalled or bot-blocked pages may appear in `failed_urls`.