nansen-cli 1.44.2 → 1.44.3
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 +20 -0
- package/package.json +1 -1
- package/src/commands/agent.js +65 -37
- package/src/commands/alerts.js +14 -10
- package/src/trade-validation.js +39 -5
- package/src/trading.js +14 -0
- package/src/walletconnect-x402.js +28 -38
- package/src/x402-svm.js +53 -12
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,25 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.44.3
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#621](https://github.com/nansen-ai/nansen-cli/pull/621) [`6ece0a1`](https://github.com/nansen-ai/nansen-cli/commit/6ece0a14290444472f0784115e678e73deb3981f) Thanks [@kome12](https://github.com/kome12)! - Validate alerts list pagination flags before fetching alerts.
|
|
8
|
+
|
|
9
|
+
- [#620](https://github.com/nansen-ai/nansen-cli/pull/620) [`bf8f40f`](https://github.com/nansen-ai/nansen-cli/commit/bf8f40f840495d7a92d95d105d131b5406a10e22) Thanks [@Radovenchyk](https://github.com/Radovenchyk)! - Fix `nansen agent` throwing a raw `AbortError` instead of a `NansenError(TIMEOUT)` when the request timeout fires while reading the SSE response body (as opposed to during the initial connection). Both streaming and `--json` output modes now report a consistent timeout error regardless of which phase of the request the abort happened in.
|
|
10
|
+
|
|
11
|
+
- [#618](https://github.com/nansen-ai/nansen-cli/pull/618) [`1e08a15`](https://github.com/nansen-ai/nansen-cli/commit/1e08a150295b44768ce954b9628de10e291924f4) Thanks [@Radovenchyk](https://github.com/Radovenchyk)! - Fix `consumeSSEStream` silently dropping the final SSE event when the stream closes without a trailing blank line (e.g. a `finish` event carrying `conversation_id`, or a trailing `delta` chunk).
|
|
12
|
+
|
|
13
|
+
- [#623](https://github.com/nansen-ai/nansen-cli/pull/623) [`9ae1dc2`](https://github.com/nansen-ai/nansen-cli/commit/9ae1dc2d871b04fae749c7126f970258bf58f41e) Thanks [@kome12](https://github.com/kome12)! - Improve Solana raw-instruction bridge error handling for RPC failures and malformed instruction data.
|
|
14
|
+
|
|
15
|
+
- [#622](https://github.com/nansen-ai/nansen-cli/pull/622) [`d86aae9`](https://github.com/nansen-ai/nansen-cli/commit/d86aae9e8d45d0427fbc0d51363529b5873d8dd0) Thanks [@kome12](https://github.com/kome12)! - Tolerate small refunded native input amounts during bridge outcome verification.
|
|
16
|
+
|
|
17
|
+
- [#617](https://github.com/nansen-ai/nansen-cli/pull/617) [`d048c0f`](https://github.com/nansen-ai/nansen-cli/commit/d048c0f3bb4e5ded6c42324ec7d3e32b58bfd4ee) Thanks [@teyrebaz33](https://github.com/teyrebaz33)! - Fix x402 auto-payment via WalletConnect signing a payment authorization from any connected EVM account instead of verifying the WalletConnect session is actually approved for the payment's chain.
|
|
18
|
+
|
|
19
|
+
`handleX402Payment` resolved its signer with its own `checkWalletConnection()` helper and took `wallet.accounts[0]?.address` with no chain filtering at all -- the same defect class fixed in `getWalletConnectAddress` for `nansen transfer`/`nansen trade execute` (see the WalletConnect chain-scoped signing fix), just left unguarded here because this path never reused that helper. Because EVM addresses are identical across chains, a WalletConnect session approved only for, say, Base could be silently used to authorize an x402 payment on BNB Smart Chain or X Layer -- the other two EVM networks Nansen's x402 payments support.
|
|
20
|
+
|
|
21
|
+
`handleX402Payment` now resolves its signer via `getWalletConnectAddress('evm', chainId)`, scoped to the exact chain of the selected payment requirement, and refuses to pay with a clear error when no WalletConnect session is approved for that chain. The now-unused, duplicate `checkWalletConnection` helper was removed.
|
|
22
|
+
|
|
3
23
|
## 1.44.2
|
|
4
24
|
|
|
5
25
|
### Patch Changes
|
package/package.json
CHANGED
package/src/commands/agent.js
CHANGED
|
@@ -66,11 +66,49 @@ export async function consumeSSEStream(response, callbacks = {}) {
|
|
|
66
66
|
const toolCalls = [];
|
|
67
67
|
let conversationId = null;
|
|
68
68
|
let errorPayload = null;
|
|
69
|
+
let done = false;
|
|
69
70
|
|
|
70
71
|
const reader = response.body;
|
|
71
72
|
const decoder = new TextDecoder();
|
|
72
73
|
let buffer = '';
|
|
73
74
|
|
|
75
|
+
const processFrame = (frame) => {
|
|
76
|
+
for (const line of frame.split('\n')) {
|
|
77
|
+
if (!line.startsWith('data: ')) continue;
|
|
78
|
+
const payload = line.slice(6);
|
|
79
|
+
if (payload === '[DONE]') { done = true; return; }
|
|
80
|
+
|
|
81
|
+
let event;
|
|
82
|
+
try {
|
|
83
|
+
event = JSON.parse(payload);
|
|
84
|
+
} catch {
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
switch (event.type) {
|
|
89
|
+
case 'delta':
|
|
90
|
+
if (event.text) {
|
|
91
|
+
chunks.push(event.text);
|
|
92
|
+
if (onDelta) onDelta(event.text);
|
|
93
|
+
}
|
|
94
|
+
break;
|
|
95
|
+
case 'tool_call':
|
|
96
|
+
if (event.name) {
|
|
97
|
+
toolCalls.push(event.name);
|
|
98
|
+
if (onToolCall) onToolCall(event.name);
|
|
99
|
+
}
|
|
100
|
+
break;
|
|
101
|
+
case 'finish':
|
|
102
|
+
conversationId = event.conversation_id ?? null;
|
|
103
|
+
break;
|
|
104
|
+
case 'error':
|
|
105
|
+
errorPayload = event;
|
|
106
|
+
break;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
outer:
|
|
74
112
|
for await (const raw of reader) {
|
|
75
113
|
buffer += decoder.decode(raw, { stream: true });
|
|
76
114
|
|
|
@@ -79,47 +117,19 @@ export async function consumeSSEStream(response, callbacks = {}) {
|
|
|
79
117
|
|
|
80
118
|
// SSE: split on double-newline boundaries
|
|
81
119
|
let boundary;
|
|
82
|
-
let done = false;
|
|
83
120
|
while ((boundary = buffer.indexOf('\n\n')) !== -1) {
|
|
84
121
|
const frame = buffer.slice(0, boundary);
|
|
85
122
|
buffer = buffer.slice(boundary + 2);
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
if (!line.startsWith('data: ')) continue;
|
|
89
|
-
const payload = line.slice(6);
|
|
90
|
-
if (payload === '[DONE]') { done = true; break; }
|
|
91
|
-
|
|
92
|
-
let event;
|
|
93
|
-
try {
|
|
94
|
-
event = JSON.parse(payload);
|
|
95
|
-
} catch {
|
|
96
|
-
continue;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
switch (event.type) {
|
|
100
|
-
case 'delta':
|
|
101
|
-
if (event.text) {
|
|
102
|
-
chunks.push(event.text);
|
|
103
|
-
if (onDelta) onDelta(event.text);
|
|
104
|
-
}
|
|
105
|
-
break;
|
|
106
|
-
case 'tool_call':
|
|
107
|
-
if (event.name) {
|
|
108
|
-
toolCalls.push(event.name);
|
|
109
|
-
if (onToolCall) onToolCall(event.name);
|
|
110
|
-
}
|
|
111
|
-
break;
|
|
112
|
-
case 'finish':
|
|
113
|
-
conversationId = event.conversation_id ?? null;
|
|
114
|
-
break;
|
|
115
|
-
case 'error':
|
|
116
|
-
errorPayload = event;
|
|
117
|
-
break;
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
if (done) break;
|
|
123
|
+
processFrame(frame);
|
|
124
|
+
if (done) break outer;
|
|
121
125
|
}
|
|
122
|
-
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Flush a trailing unterminated frame (stream closed without \n\n after
|
|
129
|
+
// the last event, e.g. 'finish' or a final 'delta').
|
|
130
|
+
if (!done && buffer.trim() !== '') {
|
|
131
|
+
buffer += decoder.decode(); // flush any pending multi-byte UTF-8 tail
|
|
132
|
+
processFrame(buffer);
|
|
123
133
|
}
|
|
124
134
|
|
|
125
135
|
if (errorPayload) {
|
|
@@ -300,11 +310,27 @@ EXAMPLES:
|
|
|
300
310
|
);
|
|
301
311
|
}
|
|
302
312
|
|
|
313
|
+
// Abort can also fire while reading the SSE body, not just during
|
|
314
|
+
// fetch() — wrap that AbortError the same way for a consistent error.
|
|
315
|
+
const wrapAbortDuringStream = (err) => {
|
|
316
|
+
if (err.name === 'AbortError') {
|
|
317
|
+
throw new NansenError(
|
|
318
|
+
`Request timed out after ${timeoutMs / 1000}s`,
|
|
319
|
+
ErrorCode.TIMEOUT,
|
|
320
|
+
504,
|
|
321
|
+
{ detail: `${modeName} mode timeout (${timeoutMs / 1000}s)` },
|
|
322
|
+
);
|
|
323
|
+
}
|
|
324
|
+
throw err;
|
|
325
|
+
};
|
|
326
|
+
|
|
303
327
|
// ── JSON mode: buffer everything, return structured data ──
|
|
304
328
|
if (flags.json) {
|
|
305
329
|
let result;
|
|
306
330
|
try {
|
|
307
331
|
result = await consumeSSEStream(response);
|
|
332
|
+
} catch (err) {
|
|
333
|
+
return wrapAbortDuringStream(err); // always throws; return makes intent explicit
|
|
308
334
|
} finally {
|
|
309
335
|
clearTimeout(timer);
|
|
310
336
|
}
|
|
@@ -333,6 +359,8 @@ EXAMPLES:
|
|
|
333
359
|
errorLog(`⚙ ${name}`);
|
|
334
360
|
},
|
|
335
361
|
});
|
|
362
|
+
} catch (err) {
|
|
363
|
+
return wrapAbortDuringStream(err); // always throws; return makes intent explicit
|
|
336
364
|
} finally {
|
|
337
365
|
clearTimeout(timer);
|
|
338
366
|
}
|
package/src/commands/alerts.js
CHANGED
|
@@ -124,6 +124,15 @@ function parseFiniteNumber(raw, name) {
|
|
|
124
124
|
return n;
|
|
125
125
|
}
|
|
126
126
|
|
|
127
|
+
function parseNonNegativeIntegerOption(raw, name) {
|
|
128
|
+
if (raw === undefined) return undefined;
|
|
129
|
+
const n = Number(raw);
|
|
130
|
+
if (!Number.isInteger(n) || n < 0) {
|
|
131
|
+
throw new NansenError(`--${name} must be a non-negative integer, got "${raw}"`, ErrorCode.INVALID_PARAMS);
|
|
132
|
+
}
|
|
133
|
+
return n;
|
|
134
|
+
}
|
|
135
|
+
|
|
127
136
|
/**
|
|
128
137
|
* Build a { min, max } range object from two option values.
|
|
129
138
|
* Returns undefined if neither is provided.
|
|
@@ -601,6 +610,9 @@ USAGE:
|
|
|
601
610
|
'list': async () => {
|
|
602
611
|
if (flags.enabled && flags.disabled) throw new NansenError('Cannot specify both --enabled and --disabled', ErrorCode.INVALID_PARAMS);
|
|
603
612
|
|
|
613
|
+
const offset = parseNonNegativeIntegerOption(options.offset, 'offset');
|
|
614
|
+
const limit = parseNonNegativeIntegerOption(options.limit, 'limit');
|
|
615
|
+
|
|
604
616
|
const results = await apiInstance.alertsList();
|
|
605
617
|
let alerts = Array.isArray(results) ? results : results?.alerts ?? results?.data ?? [];
|
|
606
618
|
|
|
@@ -635,18 +647,10 @@ USAGE:
|
|
|
635
647
|
// - Negative values (`--offset -1`) were accepted and fed straight
|
|
636
648
|
// into `slice()`, which treats negative indices as "from the end" —
|
|
637
649
|
// silently returning the wrong slice instead of rejecting the input.
|
|
638
|
-
if (
|
|
639
|
-
const offset = Number(options.offset);
|
|
640
|
-
if (!Number.isInteger(offset) || offset < 0) {
|
|
641
|
-
throw new NansenError(`--offset must be a non-negative integer, got "${options.offset}"`, ErrorCode.INVALID_PARAMS);
|
|
642
|
-
}
|
|
650
|
+
if (offset !== undefined) {
|
|
643
651
|
alerts = alerts.slice(offset);
|
|
644
652
|
}
|
|
645
|
-
if (
|
|
646
|
-
const limit = Number(options.limit);
|
|
647
|
-
if (!Number.isInteger(limit) || limit < 0) {
|
|
648
|
-
throw new NansenError(`--limit must be a non-negative integer, got "${options.limit}"`, ErrorCode.INVALID_PARAMS);
|
|
649
|
-
}
|
|
653
|
+
if (limit !== undefined) {
|
|
650
654
|
alerts = alerts.slice(0, limit);
|
|
651
655
|
}
|
|
652
656
|
|
package/src/trade-validation.js
CHANGED
|
@@ -174,6 +174,14 @@ const NATIVE_TOKEN_ADDRESSES = {
|
|
|
174
174
|
// legitimately needs more.
|
|
175
175
|
export const EVM_BRIDGE_NATIVE_FEE_SLACK = 2_000_000_000_000_000n; // 0.002 ETH
|
|
176
176
|
|
|
177
|
+
// Tolerance for a native-ETH refund on an exact-in bridge: some routers receive
|
|
178
|
+
// msg.value = request.amount and return a small unused remainder, so the sim's net
|
|
179
|
+
// outflow can be slightly below the requested input on a correctly funded bridge.
|
|
180
|
+
// Same numeric cap as EVM_BRIDGE_NATIVE_FEE_SLACK (conservative, gas-independent);
|
|
181
|
+
// kept separate so sibling-fee and input-refund tolerances protect distinct
|
|
182
|
+
// assertions and remain distinguishable in reviews.
|
|
183
|
+
export const EVM_BRIDGE_NATIVE_INPUT_REFUND_SLACK = 2_000_000_000_000_000n; // 0.002 ETH
|
|
184
|
+
|
|
177
185
|
// Native SOL has two on-chain spellings that denote the same asset: the
|
|
178
186
|
// canonical wrapped-SOL mint (what the CLI resolves `SOL` to and persists as
|
|
179
187
|
// the request intent) and the System Program address that aggregators and
|
|
@@ -966,7 +974,9 @@ export function isBridgeRequest(request) {
|
|
|
966
974
|
* Four assertions, all derived from the persisted request intent + the quote:
|
|
967
975
|
* 1. the input token leaves the wallet by no MORE than maxInputAmount. Native
|
|
968
976
|
* input excludes gas: the sim deltas are log-based, so gas (not a transfer
|
|
969
|
-
* log) is never counted.
|
|
977
|
+
* log) is never counted. For exact-in cross-chain bridges with native ETH
|
|
978
|
+
* input, the lower outflow floor is relaxed by EVM_BRIDGE_NATIVE_INPUT_REFUND_SLACK
|
|
979
|
+
* to tolerate routers that refund a small unused remainder of msg.value.
|
|
970
980
|
* 2. the output token arrives by AT LEAST minOut — exactOut: >= the requested
|
|
971
981
|
* output; exactIn: the quoted output reduced by the slippage in effect.
|
|
972
982
|
* SKIPPED for a cross-chain bridge: the output settles on the destination
|
|
@@ -1033,6 +1043,7 @@ export function assertSwapOutcome(request, quote, sim, { slippage, expectedSpend
|
|
|
1033
1043
|
|
|
1034
1044
|
// Bridges skip only assertion 2 (output arrival) below — see isBridgeRequest.
|
|
1035
1045
|
const isBridge = isBridgeRequest(request);
|
|
1046
|
+
const inputIsNative = inputToken === EVM_NATIVE_SENTINEL;
|
|
1036
1047
|
|
|
1037
1048
|
// --- Assertion 1: input outflow within the spend ceiling ---
|
|
1038
1049
|
// This bounds the outflow by maxInputAmount (the slippage-buffered ceiling),
|
|
@@ -1073,8 +1084,9 @@ export function assertSwapOutcome(request, quote, sim, { slippage, expectedSpend
|
|
|
1073
1084
|
// fee-only or 1-unit no-op would still verify a bridge that never funded its
|
|
1074
1085
|
// input. For exactIn the outflow must be ~the requested input (assertion 1
|
|
1075
1086
|
// already caps it above); for exactOut the input is variable up to the cap, so
|
|
1076
|
-
// only a positive-outflow floor is meaningful.
|
|
1077
|
-
//
|
|
1087
|
+
// only a positive-outflow floor is meaningful. For native ETH input the floor
|
|
1088
|
+
// is relaxed by EVM_BRIDGE_NATIVE_INPUT_REFUND_SLACK to tolerate routers that
|
|
1089
|
+
// refund a small unused portion of msg.value; token input floors remain exact.
|
|
1078
1090
|
if (isBridge) {
|
|
1079
1091
|
if (swapMode === 'exactIn') {
|
|
1080
1092
|
if (request.amount == null) throw fail('bridge exactIn request is missing the requested input amount.');
|
|
@@ -1085,8 +1097,19 @@ export function assertSwapOutcome(request, quote, sim, { slippage, expectedSpend
|
|
|
1085
1097
|
throw fail(`requested input amount (${request.amount}) is not an integer.`);
|
|
1086
1098
|
}
|
|
1087
1099
|
if (requested <= 0n) throw fail(`bridge exactIn request has a non-positive input amount (${requested}).`);
|
|
1088
|
-
|
|
1089
|
-
|
|
1100
|
+
const floorSlack = inputIsNative ? EVM_BRIDGE_NATIVE_INPUT_REFUND_SLACK : 0n;
|
|
1101
|
+
// Cap at requested / 2n: for bridges below 2 × EVM_BRIDGE_NATIVE_INPUT_REFUND_SLACK
|
|
1102
|
+
// (~0.004 ETH), the applied slack shrinks proportionally so the floor stays ≥ 50 %
|
|
1103
|
+
// of the requested amount rather than collapsing toward zero.
|
|
1104
|
+
const appliedSlack = floorSlack < requested / 2n ? floorSlack : requested / 2n;
|
|
1105
|
+
const minOutflow = requested - appliedSlack;
|
|
1106
|
+
if (outflow < minOutflow) {
|
|
1107
|
+
throw fail(
|
|
1108
|
+
`the bridge moved only ${outflow} of the input token (${inputToken}) out of the wallet, ` +
|
|
1109
|
+
`below the minimum required outflow (${minOutflow})` +
|
|
1110
|
+
`${inputIsNative ? ` (requested ${requested} minus native refund slack ${appliedSlack})` : ''}` +
|
|
1111
|
+
`; a bridge must spend its input on the source chain.`
|
|
1112
|
+
);
|
|
1090
1113
|
}
|
|
1091
1114
|
} else if (outflow <= 0n) {
|
|
1092
1115
|
throw fail(`the bridge moved no input token (${inputToken}) out of the wallet; a bridge must spend its input on the source chain.`);
|
|
@@ -1164,6 +1187,17 @@ export function assertSwapOutcome(request, quote, sim, { slippage, expectedSpend
|
|
|
1164
1187
|
// threshold the caller passes (gas is already excluded from the native delta).
|
|
1165
1188
|
// ERC-20 siblings and every same-chain swap keep strict-zero. This mirrors the
|
|
1166
1189
|
// native-only carve-out assertSolanaSwapOutcome already applies for SOL.
|
|
1190
|
+
//
|
|
1191
|
+
// Empirically (survey of the shipping quote path, Sept 2026) no reachable Base
|
|
1192
|
+
// token-input bridge route charges such a native fee: the live aggregator for
|
|
1193
|
+
// Base bridges returns tx.value 0 on token inputs, and the other aggregator
|
|
1194
|
+
// returns no Base route at all. So this carve-out is latent defense-in-depth
|
|
1195
|
+
// today, kept because backend routing can change (a new route, or a fee added).
|
|
1196
|
+
//
|
|
1197
|
+
// Wallet-owned intermediate-token bridge routes are intentionally unsupported
|
|
1198
|
+
// here unless a future quote format identifies the intermediate token and a
|
|
1199
|
+
// safe maximum outflow. Treat every ERC-20 sibling as strict-zero so a route
|
|
1200
|
+
// cannot drain unrelated wallet holdings under the label of "intermediate".
|
|
1167
1201
|
const nativeDust = isBridge && siblingDustThreshold > 0n ? siblingDustThreshold : 0n;
|
|
1168
1202
|
for (const [token, delta] of Object.entries(deltas)) {
|
|
1169
1203
|
if (token === inputToken) continue; // its outflow is bounded by assertion 1
|
package/src/trading.js
CHANGED
|
@@ -635,8 +635,22 @@ export function signSolanaTransaction(transactionBase64, privateKeyHex) {
|
|
|
635
635
|
// blockhash fetch (no wasted RPC round trip on a request we're going to reject).
|
|
636
636
|
const SIZE_CHECK_BLOCKHASH = '11111111111111111111111111111111';
|
|
637
637
|
|
|
638
|
+
function formatInstructionDataForError(value) {
|
|
639
|
+
try {
|
|
640
|
+
const s = JSON.stringify(value);
|
|
641
|
+
return s.length > 200 ? s.slice(0, 200) + '…' : s;
|
|
642
|
+
} catch {
|
|
643
|
+
return String(value);
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
|
|
638
647
|
function decodeInstructionData(hex) {
|
|
639
648
|
if (hex == null || hex === '') return Buffer.alloc(0); // some instructions legitimately carry no data
|
|
649
|
+
if (typeof hex !== 'string') {
|
|
650
|
+
throw new Error(
|
|
651
|
+
`Cannot compile Solana transaction: instruction data is not valid hex (${formatInstructionDataForError(hex)})`
|
|
652
|
+
);
|
|
653
|
+
}
|
|
640
654
|
const body = hex.startsWith('0x') ? hex.slice(2) : hex;
|
|
641
655
|
// Buffer.from(str, 'hex') silently drops a trailing odd nibble and stops at
|
|
642
656
|
// the first non-hex character, so it would decode malformed data into a
|
|
@@ -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.
|
|
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
|
-
//
|
|
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
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
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
|
/**
|