nansen-cli 1.44.3 → 1.46.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
@@ -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
- return BigInt(whole) * (10n ** BigInt(decimals)) + BigInt(frac);
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) {
@@ -334,7 +345,16 @@ export async function getTokenInfo(rpcUrl, mint) {
334
345
  if (!info || !info.value) throw new Error(`Token mint ${mint} not found`);
335
346
  const owner = info.value.owner;
336
347
  const decimals = info.value.data?.parsed?.info?.decimals;
337
- return { tokenProgram: owner, decimals: decimals ?? 9 };
348
+ // The decimals scale every human-readable --amount into base units, so a
349
+ // guess is never safe. When the RPC cannot jsonParse the mint (an owner
350
+ // program it does not know, or raw base64 data) the account is not a mint
351
+ // we can size a transfer for — say so instead of assuming 9 decimals.
352
+ if (!Number.isInteger(decimals) || decimals < 0) {
353
+ throw new Error(
354
+ `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.`,
355
+ );
356
+ }
357
+ return { tokenProgram: owner, decimals };
338
358
  }
339
359
 
340
360
  /**
@@ -957,7 +977,6 @@ function getExplorerUrl(chain, txHash) {
957
977
  bnb: 'https://bscscan.com/tx/',
958
978
  avalanche: 'https://snowtrace.io/tx/',
959
979
  linea: 'https://lineascan.build/tx/',
960
- scroll: 'https://scrollscan.com/tx/',
961
980
  mantle: 'https://mantlescan.xyz/tx/',
962
981
  };
963
982
  const base = explorers[chain] || explorers.ethereum;
@@ -101,10 +101,10 @@ const REGISTRY_URL = `https://registry.npmjs.org/${PACKAGE_NAME}/latest`;
101
101
  * POSIX, so a concurrent `nansen` reader always sees either the old file or the
102
102
  * fully-written new one — never a truncated/empty file.
103
103
  *
104
- * The registry URL is overridable via NANSEN_REGISTRY_URL purely as a test seam
105
- * (lets a test point the child at a local server); it defaults to npm.
104
+ * The URL is injectable as the third argument, which is how the tests point the
105
+ * child at a local server. It defaults to the npm registry.
106
106
  */
107
- export function buildCheckScript(dir, file, url = process.env.NANSEN_REGISTRY_URL || REGISTRY_URL) {
107
+ export function buildCheckScript(dir, file, url = REGISTRY_URL) {
108
108
  return `
109
109
  const url = ${JSON.stringify(url)};
110
110
  const http = require(url.startsWith('https:') ? 'https' : 'http');
@@ -112,11 +112,17 @@ export function buildCheckScript(dir, file, url = process.env.NANSEN_REGISTRY_UR
112
112
  const dir = ${JSON.stringify(dir)};
113
113
  const file = ${JSON.stringify(file)};
114
114
  const req = http.get(url, { timeout: 5000 }, (res) => {
115
+ if (res.statusCode < 200 || res.statusCode >= 300) {
116
+ res.resume();
117
+ return;
118
+ }
119
+
115
120
  let body = '';
116
121
  res.on('data', c => body += c);
117
122
  res.on('end', () => {
118
123
  try {
119
124
  const { version } = JSON.parse(body);
125
+ if (typeof version !== 'string' || version.trim() === '') return;
120
126
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { mode: 0o700, recursive: true });
121
127
  const tmp = file + '.' + process.pid + '.tmp';
122
128
  try {
package/src/wallet.js CHANGED
@@ -3,6 +3,7 @@
3
3
  * Local key generation and storage for EVM and Solana chains.
4
4
  */
5
5
 
6
+ import { rejectBlankOption } from './query-options.js';
6
7
  import crypto from 'crypto';
7
8
  import fs from 'fs';
8
9
  import path from 'path';
@@ -579,6 +580,25 @@ export async function deleteWallet(name, password) {
579
580
 
580
581
  // ============= CLI Command Builder =============
581
582
 
583
+ /**
584
+ * Every `nansen wallet` subcommand the dispatcher below accepts, in the order
585
+ * they are advertised to users. `help` is deliberately absent: it is the
586
+ * fallback, not a capability. The top-level help banner builds its wallet line
587
+ * from this list, and command-surface.test.js checks the handlers, README and
588
+ * src/schema.json against it so the four cannot drift apart.
589
+ */
590
+ export const WALLET_SUBCOMMANDS = [
591
+ 'create',
592
+ 'list',
593
+ 'show',
594
+ 'export',
595
+ 'default',
596
+ 'delete',
597
+ 'send',
598
+ 'forget-password',
599
+ 'secure',
600
+ ];
601
+
582
602
  /**
583
603
  * Build wallet command handlers for integration into CLI.
584
604
  */
@@ -588,6 +608,7 @@ export function buildWalletCommands(deps = {}) {
588
608
  return {
589
609
  'wallet': async (args, apiInstance, flags, options) => {
590
610
  const subcommand = args[0] || 'help';
611
+ if (subcommand === 'create') rejectBlankOption(options.name, 'name', '<name>');
591
612
 
592
613
  // Privy-specific: only 'create' and policy commands need --provider privy
593
614
  if (options.provider === 'privy' || process.env.NANSEN_WALLET_PROVIDER === 'privy') {
@@ -757,7 +778,45 @@ export function buildWalletCommands(deps = {}) {
757
778
  'export': async () => {
758
779
  const name = options.name || args[1];
759
780
  if (!name) {
760
- throw new CommandError('Usage: nansen wallet export <name>', 'MISSING_ARGS');
781
+ throw new CommandError('Usage: nansen wallet export <name> [--reveal | --file <path>]', 'MISSING_ARGS');
782
+ }
783
+
784
+ // Bare `--file` parses as flags.file, a repeated or JSON-array `--file`
785
+ // arrives as a non-string, and `--file ""` (an unset shell variable) is
786
+ // an empty path that would only fail at open time — reject all of them
787
+ // before any secret is decrypted.
788
+ const wantsFile = options.file !== undefined || flags.file;
789
+ if (wantsFile && (typeof options.file !== 'string' || options.file === '')) {
790
+ throw new CommandError('--file requires a path: nansen wallet export <name> --file <path>', 'INVALID_INPUT');
791
+ }
792
+ if (wantsFile && flags.reveal) {
793
+ throw new CommandError('Choose one of --reveal or --file <path>, not both.', 'INVALID_INPUT');
794
+ }
795
+
796
+ // Default: redacted. No decryption, no password — secrets never
797
+ // materialize unless the caller explicitly asked for them.
798
+ if (!flags.reveal && !wantsFile) {
799
+ try {
800
+ const result = showWallet(name);
801
+ if (result.provider !== 'local') {
802
+ throw new Error(`${result.provider} wallets don't support key export. Keys are managed by the provider.`);
803
+ }
804
+ log(`\n Wallet "${result.name}" — private keys are NOT shown by default.\n`);
805
+ log(` EVM:`);
806
+ log(` Address: ${result.evm}`);
807
+ log(` Private Key: [REDACTED]`);
808
+ log(` Solana:`);
809
+ log(` Address: ${result.solana}`);
810
+ log(` Private Key: [REDACTED]`);
811
+ log('');
812
+ log(' To export the private keys:');
813
+ log(` nansen wallet export ${result.name} --file <path> safer: writes a file only you can read (0600)`);
814
+ log(` nansen wallet export ${result.name} --reveal prints them in plaintext to stdout`);
815
+ log('');
816
+ return;
817
+ } catch (err) {
818
+ throw new CommandError(`❌ ${err.message}`, 'EXPORT_FAILED');
819
+ }
761
820
  }
