nansen-cli 2.5.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.
@@ -680,6 +680,61 @@ function tokensEqual(a, b, chain) {
680
680
  return a.toLowerCase() === b.toLowerCase();
681
681
  }
682
682
 
683
+ /**
684
+ * The quote's input amount as the intent binding reads it: `inputAmount`, or
685
+ * the legacy `inAmount` alias when `inputAmount` is absent. Every pre-sign
686
+ * check that bounds the input (intent match, spend ceiling, native tx.value)
687
+ * must read this same field, or a quote carrying both aliases with different
688
+ * values satisfies each check with a different one.
689
+ */
690
+ export function quoteInputAmountRaw(quote) {
691
+ return quote?.inputAmount ?? quote?.inAmount;
692
+ }
693
+
694
+ /**
695
+ * Check a native-token-input EVM transaction's `value` against the quote and
696
+ * the persisted request intent. Returns null when it is safe to sign, or a
697
+ * reason string the caller reports as a value mismatch.
698
+ *
699
+ * - tx.value must equal the bound input (quoteInputAmountRaw), the same field
700
+ * assertQuoteMatchesRequest / assertInputWithinMax already checked.
701
+ * - tx.value must also not exceed request.maxInputAmount, independently, so
702
+ * the native value is capped by persisted intent whichever alias the API
703
+ * populated.
704
+ *
705
+ * @param {object} request - Persisted intent (quoteData.request)
706
+ * @param {object} quote - The quote being executed
707
+ * @param {bigint} txValue - The transaction value about to be signed
708
+ * @returns {string|null}
709
+ */
710
+ export function nativeValueMismatch(request, quote, txValue) {
711
+ const inRaw = quoteInputAmountRaw(quote);
712
+ if (inRaw == null || inRaw === '') {
713
+ return `tx.value=${txValue}, but the quote has no input amount to bind it to`;
714
+ }
715
+ let expected;
716
+ try {
717
+ expected = BigInt(inRaw);
718
+ } catch {
719
+ return `tx.value=${txValue}, but the quote input amount (${inRaw}) is not an integer`;
720
+ }
721
+ if (txValue !== expected) {
722
+ return `tx.value=${txValue}, expected=${expected}`;
723
+ }
724
+ if (request?.maxInputAmount != null) {
725
+ let cap;
726
+ try {
727
+ cap = BigInt(request.maxInputAmount);
728
+ } catch {
729
+ return `tx.value=${txValue}, but the persisted maximum input (${request.maxInputAmount}) is not an integer`;
730
+ }
731
+ if (txValue > cap) {
732
+ return `tx.value=${txValue} exceeds the maximum input ${cap}`;
733
+ }
734
+ }
735
+ return null;
736
+ }
737
+
683
738
  /**
684
739
  * Revalidate a quote against the immutable request intent that was persisted
685
740
  * when the quote was fetched. The Trading API supplies the amounts, token
@@ -802,7 +857,7 @@ export function assertQuoteMatchesRequest(request, quote, { chain, walletAddress
802
857
  );
803
858
  }
804
859
  } else {
805
- const inRaw = quote.inputAmount ?? quote.inAmount;
860
+ const inRaw = quoteInputAmountRaw(quote);
806
861
  if (inRaw == null) {
807
862
  throw new Error(
808
863
  `Quote is missing the input amount; cannot confirm it matches the requested input (${requested}). Refusing to sign.`,
@@ -882,7 +937,7 @@ export function assertInputWithinMax(request, quote, slippage) {
882
937
  );
883
938
  }
884
939
 
885
- const inRaw = quote.inputAmount ?? quote.inAmount;
940
+ const inRaw = quoteInputAmountRaw(quote);
886
941
  if (inRaw == null) {
887
942
  throw new Error(
888
943
  'Quote is missing the input amount; cannot enforce the maximum input. Refusing to sign.',
package/src/trading.js CHANGED
@@ -16,7 +16,7 @@ import { buildMessageV0, fetchAddressLookupTables, fetchRecentBlockhash } from '
16
16
  import { keccak256, signSecp256k1, rlpEncode } from './crypto.js';
17
17
  import { getWalletConnectAddress, sendTransactionViaWalletConnect, sendSolanaTransactionViaWalletConnect, sendApprovalViaWalletConnect } from './walletconnect-trading.js';
18
18
  import { retrievePassword } from './keychain.js';
19
- import { validateQuoteInput, validateBalance, resolvePercentAmount, validateGasBalance, encodeApproveCalldata, assertValidApprovalSpender, assertQuoteMatchesRequest, assertSwapCalldataNotBareTransfer, assertSwapOutcome, assertSolanaInstructionsSafe, checkSolanaFeeBalance, assertSolanaSwapOutcome, approvalAmountForSwap, needsAllowanceRevoke, OVERSIZED_ALLOWANCE_MULTIPLIER, EVM_BRIDGE_NATIVE_FEE_SLACK, isBridgeRequest } from './trade-validation.js';
19
+ import { validateQuoteInput, validateBalance, resolvePercentAmount, validateGasBalance, encodeApproveCalldata, assertValidApprovalSpender, assertQuoteMatchesRequest, assertSwapCalldataNotBareTransfer, assertSwapOutcome, assertSolanaInstructionsSafe, checkSolanaFeeBalance, assertSolanaSwapOutcome, approvalAmountForSwap, needsAllowanceRevoke, OVERSIZED_ALLOWANCE_MULTIPLIER, EVM_BRIDGE_NATIVE_FEE_SLACK, isBridgeRequest, nativeValueMismatch } from './trade-validation.js';
20
20
  import { readCompactU16 } from './solana-tx.js';
21
21
  import { formatPlan, guardExecution, resolveExecuteGuard } from './execute-guard.js';
22
22
  export { readCompactU16 };
@@ -2928,10 +2928,10 @@ async function preflightTradeExecutionCandidate({
2928
2928
  const nativeInput = isNativeToken(quote.inputMint);
2929
2929
  const txValue = BigInt(quote.transaction.value || '0');
2930
2930
  if (nativeInput) {
2931
- const expectedValue = BigInt(quote.inAmount || quote.inputAmount || '0');
2932
- if (txValue !== expectedValue) {
2931
+ const valueMismatch = nativeValueMismatch(quoteData.request, quote, txValue);
2932
+ if (valueMismatch) {
2933
2933
  throw new CommandError(
2934
- `Transaction value mismatch: tx.value=${txValue}, expected=${expectedValue}`,
2934
+ `Transaction value mismatch: ${valueMismatch}`,
2935
2935
  'AMOUNT_MISMATCH',
2936
2936
  );
2937
2937
  }
@@ -4037,9 +4037,9 @@ EXAMPLES:
4037
4037
  const isNative = isNativeToken(currentQuote.inputMint);
4038
4038
  const txValue = BigInt(currentQuote.transaction.value || '0');
4039
4039
  if (isNative) {
4040
- const expectedValue = BigInt(currentQuote.inAmount || currentQuote.inputAmount || '0');
4041
- if (txValue !== expectedValue) {
4042
- log(` ❌ Transaction value mismatch for ${quoteName}: tx.value=${txValue}, expected=${expectedValue}`);
4040
+ const valueMismatch = nativeValueMismatch(quoteData.request, currentQuote, txValue);
4041
+ if (valueMismatch) {
4042
+ log(` ❌ Transaction value mismatch for ${quoteName}: ${valueMismatch}`);
4043
4043
  if (qi + 1 < endIndex) log(` Trying next quote...`);
4044
4044
  lastQuoteError = `${quoteName} transaction value mismatch`;
4045
4045
  continue;
@@ -4430,9 +4430,9 @@ EXAMPLES:
4430
4430
  // Validate transaction.value (same checks as local wallet)
4431
4431
  const txValue = BigInt(currentQuote.transaction.value || '0');
4432
4432
  if (isNative) {
4433
- const expectedValue = BigInt(currentQuote.inAmount || currentQuote.inputAmount || '0');
4434
- if (txValue !== expectedValue) {
4435
- log(` ❌ Transaction value mismatch for ${quoteName}: tx.value=${txValue}, expected=${expectedValue}`);
4433
+ const valueMismatch = nativeValueMismatch(quoteData.request, currentQuote, txValue);
4434
+ if (valueMismatch) {
4435
+ log(` ❌ Transaction value mismatch for ${quoteName}: ${valueMismatch}`);
4436
4436
  if (qi + 1 < endIndex) log(` Trying next quote...`);
4437
4437
  lastQuoteError = `${quoteName} transaction value mismatch`;
4438
4438
  continue;
@@ -4822,13 +4822,13 @@ EXAMPLES:
4822
4822
 
4823
4823
  // Validate transaction.value matches the swap type.
4824
4824
  // ERC-20 swaps transfer tokens via calldata, so value must be 0.
4825
- // Native ETH swaps must have value matching the quoted inAmount.
4825
+ // Native ETH swaps must have value matching the bound quote input (and within maxInputAmount).
4826
4826
  // A compromised API could attach a large value to drain ETH silently.
4827
4827
  const txValue = BigInt(currentQuote.transaction.value || '0');
4828
4828
  if (isNative) {
4829
- const expectedValue = BigInt(currentQuote.inAmount || currentQuote.inputAmount || '0');
4830
- if (txValue !== expectedValue) {
4831
- log(` ❌ Transaction value mismatch for ${quoteName}: tx.value=${txValue}, expected=${expectedValue}`);
4829
+ const valueMismatch = nativeValueMismatch(quoteData.request, currentQuote, txValue);
4830
+ if (valueMismatch) {
4831
+ log(` ❌ Transaction value mismatch for ${quoteName}: ${valueMismatch}`);
4832
4832
  if (qi + 1 < endIndex) log(` Trying next quote...`);
4833
4833
  lastQuoteError = `${quoteName} transaction value mismatch`;
4834
4834
  continue;
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)
@@ -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`.