nansen-cli 1.44.2 → 1.45.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.
@@ -8,23 +8,9 @@
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
12
  import { evaluatePaymentRequirement, resolvePaymentAmount, resolvePayTo } from './x402-policy.js';
12
13
 
13
- /**
14
- * Check if a WalletConnect wallet session is active.
15
- * Returns { wallet, accounts, expires } or null.
16
- */
17
- export async function checkWalletConnection() {
18
- try {
19
- const output = await wcExec('walletconnect', ['whoami', '--json'], 3000);
20
- const data = JSON.parse(output);
21
- if (data.connected === false) return null;
22
- return data;
23
- } catch {
24
- return null;
25
- }
26
- }
27
-
28
14
  /**
29
15
  * Select a compatible payment requirement from the accepts array.
30
16
  * Requires scheme=exact and EIP-3009 TransferWithAuthorization support (extra.name + extra.version).
@@ -160,28 +146,7 @@ function formatPaymentAmount(requirement) {
160
146
  * @throws {NansenError} On failure
161
147
  */
162
148
  export async function handleX402Payment(paymentRequirements) {
163
- // 1. Check wallet connection
164
- const wallet = await checkWalletConnection();
165
- if (!wallet) {
166
- throw new NansenError(
167
- 'x402 payment required but no wallet connected. ' +
168
- 'To pay automatically: create a local wallet with `nansen wallet create` (then set NANSEN_WALLET_PASSWORD), ' +
169
- 'or connect an external wallet via the `walletconnect` CLI (`walletconnect connect`).',
170
- ErrorCode.PAYMENT_REQUIRED,
171
- 402
172
- );
173
- }
174
-
175
- const fromAddress = wallet.accounts[0]?.address;
176
- if (!fromAddress) {
177
- throw new NansenError(
178
- 'x402 payment required but wallet has no accounts.',
179
- ErrorCode.PAYMENT_REQUIRED,
180
- 402
181
- );
182
- }
183
-
184
- // 2. Select compatible payment requirement
149
+ // 1. Select compatible payment requirement
185
150
  const accepts = paymentRequirements.accepts || paymentRequirements;
186
151
  const requirement = selectPaymentRequirement(Array.isArray(accepts) ? accepts : [accepts]);
187
152
  if (!requirement) {
@@ -193,12 +158,37 @@ export async function handleX402Payment(paymentRequirements) {
193
158
  );
194
159
  }
195
160
 
196
- // 3. Evaluate payment policy before touching any signing material
161
+ // 2. Evaluate payment policy before touching any signing material
197
162
  const decision = evaluatePaymentRequirement(requirement);
198
163
  if (!decision.ok) {
199
164
  throw new Error(decision.reason);
200
165
  }
201
166
 
167
+ // 3. Resolve the WalletConnect signer scoped to this exact chain. EVM
168
+ // addresses are identical across chains, so "some account exists in the
169
+ // session" can't prove the session was actually approved for THIS chain --
170
+ // only the CAIP-2 chain tag can (mirrors getWalletConnectAddress's chainId
171
+ // param, used the same way before signing/broadcasting in trading.js and
172
+ // transfer.js). Without this, a session connected only to, say, Base would
173
+ // be silently accepted to authorize a payment on BNB Chain or X Layer --
174
+ // the same defect class fixed in #615, just unguarded here because this
175
+ // path never reused getWalletConnectAddress and instead took accounts[0]
176
+ // with no chain filter at all.
177
+ const chainId = parseChainId(requirement.network);
178
+ if (chainId === null) {
179
+ throw new Error(`Refusing to auto-pay: unsupported or missing EVM network ${requirement.network}.`);
180
+ }
181
+ const fromAddress = await getWalletConnectAddress('evm', chainId);
182
+ if (!fromAddress) {
183
+ throw new NansenError(
184
+ `x402 payment required but no WalletConnect session is active for chain ${requirement.network}. ` +
185
+ 'To pay automatically: create a local wallet with `nansen wallet create` (then set NANSEN_WALLET_PASSWORD), ' +
186
+ 'or connect an external wallet approved for this chain via the `walletconnect` CLI (`walletconnect connect`).',
187
+ ErrorCode.PAYMENT_REQUIRED,
188
+ 402
189
+ );
190
+ }
191
+
202
192
  // 4. Build EIP-712 typed data
203
193
  const typedData = buildEIP712TypedData({ fromAddress, requirement });
204
194
  const typedDataJson = JSON.stringify(typedData);
package/src/x402-svm.js CHANGED
@@ -312,18 +312,59 @@ export function createSvmPaymentPayload(
312
312
  * Fetch recent blockhash from Solana RPC.
313
313
  */
314
314
  export async function fetchRecentBlockhash(rpcUrl = 'https://api.mainnet-beta.solana.com') {
315
- const response = await fetch(rpcUrl, {
316
- method: 'POST',
317
- headers: { 'Content-Type': 'application/json' },
318
- body: JSON.stringify({
319
- jsonrpc: '2.0',
320
- id: 1,
321
- method: 'getLatestBlockhash',
322
- params: [{ commitment: 'finalized' }],
323
- }),
324
- });
325
- const data = await response.json();
326
- return data.result.value.blockhash;
315
+ let response;
316
+ try {
317
+ response = await fetch(rpcUrl, {
318
+ method: 'POST',
319
+ headers: { 'Content-Type': 'application/json' },
320
+ body: JSON.stringify({
321
+ jsonrpc: '2.0',
322
+ id: 1,
323
+ method: 'getLatestBlockhash',
324
+ params: [{ commitment: 'finalized' }],
325
+ }),
326
+ });
327
+ } catch (err) {
328
+ throw new Error(
329
+ `Solana RPC unavailable while fetching a recent blockhash. Retry or configure a different RPC endpoint. ${String(err.message ?? err)}`,
330
+ { cause: err }
331
+ );
332
+ }
333
+
334
+ if (!response.ok) {
335
+ const text = await response.text().catch(() => '');
336
+ throw new Error(
337
+ `Solana RPC returned HTTP ${response.status} while fetching a recent blockhash. Retry or configure a different RPC endpoint. ${text.slice(0, 100)}`
338
+ );
339
+ }
340
+
341
+ let data;
342
+ try {
343
+ data = await response.json();
344
+ } catch {
345
+ throw new Error(
346
+ 'Solana RPC returned an invalid response while fetching a recent blockhash. Retry or configure a different RPC endpoint.'
347
+ );
348
+ }
349
+
350
+ if (data?.error) {
351
+ const detail =
352
+ data.error.message != null ? String(data.error.message)
353
+ : data.error.code != null ? String(data.error.code)
354
+ : 'unknown RPC error';
355
+ throw new Error(
356
+ `Solana RPC failed while fetching a recent blockhash: ${detail}. Retry or configure a different RPC endpoint.`
357
+ );
358
+ }
359
+
360
+ const blockhash = data?.result?.value?.blockhash;
361
+ if (typeof blockhash !== 'string' || blockhash.length === 0) {
362
+ throw new Error(
363
+ 'Solana RPC returned no recent blockhash. Retry or configure a different RPC endpoint.'
364
+ );
365
+ }
366
+
367
+ return blockhash;
327
368
  }
328
369
 
329
370
  /**