nansen-cli 2.6.0 → 2.6.1

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
@@ -5,7 +5,7 @@
5
5
 
6
6
  import crypto from 'crypto';
7
7
  import { base58Encode, base58Decode, base58DecodePubkey, exportWallet, getWalletConfig, verifyPassword, showWallet } from './wallet.js';
8
- import { keccak256, signSecp256k1, rlpEncode } from './crypto.js';
8
+ import { keccak256, signSecp256k1, rlpEncode, toChecksumAddress } from './crypto.js';
9
9
  import { getWalletConnectAddress, sendTransactionViaWalletConnect } from './walletconnect-trading.js';
10
10
  import { EVM_CHAIN_IDS } from './chain-ids.js';
11
11
  import { CHAIN_RPCS } from './rpc-urls.js';
@@ -35,6 +35,17 @@ function deriveEvmAddress(privateKeyHex) {
35
35
 
36
36
  function validateEvmAddress(address) {
37
37
  if (!/^0x[0-9a-fA-F]{40}$/.test(address)) return { valid: false, error: 'Invalid EVM address' };
38
+ // EIP-55: a mixed-case address carries a checksum, and one that doesn't
39
+ // match is a typo (one changed character still has the right shape). An
40
+ // all-lowercase or all-uppercase address has no checksum to check.
41
+ const hex = address.slice(2);
42
+ if (/[a-f]/.test(hex) && /[A-F]/.test(hex) && toChecksumAddress(hex) !== address) {
43
+ return {
44
+ valid: false,
45
+ checksum: true,
46
+ error: `EVM address ${address} has an invalid EIP-55 checksum (its mixed case does not match). It likely has a typo: copy the address again from its source.`,
47
+ };
48
+ }
38
49
  return { valid: true };
39
50
  }
40
51
 
@@ -83,6 +94,7 @@ function resolveSendToken(token, chain) {
83
94
  if (known) return known;
84
95
  const check = chain === 'solana' ? validateSolanaAddress(token) : validateEvmAddress(token);
85
96
  if (check.valid) return token;
97
+ if (check.checksum) throw new Error(`Invalid --token: ${check.error}`);
86
98
  const kind = chain === 'solana' ? 'mint address' : 'contract address';
87
99
  const names = Object.keys(symbols);
88
100
  const choices = names.length ? `, or one of: ${names.join(', ')}` : '';
@@ -719,6 +731,40 @@ async function broadcastTransaction(signedTx, chain, token = null) {
719
731
 
720
732
  export { parseAmount, formatAmount, signEd25519, encodeCompactU16, base58Decode, base58DecodePubkey, deriveATA, isOnEd25519Curve, validateEvmAddress, validateSolanaAddress, bigIntToHex, resolveSendToken };
721
733
 
734
+ /**
735
+ * Refuse a Solana recipient that is not a wallet. An SPL send derives the
736
+ * recipient's associated token account, and the ATA program accepts any owner,
737
+ * so tokens sent to a token account, mint, program or program-owned data
738
+ * account land where nobody can sign to move them. Only a System-owned account
739
+ * with no data (a wallet) or one that doesn't exist yet (a new, unfunded wallet)
740
+ * passes. A System-owned account holding data, such as a durable nonce account,
741
+ * is not a wallet either.
742
+ * Fails closed: if the lookup fails, the send doesn't happen.
743
+ */
744
+ async function assertSolanaRecipientIsWallet(to) {
745
+ const info = await rpcCall(CHAIN_RPCS.solana, 'getAccountInfo', [to, { encoding: 'base64', commitment: 'confirmed' }]);
746
+ // A real node answers { context, value }, with value null for no account.
747
+ // Anything else is not an answer, so don't read it as "new wallet".
748
+ if (!info || typeof info !== 'object' || !('value' in info)) {
749
+ throw new Error(`Could not check recipient ${to}: the Solana RPC returned no account info. Nothing was sent; try again.`);
750
+ }
751
+ const owner = info.value?.owner;
752
+ if (info.value && owner !== SYSTEM_PROGRAM) {
753
+ throw new Error(
754
+ `Recipient ${to} is not a wallet address (it is an account owned by program ${owner}, such as a token account, mint or program). ` +
755
+ `Tokens sent there can't be moved out. Pass the recipient's wallet address.`,
756
+ );
757
+ }
758
+ const data = info.value?.data;
759
+ const dataLength = Array.isArray(data) && typeof data[0] === 'string' ? Buffer.from(data[0], 'base64').length : 0;
760
+ if (info.value && (dataLength > 0 || (typeof info.value.space === 'number' && info.value.space > 0))) {
761
+ throw new Error(
762
+ `Recipient ${to} is not a wallet address (it is a System account holding data, such as a nonce account). ` +
763
+ `Tokens sent there can't be moved out. Pass the recipient's wallet address.`,
764
+ );
765
+ }
766
+ }
767
+
722
768
  /**
723
769
  * Send tokens via Privy server wallet. EVM uses Privy's sendTransaction (handles gas/nonce).
724
770
  * Solana builds unsigned tx, signs via Privy, then broadcasts.
@@ -742,13 +788,19 @@ async function sendTokensViaPrivy({ to, amount, chain, token, max, dryRun, walle
742
788
  const maxAmount = BigInt(balResult.value) - fee;
743
789
  if (maxAmount <= 0n) throw new Error('Insufficient SOL balance for fees');
744
790
  amount = formatAmount(maxAmount, 9);
745
- } else if (max && token) {
791
+ } else if (token) {
746
792
  const rpcUrl = CHAIN_RPCS.solana;
747
- const { tokenProgram, decimals: _decimals } = await getTokenInfo(rpcUrl, token);
748
- const sourceATA = deriveATA(fromAddress, token, tokenProgram);
749
- const sourceAtaAddr = base58Encode(sourceATA);
750
- const ataInfo = await rpcCall(rpcUrl, 'getTokenAccountBalance', [sourceAtaAddr]);
751
- amount = ataInfo.value.uiAmountString;
793
+ const { tokenProgram, decimals } = await getTokenInfo(rpcUrl, token);
794
+ if (max) {
795
+ const sourceATA = deriveATA(fromAddress, token, tokenProgram);
796
+ const sourceAtaAddr = base58Encode(sourceATA);
797
+ const ataInfo = await rpcCall(rpcUrl, 'getTokenAccountBalance', [sourceAtaAddr]);
798
+ amount = ataInfo.value.uiAmountString;
799
+ }
800
+ // The SPL amount is otherwise parsed only while building the transaction,
801
+ // after the dry-run return. Parse it here so a preview refuses the same
802
+ // malformed, zero or sub-unit amounts the real send does.
803
+ parseAmount(amount, decimals);
752
804
  }
753
805
 
754
806
  if (dryRun) return { dryRun: true, from: fromAddress, to, amount, token, chain };
@@ -840,6 +892,10 @@ export async function sendTokens({ to, amount, chain, token = null, wallet = nul
840
892
  const v = validate(to);
841
893
  if (!v.valid) throw new Error(`Invalid recipient: ${v.error}`);
842
894
  token = resolveSendToken(token, chain);
895
+ // An ERC-20 sent to its own contract lands in a balance nobody controls.
896
+ if (chain !== 'solana' && token && to.toLowerCase() === token.toLowerCase()) {
897
+ throw new Error(`Recipient ${to} is the token contract itself; tokens sent there are lost. Pass the recipient's wallet address.`);
898
+ }
843
899
 
844
900
  if (walletconnect) {
845
901
  if (chain === 'solana') {
@@ -848,6 +904,8 @@ export async function sendTokens({ to, amount, chain, token = null, wallet = nul
848
904
  return sendTokensViaWalletConnect({ to, amount, chain, token, max, dryRun });
849
905
  }
850
906
 
907
+ if (chain === 'solana') await assertSolanaRecipientIsWallet(to);
908
+
851
909
  // Resolve wallet and check provider
852
910
  const config = getWalletConfig();
853
911
  const walletName = wallet || config.defaultWallet;
package/src/wallet.js CHANGED
@@ -32,7 +32,7 @@ const SALT_LEN = 16;
32
32
  const IV_LEN = 12;
33
33
  const _AUTH_TAG_LEN = 16;
34
34
 
35
- import { keccak256 } from './crypto.js';
35
+ import { keccak256, toChecksumAddress } from './crypto.js';
36
36
 
37
37
  // ============= Base58 Encoding (for Solana) =============
38
38
 
@@ -160,14 +160,7 @@ export function generateEvmWallet() {
160
160
  const addressBytes = hash.subarray(12);
161
161
  const addressHex = addressBytes.toString('hex');
162
162
 
163
- // EIP-55 checksum
164
- const addressHash = keccak256(Buffer.from(addressHex, 'utf8')).toString('hex');
165
- let checksummed = '0x';
166
- for (let i = 0; i < 40; i++) {
167
- checksummed += parseInt(addressHash[i], 16) >= 8
168
- ? addressHex[i].toUpperCase()
169
- : addressHex[i];
170
- }
163
+ const checksummed = toChecksumAddress(addressHex);
171
164
 
172
165
  const result = {
173
166
  privateKey: privateKey.toString('hex'),
@@ -1200,6 +1193,12 @@ export function buildWalletCommands(deps = {}) {
1200
1193
  throw new CommandError('--to <address> is required', 'MISSING_ARGS');
1201
1194
  }
1202
1195
 
1196
+ // --amount <n> with --max used to send the whole balance and drop the
1197
+ // amount silently. Refuse the combination instead (--amount max is
1198
+ // the same as --max and stays allowed).
1199
+ if (flags.max && options.amount != null && options.amount !== 'max') {
1200
+ throw new CommandError('Choose one of --amount <number> or --max, not both.', 'INVALID_INPUT');
1201
+ }
1203
1202
  const isMax = flags.max || options.amount === 'max';
1204
1203
  if (!options.amount && !isMax) {
1205
1204
  throw new CommandError('--amount <number> or --max is required', 'MISSING_ARGS');
@@ -1406,7 +1405,7 @@ OPTIONS:
1406
1405
  --token <symbol|address> Token to send: USDC, USDT, or a token contract/mint address
1407
1406
  (optional, sends native if omitted)
1408
1407
  --wallet <name> Wallet to use (optional, uses default if omitted; use "walletconnect" or "wc" for WalletConnect, EVM only)
1409
- --max Send entire balance (deducts gas for native transfers)
1408
+ --max Send entire balance (deducts gas for native transfers); not with --amount <number>
1410
1409
  --reveal Export: print private keys in plaintext to stdout (explicit acknowledgement)
1411
1410
  --file <path> Export: write private keys to <path> (created 0600, refuses to overwrite)
1412
1411
  --unsafe-no-password Skip encryption — private keys stored UNENCRYPTED on disk (local only)