762
821
 
763
822
  const config = getWalletConfig();
@@ -767,6 +826,69 @@ export function buildWalletCommands(deps = {}) {
767
826
  }
768
827
  try {
769
828
  const result = exportWallet(name, password);
829
+
830
+ if (wantsFile) {
831
+ // Exclusive create first, write second: unlink-on-failure below
832
+ // is only safe on a file THIS invocation created — a blind 'wx'
833
+ // writeFileSync can fail (e.g. EMFILE) without telling us whether
834
+ // the path pre-existed. Failures are thrown as CommandErrors with
835
+ // purpose-specific codes (FILE_EXISTS / FILE_WRITE_FAILED) so agents
836
+ // branch on the code instead of the message; the raw fs error
837
+ // (key-free, but noisy) stays attached as `cause`, out of the envelope.
838
+ let fd;
839
+ try {
840
+ fd = fs.openSync(options.file, 'wx', 0o600);
841
+ } catch (err) {
842
+ if (err.code === 'EEXIST' || err.code === 'EISDIR') {
843
+ // Linux reports an existing directory (or symlink) as EEXIST; macOS
844
+ // can report a directory as EISDIR. Both mean "already there", so
845
+ // neither advises deleting it.
846
+ throw new CommandError(`Path already exists: ${options.file} — refusing to overwrite. Choose a path that does not exist yet.`, 'FILE_EXISTS', null, { cause: err });
847
+ }
848
+ throw new CommandError(`Could not create ${options.file} (${err.code || 'open failed'}). Nothing was written.`, 'FILE_WRITE_FAILED', null, { cause: err });
849
+ }
850
+ // Linear lifecycle: pin the mode, exactly one write attempt,
851
+ // exactly one close attempt (a failed closeSync may still have
852
+ // released the fd, so it is never retried), then a single
853
+ // failure gate.
854
+ let ioErr = null;
855
+ try {
856
+ // The 0o600 passed to openSync is filtered through the process
857
+ // umask (a 0277 umask leaves 0400), so pin the final mode on
858
+ // the fd we own. Runs before any key bytes land, so a failure
859
+ // here takes the same unlink path as a failed write.
860
+ fs.fchmodSync(fd, 0o600);
861
+ fs.writeFileSync(fd, JSON.stringify(result, null, 2) + '\n');
862
+ } catch (err) {
863
+ ioErr = err;
864
+ }
865
+ try {
866
+ fs.closeSync(fd);
867
+ } catch (err) {
868
+ ioErr = ioErr || err;
869
+ }
870
+ if (ioErr) {
871
+ // A failure mid-write or at close (e.g. ENOSPC) can leave a
872
+ // partial file holding key fragments — remove what we created.
873
+ let disk = 'Nothing was left on disk.';
874
+ try {
875
+ fs.unlinkSync(options.file);
876
+ } catch (rmErr) {
877
+ if (rmErr.code !== 'ENOENT') {
878
+ disk = `A partial file may remain at ${options.file} — delete it manually.`;
879
+ }
880
+ }
881
+ throw new CommandError(`Could not write ${options.file} (${ioErr.code || 'write failed'}). ${disk}`, 'FILE_WRITE_FAILED', null, { cause: ioErr });
882
+ }
883
+ log(`\n✓ Private keys for "${result.name}" written to ${options.file} (permissions 0600).`);
884
+ log(' Delete the file as soon as the keys are imported elsewhere.');
885
+ log('');
886
+ return;
887
+ }
888
+
889
+ if (deps.isTTY ?? process.stdout.isTTY) {
890
+ 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');
891
+ }
770
892
  log(`\n⚠️ Private keys for "${result.name}" — do not share!\n`);
771
893
  log(` EVM:`);
772
894
  log(` Address: ${result.evm.address}`);
@@ -777,6 +899,9 @@ export function buildWalletCommands(deps = {}) {
777
899
  log('');
778
900
  return;
779
901
  } catch (err) {
902
+ // --file failures already carry their own code; only exportWallet
903
+ // (decrypt / lookup) failures need the generic wrap.
904
+ if (err instanceof CommandError) throw err;
780
905
  throw new CommandError(`❌ ${err.message}`, 'EXPORT_FAILED');
781
906
  }
782
907
  },
