nansen-cli 2.2.0 → 2.3.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/CHANGELOG.md CHANGED
@@ -1,5 +1,49 @@
1
1
  # Changelog
2
2
 
3
+ ## 2.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#747](https://github.com/nansen-ai/nansen-cli/pull/747) [`32a4ab2`](https://github.com/nansen-ai/nansen-cli/commit/32a4ab2bd9f9999a7ce9bd654af25c5783683ca2) Thanks [@hulk-linus](https://github.com/apps/hulk-linus)! - Add feedback submit and receipt lookup with explicit submission IDs, account authentication, safe retries, and JSON or human output.
8
+
9
+ Explain the agent preference rule in CLI guidance: ask before sending when the saved preference is off, unset or unavailable.
10
+
11
+ Explain paused submissions: report the unavailable feature, stop repeated attempts, and preserve the ID and report for a later retry.
12
+
13
+ Preserve field-level validation errors and uncertain submissions across session failures, recognize gateway authentication errors, and keep malformed feedback arguments out of telemetry.
14
+
15
+ - [#755](https://github.com/nansen-ai/nansen-cli/pull/755) [`84ba0b0`](https://github.com/nansen-ai/nansen-cli/commit/84ba0b04a2920114417b19d640ed7aff158b3d5b) Thanks [@hulk-linus](https://github.com/apps/hulk-linus)! - Read account feedback preferences and stop automatic retries when feedback is not enabled for the account.
16
+
17
+ - [#754](https://github.com/nansen-ai/nansen-cli/pull/754) [`4dddcec`](https://github.com/nansen-ai/nansen-cli/commit/4dddceccd500c3dff9641fcc4bea99d8909ccc20) Thanks [@hulk-linus](https://github.com/apps/hulk-linus)! - Save feedback submissions before sending when no ID is supplied. Resume the same report after a restart, with account and environment checks, private storage, concurrency protection, and local expiry and erasure.
18
+
19
+ - [#744](https://github.com/nansen-ai/nansen-cli/pull/744) [`f56cdbb`](https://github.com/nansen-ai/nansen-cli/commit/f56cdbba8049dcf349dd0bb4ca94552334085762) Thanks [@kome12](https://github.com/kome12)! - **Removed `--gasless` from `trade execute`.** The flag never worked. The deprecated broadcast route it posted to validates its request body strictly and has never accepted the `gasless` or `steps` fields, so every gasless swap was rejected with `Unrecognized keys` before anything was broadcast — on Base and on Solana alike. Passing `--gasless` now fails fast with `GASLESS_REMOVED` instead of signing, posting and failing; re-run without it and the wallet pays its own gas as usual. There is no replacement flag.
20
+
21
+ This corrects the 2.2.0 release note, which said "Gasless swaps stay on the deprecated route". They did, but that route rejected them; there was no working gasless path to keep.
22
+
23
+ This removes a published option and its `schema.json` entry, so anything enumerating `trade execute`'s options will see it disappear and any wrapper still passing it will fail. It is released as a minor rather than a major because the flag never completed a swap on any chain: every call already ended in a failed execution, so no working integration can depend on it.
24
+
25
+ **Removed the `$10` gas-balance bypass.** `trade quote` skipped its native-balance pre-check for any trade worth $10 or more, on the theory that such trades could use a solver-paid route. It never checked whether one was actually in use, so a wallet with no native token passed validation and then failed at broadcast. Gas is now checked on every trade, and the error says to fund the wallet rather than suggesting the removed feature.
26
+
27
+ The Solana floor comes down from `0.01` SOL to `0.005` SOL in the same change. It had drifted above the `0.005` SOL the CLI itself holds back when you sell the maximum amount of SOL, so a wallet left sitting on exactly that reserve would have been refused its next quote — a contradiction the `$10` bypass had been hiding from every trade worth $10 or more. `0.005` SOL is still a wide margin over a real swap (a 5000-lamport base fee plus at most ~0.00204 SOL of account rent). The Base floor is unchanged.
28
+
29
+ - [#751](https://github.com/nansen-ai/nansen-cli/pull/751) [`0a87eae`](https://github.com/nansen-ai/nansen-cli/commit/0a87eae89fadbadf0fa1869546f71f8d9afa5d80) Thanks [@kome12](https://github.com/kome12)! - Add `NANSEN_X402_SESSION_MAX_AMOUNT` to cap the total USD of x402 auto-payments one CLI process can sign
30
+
31
+ ### Patch Changes
32
+
33
+ - [#757](https://github.com/nansen-ai/nansen-cli/pull/757) [`19b7cfc`](https://github.com/nansen-ai/nansen-cli/commit/19b7cfcb562bac2beb85775833fb8b87edfd0037) Thanks [@hulk-linus](https://github.com/apps/hulk-linus)! - Report feedback edge blocks as rejections, keep preference failures on the ask-before-sending path, and preserve the actual submission outcome when resuming saved reports.
34
+
35
+ - [#732](https://github.com/nansen-ai/nansen-cli/pull/732) [`94815d4`](https://github.com/nansen-ai/nansen-cli/commit/94815d409cb67b6e93fe32bd5d5bbd9081084c57) Thanks [@Ahmett101](https://github.com/Ahmett101)! - Render profiler perp positions as individual rows in table and CSV output while preserving the original JSON response and account summaries. Table and CSV output also falls back to showing the payload when a response's rows carry no fields, instead of printing blank lines.
36
+
37
+ - [#742](https://github.com/nansen-ai/nansen-cli/pull/742) [`facbb45`](https://github.com/nansen-ai/nansen-cli/commit/facbb4536b7bb6e2667f8272ada3a4b34a06dd79) Thanks [@gulshngill](https://github.com/gulshngill)! - Check EVM token balances before signing automatic x402 payments. Skip unfunded options for local and Privy wallets and continue to a funded token, using exact amounts and bounded RPC checks.
38
+
39
+ - [#748](https://github.com/nansen-ai/nansen-cli/pull/748) [`fb96a5d`](https://github.com/nansen-ai/nansen-cli/commit/fb96a5d96d26e7610e7b580a000b1d85bd3fcfc4) Thanks [@hulk-linus](https://github.com/apps/hulk-linus)! - Use stable v1 API routes for ten historical research commands before their beta aliases are retired.
40
+
41
+ - [#750](https://github.com/nansen-ai/nansen-cli/pull/750) [`2c38b44`](https://github.com/nansen-ai/nansen-cli/commit/2c38b44b10329eb3570b3c44566e198bd60b4693) Thanks [@kome12](https://github.com/kome12)! - Record x402 auto-payments in a local audit log at `~/.nansen/x402/payments.jsonl`: one line when a signed payment is sent and one for its outcome (accepted, rejected or ambiguous), with the amount, network, asset, recipient and request path. Signatures, request and response bodies, and query strings are never written, and a failed write warns without blocking the payment.
42
+
43
+ - [#745](https://github.com/nansen-ai/nansen-cli/pull/745) [`5a77e0d`](https://github.com/nansen-ai/nansen-cli/commit/5a77e0d160507d97e67b50bfe38917a2005d13c5) Thanks [@gulshngill](https://github.com/gulshngill)! - Skip unfunded x402 payment options on every signing path. WalletConnect payments now try each compatible option cheapest first, check the connected wallet's token balance before asking for approval, and move on to the next option after a clean server rejection instead of failing on the first. Solana payments from local and Privy wallets check the USDC balance before signing. Privy payments now report the token they paid with, so the low-balance warning checks the right token.
44
+
45
+ - [#749](https://github.com/nansen-ai/nansen-cli/pull/749) [`221371b`](https://github.com/nansen-ai/nansen-cli/commit/221371b055d08bd88ad9bf8da409e21f01baa85c) Thanks [@kome12](https://github.com/kome12)! - x402: report on stderr when the server rejects a payment because the wallet's token balance is too low, and include the network in the "Paid via WalletConnect" log line.
46
+
3
47
  ## 2.2.0
4
48
 
5
49
  ### Minor Changes
package/README.md CHANGED
@@ -14,6 +14,83 @@ npm install -g nansen-cli
14
14
  npx skills add nansen-ai/nansen-cli # load agent skill files
15
15
  ```
16
16
 
17
+ ## Feedback
18
+
19
+ Send product feedback to Nansen with your configured API key or login session:
20
+
21
+ ```json
22
+ {
23
+ "category": "missing_capability",
24
+ "description": "I need to compare labels across 50 wallets but cannot find a bulk lookup.",
25
+ "goal": "Compare labels across a wallet list."
26
+ }
27
+ ```
28
+
29
+ Save the report as `feedback.json`. Omit the ID to save private recovery data before sending:
30
+
31
+ ```bash
32
+ nansen feedback submit --file feedback.json --json
33
+ nansen feedback resume --json
34
+ nansen feedback get fb_123 --json
35
+ ```
36
+
37
+ `resume` uses the saved ID and exact report bytes, even if the input file is gone.
38
+ Changing the account, API environment or report stops replay. After confirmation,
39
+ `resume` reads the receipt without sending another report. To deliberately start
40
+ another report, use `feedback submit --new --file feedback.json`.
41
+
42
+ One recovery entry lives in `~/.nansen/feedback/recovery.json`, with private
43
+ permissions and a process lock. Confirmed receipts remove report content and keep
44
+ only the submission ID, feedback ID, account, environment and expiry. Feedback
45
+ recovery operations erase expired data when they next open the journal. Pending
46
+ reports expire after one calendar year. No cleanup runs while the CLI is closed.
47
+ `nansen feedback forget` erases local recovery data
48
+ offline, leaving a content-free marker that prevents accidental replay. It does
49
+ not delete your input file or a report on the server. A missing or erased server
50
+ receipt also clears the local entry. Validation rejections erase the saved payload;
51
+ correct the input and use --new to submit again. Forget also erases damaged journals.
52
+ Do not back up pending report content.
53
+
54
+ Automatic IDs require POSIX private storage and the optional native locking
55
+ binding. On Windows or when storage cannot be secured, supply a caller-managed
56
+ `--submission-id report-123` and keep that ID and the unchanged file for retries.
57
+ This explicit-ID path does not save a local report. Recovery format version 1
58
+ survives upgrades; unsupported or damaged journals stop rather than start fresh.
59
+ Older explicit-ID-only CLI releases do not read recovery journals; finish recovery
60
+ with a supporting version before rolling back.
61
+
62
+ Remove `--json` for human output. `received` means
63
+ saved, `reviewed` means triaged, and `closed` means review is complete. Review does
64
+ not promise a fix or a date.
65
+
66
+ Feedback is free, with seven accepted reports per account each week, resetting
67
+ Monday at 00:00 UTC. An exhausted allowance exits with its reset time; accepted
68
+ IDs can still be replayed. Feedback bypasses caching and payment fallback.
69
+ Remove secrets and unnecessary personal details from your report. A backend
70
+ without feedback support reports an unavailable capability.
71
+
72
+ New submissions may be paused before release or during an outage. HTTP 503 with
73
+ `reason: feedback_admissions_paused` means this attempt accepted no new report
74
+ and used no weekly allowance. Tell the user feedback is unavailable, then stop;
75
+ do not keep retrying or ask for approval again in the same session. Keep the ID
76
+ and unchanged file for a later retry. Accepted-ID replays and receipt reads
77
+ remain available during a pause.
78
+
79
+ Agents should check the saved account preference before sending feedback on their
80
+ own. If enabled, they may send without asking again, subject to their host's
81
+ controls. If off, unset or unavailable, show the proposed report and ask first.
82
+ Approval for one report does not change the preference. Never enable it
83
+ automatically. Use `nansen feedback preferences --json` for a fresh account read
84
+ before each new automatic report. Without `--json`, it prints a human summary.
85
+ Reads use no credits or report quota. Change the lasting choice in Superapp settings.
86
+ An explicit user request to send the report needs no additional preference
87
+ check. The submit command sends the report without an interactive prompt.
88
+
89
+ HTTP 403 with `reason: feedback_not_enabled` means feedback is not enabled for
90
+ this account. Stop automatic retries. Approval or an enabled preference does
91
+ not override rollout. Keep the ID and unchanged report for recovery; an earlier
92
+ uncertain attempt remains uncertain. Never switch accounts or pay to bypass denial.
93
+
17
94
  ## Auth
18
95
 
19
96
  Plain `nansen login` requests fresh browser approval and saves a session automatically. No API-key copying or PEM setup is needed. Selected sessions renew automatically; rejected or uncertain renewal requires fresh login.
@@ -188,7 +265,6 @@ Cross-chain swaps work the same way — add `--to-chain`. Bridge providers (Li.F
188
265
  ```bash
189
266
  nansen trade quote --chain base --to-chain solana --from ETH --to SOL --amount 0.0003 --amount-unit token
190
267
  nansen trade execute --quote <quoteId> # signed broadcast
191
- nansen trade execute --quote <quoteId> --gasless # Relay-only: solver pays gas
192
268
  nansen trade bridge-status --tx-hash <hash> --from-chain base --to-chain solana
193
269
  ```
194
270
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nansen-cli",
3
- "version": "2.2.0",
3
+ "version": "2.3.0",
4
4
  "description": "AI-agent CLI for Nansen API analytics, DEX swaps, and cross-chain trading",
5
5
  "main": "src/index.js",
6
6
  "type": "module",
@@ -67,3 +67,40 @@ Cost: 5-50 credits per call
67
67
  Plain `nansen login` requests fresh browser approval; `--no-browser` prints the link/code for approval on another device and keeps the same native-storage requirements. NANSEN_API_KEY overrides the single saved credential. Use `nansen auth status` for offline cached/unverified selection details and `nansen account` for a free live check. Explicit `login --human` or `login --api-key` retains legacy key setup. Selected browser sessions renew automatically; uncertain renewal requires fresh login without replay or fallback to another account/payment.
68
68
 
69
69
  Browser nansen:api grants have API-key-equivalent account permissions, subject to enabled admission and the same endpoint restrictions. Internal service identity and wallet signing are not granted. Browser sessions cannot authorize wallet signing or be exported as MCP keys. CLI 2.0.0 is published; the preview platform limits above still apply.
70
+
71
+
72
+ ## Product feedback
73
+
74
+ When a Nansen task exposes a useful product gap, draft a concise report without
75
+ secrets or unnecessary conversation details. Before sending on your own, read
76
+ the current account's saved feedback preference with
77
+ `nansen feedback preferences --json`. Use a fresh read for each new report. If enabled, you may send without asking again,
78
+ subject to the host's controls. If off, unset or unavailable, show the proposed
79
+ report and ask the user. If they decline or you cannot ask, do not send.
80
+
81
+ If the preference read fails, ask first. An explicit user request or approval
82
+ permits that report; it does not change the saved preference. Never enable the
83
+ preference automatically or add approval fields to the report. Direct users to
84
+ Superapp settings for a lasting choice. Host or local-deny controls still apply
85
+ to an enabled preference and to one-report approval.
86
+
87
+ After the user requests the report or the preference permits it, submit with
88
+ `nansen feedback submit --file feedback.json --submission-id <new-id> --json`.
89
+ The command is noninteractive. Keep the same ID and unchanged report when
90
+ recovering an uncertain result; use `nansen feedback get <feedback-id> --json`
91
+ to read a saved receipt. Submission and receipt reads are free. The account
92
+ shares seven accepted reports per UTC week, resetting Monday at 00:00 UTC.
93
+
94
+ New submissions may be paused before release or during an outage. A 503 with
95
+ `reason: feedback_admissions_paused` means this attempt accepted no new report
96
+ and used no weekly allowance. Tell the user feedback is unavailable and stop;
97
+ do not keep retrying or ask for approval again in the same session. Preserve
98
+ the ID and unchanged report for a later retry. If this CLI version lacks the
99
+ feedback command, report that it is unavailable and stop. Accepted-ID replays
100
+ and receipt reads remain available during a pause.
101
+
102
+ A 403 with `reason: feedback_not_enabled` means feedback is not enabled for
103
+ this account. Stop automatic retries and tell the user. Approval and an enabled
104
+ preference do not override rollout. Keep the saved ID and unchanged report.
105
+ An earlier uncertain attempt remains uncertain; recover it with the same ID
106
+ after availability is restored. Never switch accounts or pay to bypass denial.
package/src/api.js CHANGED
@@ -13,6 +13,7 @@ import { EVM_CHAINS } from './chain-ids.js';
13
13
  import { getAnonymousId, TELEMETRY_DISABLED } from './telemetry.js';
14
14
  import { readResponseMeta, stringHeader } from './response-meta.js';
15
15
  import { trace, traceRequest, traceResponse, traceError, traceRetry, traceCacheHit } from './debug.js';
16
+ import { appendPaymentRecord, newPaymentId, sanitizeRequestUrl } from './x402-audit.js';
16
17
 
17
18
  /**
18
19
  * Key for the credit/rate-limit metadata attached to a successful response.
@@ -33,6 +34,41 @@ export const RESPONSE_META = Symbol('nansenResponseMeta');
33
34
  */
34
35
  export const X402_PAYMENT_REJECTED = Symbol('x402PaymentRejected');
35
36
 
37
+ /**
38
+ * True when an x402 rejection body carries a reason code for an underfunded
39
+ * payer, e.g. "insufficient_funds" or "invalid_exact_evm_insufficient_balance".
40
+ * Only the machine-readable reason fields are read, so free text elsewhere in
41
+ * the body (such as an accepts[].description) can't trigger it.
42
+ */
43
+ function isInsufficientBalanceRejection(data) {
44
+ if (data === null || typeof data !== 'object') return false;
45
+ return [data.error, data.invalidReason].some(
46
+ reason => typeof reason === 'string' && /insufficient_(funds|balance)\b/i.test(reason),
47
+ );
48
+ }
49
+
50
+ // A reason code in one letter case: "expired", "invalid_exact_evm_payload_signature",
51
+ // "INVALID_SIGNATURE". Hex and base58 identifiers mix digits and letters in
52
+ // ways this can't match (a lone word has no digits; base58 mixes case), so
53
+ // addresses and account keys are never copied.
54
+ const REASON_CODE = /^(?:[a-z]+(?:_[a-z0-9]+)*|[A-Z]+(?:_[A-Z0-9]+)*)$/;
55
+
56
+ /**
57
+ * The rejection's reason for the audit log, or null. Only a code matching
58
+ * REASON_CODE is copied, never free text. A non-402 status without a code is
59
+ * marked "unexpected_status": the retry still treats it as a rejection, but
60
+ * it is not a payment refusal.
61
+ */
62
+ function rejectionReasonCode(data, status) {
63
+ if (isInsufficientBalanceRejection(data)) return 'insufficient_balance';
64
+ const code = data !== null && typeof data === 'object'
65
+ ? [data.invalidReason, data.error].find(
66
+ reason => typeof reason === 'string' && reason.length <= 100 && REASON_CODE.test(reason),
67
+ )
68
+ : undefined;
69
+ return code ?? (status === 402 ? null : 'unexpected_status');
70
+ }
71
+
36
72
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
37
73
 
38
74
  export function telemetryHeaders() {
@@ -781,27 +817,55 @@ export class NansenAPI {
781
817
  * parsed. In all of those cases the server may already have received and
782
818
  * settled the payment, so the caller must not treat it as safe to retry with
783
819
  * a different option — that would risk paying twice for the same request.
784
- * Logs the payment and warns about low balance when walletLabel and network are given.
820
+ * Logs the payment when walletLabel is given, and warns about low balance
821
+ * when network is given and checkBalance is true. A rejection whose reason
822
+ * code says the payer is underfunded is reported on stderr before the
823
+ * sentinel is returned.
785
824
  *
786
825
  * @param {string} signature - Payment-Signature header value
787
826
  * @param {string|null} walletLabel - Display label for logging, e.g. "local wallet alice"
788
- * @param {string|null} network - x402 network string for balance check, e.g. "eip155:8453"
827
+ * @param {string|null} network - x402 network string the payment was signed for, e.g. "eip155:8453"
789
828
  * @param {string} url - Request URL
790
829
  * @param {object} body - Request body (will be cleaned)
791
830
  * @param {object} [options={}] - Request options (may include .method, .headers)
831
+ * @param {object} [payment={}]
832
+ * @param {string|null} [payment.asset=null] - Token the payment used, for the balance check
833
+ * @param {boolean} [payment.checkBalance=true] - Whether the local default wallet's
834
+ * balance reflects this payment. False for WalletConnect, which pays from an
835
+ * external account the low-balance warning cannot read.
836
+ * @param {string|null} [payment.provider=null] - "local", "privy" or "walletconnect", for the audit log
837
+ * @param {object|null} [payment.decision=null] - The policy decision that approved
838
+ * the payment ({ usd, symbol, payTo, amountRaw }), for the audit log
792
839
  * @returns {Promise<object|typeof X402_PAYMENT_REJECTED>}
793
840
  *
794
841
  * TODO: full fix — extract the entire x402 provider dispatch from request() into
795
842
  * an attemptX402Payment() method so adding a new payment provider only requires
796
843
  * touching that one method, not hunting inside the retry loop.
797
844
  */
798
- async _x402Retry(signature, walletLabel, network, url, body, options = {}, asset = null) {
845
+ async _x402Retry(signature, walletLabel, network, url, body, options = {}, { asset = null, checkBalance = true, provider = null, decision = null } = {}) {
799
846
  // Mirror request(): paid retries must use the original method. Hardcoding
800
847
  // POST burned a payment signature then hit the wrong route for GET/DELETE/PATCH.
801
848
  const method = options.method || 'POST';
802
849
  const isGet = method === 'GET';
803
850
  let paidResponse;
804
851
  const startedAt = Date.now();
852
+ // One "signed" record now and one outcome record before every exit below,
853
+ // sharing an id. Never the signature, bodies or query string.
854
+ const auditBase = {
855
+ id: newPaymentId(),
856
+ provider,
857
+ wallet: walletLabel,
858
+ network,
859
+ asset: decision?.asset ?? null,
860
+ symbol: decision?.symbol ?? null,
861
+ amountUsd: decision?.usd ?? null,
862
+ amountRaw: decision?.amountRaw ?? null,
863
+ payTo: decision?.payTo ?? null,
864
+ method,
865
+ requestUrl: sanitizeRequestUrl(url),
866
+ };
867
+ const audit = (event, fields = {}) => appendPaymentRecord({ ...auditBase, event, ...fields });
868
+ audit('signed');
805
869
  // The signature itself is never traced — only that a paid retry went out.
806
870
  // As in the legacy key flow, payment authenticates this retry on its own.
807
871
  // Do not attach requestCredentials(): Bearer plus payment is rejected by API
@@ -824,6 +888,7 @@ export class NansenAPI {
824
888
  });
825
889
  } catch (err) {
826
890
  traceError({ method, url, durationMs: Date.now() - startedAt, attempt: 1, error: err.message });
891
+ audit('ambiguous', { reason: 'transport_error' });
827
892
  // The signature was already on the wire when the connection failed —
828
893
  // the server may have received and settled it before we lost the
829
894
  // response. Fail closed rather than let the caller sign and send a
@@ -844,10 +909,12 @@ export class NansenAPI {
844
909
  attempt: 1,
845
910
  payment: 'x402',
846
911
  });
912
+ const outcome = { httpStatus: paidResponse.status, requestId: requestIdOf(paidResponse) };
847
913
  if (!paidResponse.ok) {
848
914
  // An admission denial does not prove that a transmitted payment cannot
849
915
  // settle. Stop here instead of authorizing another rail or wallet.
850
916
  if ([401, 403, 429, 451].includes(paidResponse.status)) {
917
+ audit('ambiguous', { ...outcome, reason: 'admission_denied' });
851
918
  throw new NansenError(
852
919
  `x402 payment outcome unknown: paid request was denied (${paidResponse.status}). Not attempting another payment for the same request.`,
853
920
  ErrorCode.PAYMENT_AMBIGUOUS,
@@ -857,25 +924,39 @@ export class NansenAPI {
857
924
  // processed it before failing to respond. Only a readable non-5xx
858
925
  // rejection body is safe to treat as "try the next option".
859
926
  if (paidResponse.status >= 500) {
927
+ audit('ambiguous', { ...outcome, reason: 'server_error' });
860
928
  throw new NansenError(
861
929
  `x402 payment outcome unknown: server returned ${paidResponse.status} after the signed payment was transmitted. Not attempting another payment for the same request.`,
862
930
  ErrorCode.PAYMENT_AMBIGUOUS,
863
931
  );
864
932
  }
933
+ let rejection;
865
934
  try {
866
- await paidResponse.json();
935
+ rejection = await paidResponse.json();
867
936
  } catch (err) {
937
+ audit('ambiguous', { ...outcome, reason: 'unreadable_rejection' });
868
938
  throw new NansenError(
869
939
  `x402 payment outcome unknown: rejection response body was unreadable (${err.message}). Not attempting another payment for the same request.`,
870
940
  ErrorCode.PAYMENT_AMBIGUOUS,
871
941
  );
872
942
  }
943
+ const reason = rejectionReasonCode(rejection, paidResponse.status);
944
+ if (reason === 'insufficient_balance') {
945
+ console.error(
946
+ `[x402] Payment rejected: ${walletLabel || 'the paying wallet'} has an insufficient token balance` +
947
+ `${network ? ` on ${network}` : ''}. Fund it on that network or use another payment option.`,
948
+ );
949
+ }
950
+ audit('rejected', { ...outcome, reason });
873
951
  return X402_PAYMENT_REJECTED;
874
952
  }
953
+ // A 2xx means the payment settled: record it before the balance check and
954
+ // body parse, which can be slow or interrupted.
955
+ audit('accepted', outcome);
875
956
  if (walletLabel) {
876
957
  console.error(`[x402] Paid via ${walletLabel}${network ? ` (${network})` : ''}`);
877
958
  }
878
- if (network) {
959
+ if (network && checkBalance) {
879
960
  try {
880
961
  const { checkX402Balance } = await import('./x402.js');
881
962
  const result = await checkX402Balance(network, asset);
@@ -1085,7 +1166,20 @@ export class NansenAPI {
1085
1166
  }
1086
1167
  }
1087
1168
 
1169
+ // When the session cap stopped every payment, its reason outranks
1170
+ // the generic payment failure below: the fix is to raise the cap, not
1171
+ // to change credentials. Once a payment was sent, its own outcome is
1172
+ // the better explanation. An invalid cap refuses every payment, so
1173
+ // check it once before any wallet or network work.
1174
+ let capRefusal = null;
1175
+ let paymentSent = false;
1176
+ const onCapRefusal = (reason) => { capRefusal = reason; };
1088
1177
  if (mayAutoPay && !hasManualSignature) {
1178
+ const { sessionCapConfigError } = await import('./x402-policy.js');
1179
+ capRefusal = sessionCapConfigError();
1180
+ }
1181
+
1182
+ if (mayAutoPay && !hasManualSignature && !capRefusal) {
1089
1183
  // Determine payment method from default wallet's provider
1090
1184
  let defaultWalletProvider = 'local';
1091
1185
  let defaultWalletName = 'unknown';
@@ -1105,9 +1199,12 @@ export class NansenAPI {
1105
1199
  // Default wallet is Privy: sign via Privy
1106
1200
  try {
1107
1201
  const { createPrivyPaymentSignatures } = await import('./privy.js');
1108
- for await (const { signature, network } of createPrivyPaymentSignatures(response, url)) {
1109
- const result = await this._x402Retry(signature, `Privy wallet ${defaultWalletName}`, network, url, body, options);
1202
+ for await (const { signature, network, asset, payment, releaseCharge } of createPrivyPaymentSignatures(response, url, { onCapRefusal })) {
1203
+ paymentSent = true;
1204
+ const result = await this._x402Retry(signature, `Privy wallet ${defaultWalletName}`, network, url, body, options, { asset, provider: 'privy', decision: payment });
1110
1205
  if (result !== X402_PAYMENT_REJECTED) return result;
1206
+ // A clean rejection settled nothing, so it doesn't count against the session cap.
1207
+ releaseCharge();
1111
1208
  }
1112
1209
  } catch (privyErr) {
1113
1210
  // An ambiguous outcome (transport failure, 5xx, unreadable body)
@@ -1122,10 +1219,13 @@ export class NansenAPI {
1122
1219
  // 1. Try local wallet with fallback across payment networks
1123
1220
  try {
1124
1221
  const { createPaymentSignatures } = await import('./x402.js');
1125
- for await (const { signature, network, asset } of createPaymentSignatures(response, url)) {
1126
- const result = await this._x402Retry(signature, `local wallet ${defaultWalletName}`, network, url, body, options, asset);
1222
+ for await (const { signature, network, asset, payment, releaseCharge } of createPaymentSignatures(response, url, { onCapRefusal })) {
1223
+ paymentSent = true;
1224
+ const result = await this._x402Retry(signature, `local wallet ${defaultWalletName}`, network, url, body, options, { asset, provider: 'local', decision: payment });
1127
1225
  if (result !== X402_PAYMENT_REJECTED) return result;
1128
- // This payment option was cleanly rejected without settling, try next
1226
+ // This payment option was cleanly rejected without settling, so it
1227
+ // doesn't count against the session cap. Try the next one.
1228
+ releaseCharge();
1129
1229
  }
1130
1230
  } catch (localErr) {
1131
1231
  // An ambiguous outcome here means a signed payment may already
@@ -1153,10 +1253,18 @@ export class NansenAPI {
1153
1253
 
1154
1254
  if (paymentRequirements) {
1155
1255
  try {
1156
- const { handleX402Payment } = await import('./walletconnect-x402.js');
1157
- const paymentSignature = await handleX402Payment(paymentRequirements);
1158
- const result = await this._x402Retry(paymentSignature, 'WalletConnect', null, url, body, options);
1159
- if (result !== X402_PAYMENT_REJECTED) return result;
1256
+ const { createWalletConnectPaymentSignatures } = await import('./walletconnect-x402.js');
1257
+ for await (const { signature, network, payment, releaseCharge } of createWalletConnectPaymentSignatures(paymentRequirements, { onCapRefusal })) {
1258
+ // The network is only logged: the post-payment balance
1259
+ // warning reads the local default wallet, not the
1260
+ // WalletConnect account, so it is skipped here.
1261
+ paymentSent = true;
1262
+ const result = await this._x402Retry(signature, 'WalletConnect', network, url, body, options, { checkBalance: false, provider: 'walletconnect', decision: payment });
1263
+ if (result !== X402_PAYMENT_REJECTED) return result;
1264
+ // Cleanly rejected without settling, so it doesn't count
1265
+ // against the session cap. Try the next option.
1266
+ releaseCharge();
1267
+ }
1160
1268
  } catch (x402Err) {
1161
1269
  // WalletConnect is the last resort in this chain — an
1162
1270
  // ambiguous outcome here still must not be reported as an
@@ -1175,6 +1283,8 @@ export class NansenAPI {
1175
1283
  }
1176
1284
  }
1177
1285
 
1286
+ if (capRefusal && !paymentSent) message = capRefusal;
1287
+
1178
1288
  if ((mayAutoPay || hasManualSignature) && (!message || message === data.message)) {
1179
1289
  message = 'Payment required (x402). Sign the paymentRequirements below per https://docs.x402.org and pass the result with --x402-payment-signature <value>.';
1180
1290
  }
@@ -2051,7 +2161,7 @@ export class NansenAPI {
2051
2161
  async researchDexTrades(params = {}) {
2052
2162
  const { tokenAddress, chain = 'solana', fromDate, toDate, filters = {}, orderBy, pagination } = params;
2053
2163
  if (tokenAddress) requireValidToken(tokenAddress, chain);
2054
- return this.request('/api/v1beta1/tgm/historical-dex-trades', {
2164
+ return this.request('/api/v1/tgm/historical-dex-trades', {
2055
2165
  token_address: tokenAddress,
2056
2166
  chain,
2057
2167
  date_range: { from: fromDate, to: toDate },
@@ -2064,7 +2174,7 @@ export class NansenAPI {
2064
2174
  async researchPnlLeaderboard(params = {}) {
2065
2175
  const { tokenAddress, chain = 'solana', fromDate, toDate, filters = {}, orderBy, pagination } = params;
2066
2176
  if (tokenAddress) requireValidToken(tokenAddress, chain);
2067
- return this.request('/api/v1beta1/tgm/historical-pnl-leaderboard', {
2177
+ return this.request('/api/v1/tgm/historical-pnl-leaderboard', {
2068
2178
  token_address: tokenAddress,
2069
2179
  chain,
2070
2180
  date_range: { from: fromDate, to: toDate },
@@ -2078,7 +2188,7 @@ export class NansenAPI {
2078
2188
  // API does not support pagination on this endpoint.
2079
2189
  const { tokenAddress, chain = 'solana', fromDate, toDate, filters = {}, orderBy } = params;
2080
2190
  if (tokenAddress) requireValidToken(tokenAddress, chain);
2081
- return this.request('/api/v1beta1/tgm/historical-token-flow-summary', {
2191
+ return this.request('/api/v1/tgm/historical-token-flow-summary', {
2082
2192
  token_address: tokenAddress,
2083
2193
  chain,
2084
2194
  date_range: { from: fromDate, to: toDate },
@@ -2090,7 +2200,7 @@ export class NansenAPI {
2090
2200
  async researchTokenQuantScores(params = {}) {
2091
2201
  const { tokenAddress, chain = 'solana', asOfDate, filters = {}, orderBy, pagination } = params;
2092
2202
  if (tokenAddress) requireValidToken(tokenAddress, chain);
2093
- return this.request('/api/v1beta1/tgm/historical-token-quant-scores', {
2203
+ return this.request('/api/v1/tgm/historical-token-quant-scores', {
2094
2204
  token_address: tokenAddress,
2095
2205
  chain,
2096
2206
  as_of_date: asOfDate,
@@ -2103,7 +2213,7 @@ export class NansenAPI {
2103
2213
  async researchTopHolders(params = {}) {
2104
2214
  const { tokenAddress, chain = 'solana', asOfDate, filters = {}, orderBy, pagination } = params;
2105
2215
  if (tokenAddress) requireValidToken(tokenAddress, chain);
2106
- return this.request('/api/v1beta1/tgm/historical-top-holders', {
2216
+ return this.request('/api/v1/tgm/historical-top-holders', {
2107
2217
  token_address: tokenAddress,
2108
2218
  chain,
2109
2219
  as_of_date: asOfDate,
@@ -2116,7 +2226,7 @@ export class NansenAPI {
2116
2226
  async researchWhoBoughtSold(params = {}) {
2117
2227
  const { tokenAddress, chain = 'solana', fromDate, toDate, buyOrSell = 'BUY', filters = {}, orderBy, pagination } = params;
2118
2228
  if (tokenAddress) requireValidToken(tokenAddress, chain);
2119
- return this.request('/api/v1beta1/tgm/historical-who-bought-sold', {
2229
+ return this.request('/api/v1/tgm/historical-who-bought-sold', {
2120
2230
  token_address: tokenAddress,
2121
2231
  chain,
2122
2232
  buy_or_sell: buyOrSell,
@@ -2130,7 +2240,7 @@ export class NansenAPI {
2130
2240
  async researchSmartMoneyBalances(params = {}) {
2131
2241
  // API does not support order_by on this endpoint.
2132
2242
  const { chains = ['solana'], asOfDate, filters = {}, pagination } = params;
2133
- return this.request('/api/v1beta1/smart-money/historical-token-balances', {
2243
+ return this.request('/api/v1/smart-money/historical-token-balances', {
2134
2244
  chains,
2135
2245
  as_of_date: asOfDate,
2136
2246
  filters,
@@ -2153,7 +2263,7 @@ export class NansenAPI {
2153
2263
  async researchWalletBalances(params = {}) {
2154
2264
  const { address, chain = 'ethereum', asOfDate, filters = {}, orderBy, pagination } = params;
2155
2265
  if (address) requireValidAddress(address, chain);
2156
- return this.request('/api/v1beta1/profiler/address/historical-token-balances', {
2266
+ return this.request('/api/v1/profiler/address/historical-token-balances', {
2157
2267
  address,
2158
2268
  chain,
2159
2269
  as_of_date: asOfDate,
@@ -2171,13 +2281,13 @@ export class NansenAPI {
2171
2281
  as_of_date: asOfDate,
2172
2282
  };
2173
2283
  if (blockTimestamp) body.block_timestamp = blockTimestamp;
2174
- return this.request('/api/v1beta1/profiler/historical-transaction-lookup', body);
2284
+ return this.request('/api/v1/profiler/historical-transaction-lookup', body);
2175
2285
  }
2176
2286
 
2177
2287
  async researchWalletTransactions(params = {}) {
2178
2288
  const { address, chain = 'ethereum', asOfDate, filters = {}, orderBy, pagination } = params;
2179
2289
  if (address) requireValidAddress(address, chain);
2180
- return this.request('/api/v1beta1/profiler/address/historical-transactions', {
2290
+ return this.request('/api/v1/profiler/address/historical-transactions', {
2181
2291
  address,
2182
2292
  chain,
2183
2293
  as_of_date: asOfDate,