nansen-cli 2.4.0 → 2.5.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/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
  };