@@ -837,6 +962,8 @@ export function buildWalletCommands(deps = {}) {
837
962
  },
838
963
 
839
964
  'send': async () => {
965
+ rejectBlankOption(options.token, 'token', '<token-address>');
966
+ rejectBlankOption(options.wallet, 'wallet', '<name>');
840
967
  const { sendTokens } = await import('./transfer.js');
841
968
 
842
969
  if (!options.to) {
@@ -1015,7 +1142,10 @@ COMMANDS:
1015
1142
  Create a new wallet pair (EVM + Solana)
1016
1143
  list List all wallets
1017
1144
  show <name> Show wallet addresses
1018
- export <name> Export private keys (local wallets only, requires password)
1145
+ export <name> [--reveal | --file <path>]
1146
+ Export private keys (local wallets only, requires password).
1147
+ Redacted by default: --reveal prints plaintext to stdout,
1148
+ --file writes them to a new file only you can read (0600)
1019
1149
  default <name> Set the default wallet
1020
1150
  delete <name> Delete a wallet
1021
1151
  send --to <address> --amount <number> --chain <evm|solana> [--token <address>] [--wallet <name>] [--max] [--dry-run]
@@ -1033,6 +1163,8 @@ OPTIONS:
1033
1163
  --token <address> Token contract/mint address (optional, sends native if omitted)
1034
1164
  --wallet <name> Wallet to use (optional, uses default if omitted; use "walletconnect" or "wc" for WalletConnect, EVM only)
1035
1165
  --max Send entire balance (deducts gas for native transfers)
1166
+ --reveal Export: print private keys in plaintext to stdout (explicit acknowledgement)
1167
+ --file <path> Export: write private keys to <path> (created 0600, refuses to overwrite)
1036
1168
  --unsafe-no-password Skip encryption — private keys stored UNENCRYPTED on disk (local only)
1037
1169
  --human Enable interactive prompts (for human terminal use only)
1038
1170
 
@@ -1056,7 +1188,9 @@ EXAMPLES:
1056
1188
  NANSEN_WALLET_PASSWORD=mypass nansen wallet create --name trading
1057
1189
  nansen wallet create --name agent-wallet --provider privy
1058
1190
  nansen wallet list
1059
- nansen wallet export trading
1191
+ nansen wallet export trading # redacted (addresses only)
1192
+ nansen wallet export trading --file backup.json # keys → 0600 file, nothing on stdout
1193
+ nansen wallet export trading --reveal # keys → stdout (plaintext)
1060
1194
  nansen wallet default trading
1061
1195
  nansen wallet send --to 0x742d35Cc... --amount 1.5 --chain evm
1062
1196
  nansen wallet send --to 9WzDXw... --amount 0.1 --chain solana --token So11...
@@ -15,10 +15,12 @@ import { encodeApproveCalldata } from './trade-validation.js';
15
15
  const SOLANA_MAINNET_CHAIN = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';
16
16
 
17
17
  /**
18
- * Extract the first JSON line from walletconnect CLI output.
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');
@@ -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 JSON line — extract JSON only
205
- const jsonLine = output.split('\n').find(line => line.startsWith('{'));
206
- if (!jsonLine) throw new Error('No JSON output from walletconnect sign-typed-data');
207
- signResult = JSON.parse(jsonLine);
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}`,