nansen-cli 1.44.0 → 1.44.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/CHANGELOG.md +28 -0
- package/package.json +1 -1
- package/src/api.js +22 -5
- package/src/cli.js +39 -4
- package/src/commands/alerts.js +56 -16
- package/src/limit-order.js +196 -18
- package/src/schema.json +11 -2
- package/src/telemetry.js +15 -5
- package/src/trade-validation.js +222 -5
- package/src/trading.js +3 -2
- package/src/walletconnect-x402.js +25 -4
- package/src/x402-evm.js +8 -4
- package/src/x402-policy.js +16 -1
- package/src/x402-svm.js +9 -7
- package/src/x402-tokens.js +7 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,33 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.44.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#588](https://github.com/nansen-ai/nansen-cli/pull/588) [`0db1c74`](https://github.com/nansen-ai/nansen-cli/commit/0db1c745b4cdfd05b47bd261159bace7b60f0854) Thanks [@Kewe63](https://github.com/Kewe63)! - Prevent duplicate alert creation after ambiguous network failures and keep Smart Alert mutations out of the response cache.
|
|
8
|
+
|
|
9
|
+
- [#595](https://github.com/nansen-ai/nansen-cli/pull/595) [`1e3fadb`](https://github.com/nansen-ai/nansen-cli/commit/1e3fadb346be2219e8d91ba417806ae7f5b9bcd9) Thanks [@devorun](https://github.com/devorun)! - Fix `--cache` reshaping a cached array response into an object. Endpoints that return a top-level JSON array were object-spread on a cache hit, so `[a, b]` came back as `{ 0: a, 1: b }` and every `Array.isArray()` branch downstream stopped matching — the first call printed rows and the second printed nothing. Cached arrays now stay arrays, and primitive response bodies are returned untouched instead of being exploded into character maps.
|
|
10
|
+
|
|
11
|
+
- [#589](https://github.com/nansen-ai/nansen-cli/pull/589) [`0cc4c18`](https://github.com/nansen-ai/nansen-cli/commit/0cc4c180e5525b6bf8a777d04401ac60b7c926a8) Thanks [@ygd58](https://github.com/ygd58)! - Fix `nansen alerts list --limit`/`--offset` silently misbehaving on invalid or edge-case input. `--limit 0` and `--offset 0` were treated as "not set" (falsy check) and silently ignored instead of honored; a non-numeric value like `--limit abc` silently returned zero results (`Array.prototype.slice` coerces `NaN` to `0`) instead of erroring; and a negative `--offset` was silently accepted by `slice()`, which treats negative indices as "from the end" — returning the wrong records instead of rejecting the input. Both flags are now validated as non-negative integers, matching the strict-validation convention already used elsewhere in the CLI (e.g. `--slippage`), and throw a clear `INVALID_PARAMS` error otherwise.
|
|
12
|
+
|
|
13
|
+
- [#577](https://github.com/nansen-ai/nansen-cli/pull/577) [`3c214a1`](https://github.com/nansen-ai/nansen-cli/commit/3c214a179a3f2c78a8b4b17e2c6b1177828bf2c6) Thanks [@batuhankocyigit](https://github.com/batuhankocyigit)! - Fix `nansen alerts create`/`update` silently dropping numeric range filters (`--usd-min/max`, `--market-cap-min/max`, `--fdv-min/max`, `--token-amount-min/max`, `--token-age-min/max`, and the `--inflow/outflow/netflow-*-min/max` flags) instead of rejecting bad input. These flags were converted with plain `Number(val)`, so a typo or garbage value (e.g. `--usd-min abc`) became `NaN`, which `JSON.stringify` silently turns into `null` in the request body — the alert would get created without the filter the user thought they'd set, with no error at any point. `--*-min`/`--*-max` now reject non-numeric input with a clear `Invalid --<flag> "<value>": must be a number` error; valid negative values (e.g. `--netflow-1h-min -5000` for a net-outflow filter) are unaffected.
|
|
14
|
+
|
|
15
|
+
- [#605](https://github.com/nansen-ai/nansen-cli/pull/605) [`9656d08`](https://github.com/nansen-ai/nansen-cli/commit/9656d08e2df3562ac650d299a5fc6b92bf00d8ad) Thanks [@kome12](https://github.com/kome12)! - Keep non-JSON 4xx responses from trade execute reusable instead of treating them as ambiguous broadcast failures.
|
|
16
|
+
|
|
17
|
+
- [#602](https://github.com/nansen-ai/nansen-cli/pull/602) [`9c72189`](https://github.com/nansen-ai/nansen-cli/commit/9c72189c6760c119784b3534a6777bd1a2e3ce11) Thanks [@kome12](https://github.com/kome12)! - trade limit-order cancel: give distinct, actionable errors when the refund can't be verified — a fully-filled order now says so plainly ("nothing left to refund") instead of sharing the same generic message as unparseable order metadata.
|
|
18
|
+
|
|
19
|
+
- [#598](https://github.com/nansen-ai/nansen-cli/pull/598) [`1450b66`](https://github.com/nansen-ai/nansen-cli/commit/1450b66ffab26d0d9fbe570c90de79916f405ffb) Thanks [@kome12](https://github.com/kome12)! - Close two dust-refund gaps in limit-order cancel verification: a native-SOL refund at or below the fee/rent slack could be "cancelled" by returning a single lamport while the rest of the escrow was rerouted, and a cancel now fails closed when the order is found but its remaining refund amount can't be computed instead of silently downgrading to a bare positive-inflow check.
|
|
20
|
+
|
|
21
|
+
- [#598](https://github.com/nansen-ai/nansen-cli/pull/598) [`b6d5baf`](https://github.com/nansen-ai/nansen-cli/commit/b6d5baf1b14ebd53287744eb23a1f9c4b7ac20a3) Thanks [@kome12](https://github.com/kome12)! - Limit-order create and cancel now verify the API-provided Solana transaction's simulated balance effect against the requested operation before signing, refusing to sign a deposit that would move unexpected funds out of the wallet or a cancel that fails to return the order's own deposited asset to it. The cancel check binds to the full expected remaining refund, not just a positive inflow, so a withdrawal that reroutes most of the escrow and returns only a dust amount of the right asset is refused. Also closes a gap where a cancel could pass on an inflow of any asset (not just the deposited one), and a tiny native-SOL deposit could pass on a fee-only outflow. The pre-cancel order lookup now paginates the active-order list, so an order beyond the first page can still be cancelled.
|
|
22
|
+
|
|
23
|
+
- [#582](https://github.com/nansen-ai/nansen-cli/pull/582) [`8e674c2`](https://github.com/nansen-ai/nansen-cli/commit/8e674c24c6c9340b2c658e511199ac546064fe9b) Thanks [@devorun](https://github.com/devorun)! - Telemetry now creates `~/.nansen` with mode 0700 and writes its id/session files with mode 0600, matching every other module that writes to that directory. Previously these were the only writes there that used default permissions, so when they were the first to create the directory (for example when authenticating with `NANSEN_API_KEY` instead of `nansen login`) it was left group- and world-readable.
|
|
24
|
+
|
|
25
|
+
- [#594](https://github.com/nansen-ai/nansen-cli/pull/594) [`95bdde1`](https://github.com/nansen-ai/nansen-cli/commit/95bdde151057b0bdc6b0bdc5efd67cc3420a9c44) Thanks [@Kewe63](https://github.com/Kewe63)! - Reject invalid cache TTL values before constructing the API client.
|
|
26
|
+
|
|
27
|
+
- [#593](https://github.com/nansen-ai/nansen-cli/pull/593) [`dfc908a`](https://github.com/nansen-ai/nansen-cli/commit/dfc908a74ebc9a6341629c43bea4d98df1219ccc) Thanks [@Kewe63](https://github.com/Kewe63)! - Reject invalid retry counts before constructing the API client.
|
|
28
|
+
|
|
29
|
+
- [#599](https://github.com/nansen-ai/nansen-cli/pull/599) [`bdbdcb2`](https://github.com/nansen-ai/nansen-cli/commit/bdbdcb222ae2f3a4f3b88c8832e7375c46559d79) Thanks [@kome12](https://github.com/kome12)! - x402 auto-pay now signs only for supported schemes and recognized payment networks (exact Solana mainnet CAIP-2 binding), and derives the EIP-712 chain id from the validated network. The EIP-712 domain version is now required across all signing backends (local, WalletConnect, Privy) so a missing version can no longer be silently defaulted to a wrong value, while a null/empty remote chain id is treated as unspecified rather than a conflict.
|
|
30
|
+
|
|
3
31
|
## 1.44.0
|
|
4
32
|
|
|
5
33
|
### Minor Changes
|
package/package.json
CHANGED
package/src/api.js
CHANGED
|
@@ -275,7 +275,22 @@ export function getCachedResponse(endpoint, body, ttlSeconds = DEFAULT_CACHE_TTL
|
|
|
275
275
|
return null;
|
|
276
276
|
}
|
|
277
277
|
|
|
278
|
-
|
|
278
|
+
// Re-attach the cache marker without reshaping the payload. Object-spreading
|
|
279
|
+
// a top-level array turns it into { 0: …, 1: … }, so a cached array came back
|
|
280
|
+
// as an object and every Array.isArray() branch downstream (the table/CSV/
|
|
281
|
+
// markdown formatters in cli.js, alertsGet) stopped recognising it — the first
|
|
282
|
+
// call rendered rows and the second rendered nothing. Arrays therefore get
|
|
283
|
+
// _meta hung off the array itself, exactly as the live request path does when
|
|
284
|
+
// it records retriedAttempts, and primitives are handed back untouched
|
|
285
|
+
// because a non-object cannot carry the marker at all.
|
|
286
|
+
const meta = { ...cached.data?._meta, fromCache: true, cacheAge: Math.round(age) };
|
|
287
|
+
if (Array.isArray(cached.data)) {
|
|
288
|
+
const rows = cached.data.slice();
|
|
289
|
+
rows._meta = meta;
|
|
290
|
+
return rows;
|
|
291
|
+
}
|
|
292
|
+
if (cached.data === null || typeof cached.data !== 'object') return cached.data;
|
|
293
|
+
return { ...cached.data, _meta: meta };
|
|
279
294
|
} catch (_e) {
|
|
280
295
|
// Invalid cache file, delete it
|
|
281
296
|
try { fs.unlinkSync(cacheFile); } catch { /* ignore */ }
|
|
@@ -1802,15 +1817,17 @@ export class NansenAPI {
|
|
|
1802
1817
|
}
|
|
1803
1818
|
|
|
1804
1819
|
async alertsCreate(params = {}) {
|
|
1805
|
-
|
|
1820
|
+
// Creating an alert is non-idempotent: a lost response after a committed
|
|
1821
|
+
// create must not trigger another request through the generic retry loop.
|
|
1822
|
+
return this.request('/api/v1/smart-alert', params, { cache: false, retry: false });
|
|
1806
1823
|
}
|
|
1807
1824
|
|
|
1808
1825
|
async alertsUpdate(params = {}) {
|
|
1809
|
-
return this.request('/api/v1/smart-alert', params, { method: 'PATCH' });
|
|
1826
|
+
return this.request('/api/v1/smart-alert', params, { method: 'PATCH', cache: false });
|
|
1810
1827
|
}
|
|
1811
1828
|
|
|
1812
1829
|
async alertsToggle(params = {}) {
|
|
1813
|
-
return this.request('/api/v1/smart-alert/toggle', params, { method: 'PATCH' });
|
|
1830
|
+
return this.request('/api/v1/smart-alert/toggle', params, { method: 'PATCH', cache: false });
|
|
1814
1831
|
}
|
|
1815
1832
|
|
|
1816
1833
|
async alertsGet(id) {
|
|
@@ -1822,7 +1839,7 @@ export class NansenAPI {
|
|
|
1822
1839
|
}
|
|
1823
1840
|
|
|
1824
1841
|
async alertsDelete(alertId) {
|
|
1825
|
-
return this.request(`/api/v1/smart-alert/${encodeURIComponent(alertId)}`, {}, { method: 'DELETE' });
|
|
1842
|
+
return this.request(`/api/v1/smart-alert/${encodeURIComponent(alertId)}`, {}, { method: 'DELETE', cache: false });
|
|
1826
1843
|
}
|
|
1827
1844
|
}
|
|
1828
1845
|
|
package/src/cli.js
CHANGED
|
@@ -220,6 +220,40 @@ export function parseArgs(args) {
|
|
|
220
220
|
return result;
|
|
221
221
|
}
|
|
222
222
|
|
|
223
|
+
function parseNonNegativeSafeIntegerOption(name, options, flags, defaultValue) {
|
|
224
|
+
if (flags[name]) {
|
|
225
|
+
throw new NansenError(
|
|
226
|
+
`--${name} requires a non-negative safe integer value`,
|
|
227
|
+
ErrorCode.INVALID_PARAMS,
|
|
228
|
+
);
|
|
229
|
+
}
|
|
230
|
+
if (options[name] === undefined) return defaultValue;
|
|
231
|
+
|
|
232
|
+
const rawValue = options[name];
|
|
233
|
+
if (Array.isArray(rawValue)) {
|
|
234
|
+
throw new NansenError(
|
|
235
|
+
`--${name} may only be specified once`,
|
|
236
|
+
ErrorCode.INVALID_PARAMS,
|
|
237
|
+
);
|
|
238
|
+
}
|
|
239
|
+
if (typeof rawValue === 'string' && rawValue.trim() === '') {
|
|
240
|
+
throw new NansenError(
|
|
241
|
+
`--${name} requires a non-negative safe integer value`,
|
|
242
|
+
ErrorCode.INVALID_PARAMS,
|
|
243
|
+
);
|
|
244
|
+
}
|
|
245
|
+
const value = typeof rawValue === 'string' || typeof rawValue === 'number'
|
|
246
|
+
? Number(rawValue)
|
|
247
|
+
: NaN;
|
|
248
|
+
if (!Number.isSafeInteger(value) || value < 0) {
|
|
249
|
+
throw new NansenError(
|
|
250
|
+
`--${name} must be a non-negative safe integer; received: ${String(rawValue)}`,
|
|
251
|
+
ErrorCode.INVALID_PARAMS,
|
|
252
|
+
);
|
|
253
|
+
}
|
|
254
|
+
return value;
|
|
255
|
+
}
|
|
256
|
+
|
|
223
257
|
// Format a single value for table display
|
|
224
258
|
export function formatValue(val) {
|
|
225
259
|
if (val === null || val === undefined) return '';
|
|
@@ -1180,7 +1214,7 @@ export function buildCommands(deps = {}) {
|
|
|
1180
1214
|
log('CACHE OPTIONS (for any command):');
|
|
1181
1215
|
log(' --cache Enable caching for this session');
|
|
1182
1216
|
log(' --no-cache Bypass cache for this request');
|
|
1183
|
-
log(' --cache-ttl <seconds> Set cache TTL (default: 300)');
|
|
1217
|
+
log(' --cache-ttl <seconds> Set non-negative safe integer cache TTL (default: 300)');
|
|
1184
1218
|
}
|
|
1185
1219
|
};
|
|
1186
1220
|
|
|
@@ -2039,15 +2073,16 @@ export async function runCLI(rawArgs, deps = {}) {
|
|
|
2039
2073
|
|
|
2040
2074
|
try {
|
|
2041
2075
|
// Configure retry options
|
|
2076
|
+
const maxRetries = parseNonNegativeSafeIntegerOption('retries', options, flags, 3);
|
|
2042
2077
|
const retryOptions = flags['no-retry']
|
|
2043
2078
|
? { maxRetries: 0 }
|
|
2044
|
-
: { maxRetries
|
|
2079
|
+
: { maxRetries };
|
|
2045
2080
|
|
|
2046
2081
|
// Configure cache options
|
|
2047
|
-
const cacheTtl =
|
|
2082
|
+
const cacheTtl = parseNonNegativeSafeIntegerOption('cache-ttl', options, flags, 300);
|
|
2048
2083
|
const cacheOptions = {
|
|
2049
2084
|
enabled: flags['cache'] && !flags['no-cache'],
|
|
2050
|
-
ttl:
|
|
2085
|
+
ttl: cacheTtl
|
|
2051
2086
|
};
|
|
2052
2087
|
|
|
2053
2088
|
const defaultHeaders = {};
|
package/src/commands/alerts.js
CHANGED
|
@@ -107,15 +107,32 @@ function parseChains(chainsOpt) {
|
|
|
107
107
|
return chainsOpt.split(',').map(s => s.trim()).filter(Boolean);
|
|
108
108
|
}
|
|
109
109
|
|
|
110
|
+
/**
|
|
111
|
+
* Parse a CLI option value as a finite number, or throw a clear error.
|
|
112
|
+
*
|
|
113
|
+
* Plain `Number(val)` turns garbage input ("abc") into NaN, and
|
|
114
|
+
* `JSON.stringify` silently turns NaN into `null` — so a typo'd
|
|
115
|
+
* --usd-min/--market-cap-max/etc. would vanish from the request instead of
|
|
116
|
+
* failing loudly, and the alert would ship without the filter the user
|
|
117
|
+
* asked for.
|
|
118
|
+
*/
|
|
119
|
+
function parseFiniteNumber(raw, name) {
|
|
120
|
+
const n = Number(raw);
|
|
121
|
+
if (!Number.isFinite(n)) {
|
|
122
|
+
throw new NansenError(`Invalid --${name} "${raw}": must be a number`, ErrorCode.INVALID_PARAMS);
|
|
123
|
+
}
|
|
124
|
+
return n;
|
|
125
|
+
}
|
|
126
|
+
|
|
110
127
|
/**
|
|
111
128
|
* Build a { min, max } range object from two option values.
|
|
112
129
|
* Returns undefined if neither is provided.
|
|
113
130
|
*/
|
|
114
|
-
function buildRange(minVal, maxVal) {
|
|
131
|
+
function buildRange(minVal, maxVal, name) {
|
|
115
132
|
if (minVal === undefined && maxVal === undefined) return undefined;
|
|
116
133
|
const r = {};
|
|
117
|
-
if (minVal !== undefined) r.min =
|
|
118
|
-
if (maxVal !== undefined) r.max =
|
|
134
|
+
if (minVal !== undefined) r.min = parseFiniteNumber(minVal, `${name}-min`);
|
|
135
|
+
if (maxVal !== undefined) r.max = parseFiniteNumber(maxVal, `${name}-max`);
|
|
119
136
|
return r;
|
|
120
137
|
}
|
|
121
138
|
|
|
@@ -138,7 +155,7 @@ export function buildSmTokenFlowsData(options) {
|
|
|
138
155
|
|
|
139
156
|
const flowFields = ['inflow-1h', 'inflow-1d', 'inflow-7d', 'outflow-1h', 'outflow-1d', 'outflow-7d', 'netflow-1h', 'netflow-1d', 'netflow-7d'];
|
|
140
157
|
for (const field of flowFields) {
|
|
141
|
-
const range = buildRange(options[`${field}-min`], options[`${field}-max`]);
|
|
158
|
+
const range = buildRange(options[`${field}-min`], options[`${field}-max`], field);
|
|
142
159
|
if (range) {
|
|
143
160
|
// Convert CLI key "inflow-1h" → data key "inflow_1h"
|
|
144
161
|
data[field.replace(/-/g, '_')] = range;
|
|
@@ -156,13 +173,13 @@ export function buildSmTokenFlowsData(options) {
|
|
|
156
173
|
if (excludeSectors) data.exclusion = { ...data.exclusion, tokenSectors: excludeSectors };
|
|
157
174
|
|
|
158
175
|
if (options['token-age-max'] !== undefined) {
|
|
159
|
-
data.inclusion = { ...data.inclusion, tokenAge: { max:
|
|
176
|
+
data.inclusion = { ...data.inclusion, tokenAge: { max: parseFiniteNumber(options['token-age-max'], 'token-age-max') } };
|
|
160
177
|
}
|
|
161
178
|
|
|
162
|
-
const marketCapRange = buildRange(options['market-cap-min'], options['market-cap-max']);
|
|
179
|
+
const marketCapRange = buildRange(options['market-cap-min'], options['market-cap-max'], 'market-cap');
|
|
163
180
|
if (marketCapRange) data.inclusion = { ...data.inclusion, marketCap: marketCapRange };
|
|
164
181
|
|
|
165
|
-
const fdvRange = buildRange(options['fdv-min'], options['fdv-max']);
|
|
182
|
+
const fdvRange = buildRange(options['fdv-min'], options['fdv-max'], 'fdv');
|
|
166
183
|
if (fdvRange) data.inclusion = { ...data.inclusion, fdvUsd: fdvRange };
|
|
167
184
|
|
|
168
185
|
return data;
|
|
@@ -181,10 +198,10 @@ export function buildCommonTokenTransferData(options) {
|
|
|
181
198
|
data.events = typeof options.events === 'string' ? options.events.split(',') : options.events;
|
|
182
199
|
}
|
|
183
200
|
|
|
184
|
-
const usdRange = buildRange(options['usd-min'], options['usd-max']);
|
|
201
|
+
const usdRange = buildRange(options['usd-min'], options['usd-max'], 'usd');
|
|
185
202
|
if (usdRange) data.usdValue = usdRange;
|
|
186
203
|
|
|
187
|
-
const amountRange = buildRange(options['token-amount-min'], options['token-amount-max']);
|
|
204
|
+
const amountRange = buildRange(options['token-amount-min'], options['token-amount-max'], 'token-amount');
|
|
188
205
|
if (amountRange) data.tokenAmount = amountRange;
|
|
189
206
|
|
|
190
207
|
const subjects = parseSubjects(options.subject);
|
|
@@ -207,12 +224,12 @@ export function buildCommonTokenTransferData(options) {
|
|
|
207
224
|
const tokenAgeMax = options['token-age-max'];
|
|
208
225
|
if (tokenAgeMin !== undefined || tokenAgeMax !== undefined) {
|
|
209
226
|
const tokenAge = {};
|
|
210
|
-
if (tokenAgeMin !== undefined) tokenAge.min =
|
|
211
|
-
if (tokenAgeMax !== undefined) tokenAge.max =
|
|
227
|
+
if (tokenAgeMin !== undefined) tokenAge.min = parseFiniteNumber(tokenAgeMin, 'token-age-min');
|
|
228
|
+
if (tokenAgeMax !== undefined) tokenAge.max = parseFiniteNumber(tokenAgeMax, 'token-age-max');
|
|
212
229
|
data.inclusion = { ...data.inclusion, tokenAge };
|
|
213
230
|
}
|
|
214
231
|
|
|
215
|
-
const marketCapRange = buildRange(options['market-cap-min'], options['market-cap-max']);
|
|
232
|
+
const marketCapRange = buildRange(options['market-cap-min'], options['market-cap-max'], 'market-cap');
|
|
216
233
|
if (marketCapRange) data.inclusion = { ...data.inclusion, marketCap: marketCapRange };
|
|
217
234
|
|
|
218
235
|
const excludeFrom = parseSubjects(options['exclude-from']);
|
|
@@ -232,7 +249,7 @@ export function buildSmartContractCallData(options) {
|
|
|
232
249
|
const chains = parseChains(options.chains);
|
|
233
250
|
if (chains) data.chains = chains;
|
|
234
251
|
|
|
235
|
-
const usdRange = buildRange(options['usd-min'], options['usd-max']);
|
|
252
|
+
const usdRange = buildRange(options['usd-min'], options['usd-max'], 'usd');
|
|
236
253
|
if (usdRange) data.usdValue = usdRange;
|
|
237
254
|
|
|
238
255
|
if (options['signature-hash']) {
|
|
@@ -606,9 +623,32 @@ USAGE:
|
|
|
606
623
|
});
|
|
607
624
|
}
|
|
608
625
|
|
|
609
|
-
// Pagination (applied after filtering)
|
|
610
|
-
|
|
611
|
-
if (options.
|
|
626
|
+
// Pagination (applied after filtering). Validate strictly rather than
|
|
627
|
+
// silently misbehaving on bad input:
|
|
628
|
+
// - `if (options.offset)` / `if (options.limit)` treat 0 as "not set"
|
|
629
|
+
// (falsy), so `--offset 0` / `--limit 0` were silently ignored
|
|
630
|
+
// instead of being honored.
|
|
631
|
+
// - `Number("abc")` is NaN, and `Array.prototype.slice` coerces a NaN
|
|
632
|
+
// argument to 0 — so `--offset abc` silently became a no-op and
|
|
633
|
+
// `--limit abc` silently returned zero results, with no error
|
|
634
|
+
// telling the caller their input wasn't a number at all.
|
|
635
|
+
// - Negative values (`--offset -1`) were accepted and fed straight
|
|
636
|
+
// into `slice()`, which treats negative indices as "from the end" —
|
|
637
|
+
// silently returning the wrong slice instead of rejecting the input.
|
|
638
|
+
if (options.offset !== undefined) {
|
|
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
|
+
}
|
|
643
|
+
alerts = alerts.slice(offset);
|
|
644
|
+
}
|
|
645
|
+
if (options.limit !== undefined) {
|
|
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
|
+
}
|
|
650
|
+
alerts = alerts.slice(0, limit);
|
|
651
|
+
}
|
|
612
652
|
|
|
613
653
|
return alerts;
|
|
614
654
|
},
|
package/src/limit-order.js
CHANGED
|
@@ -11,7 +11,17 @@ import path from 'path';
|
|
|
11
11
|
import { base58Encode, exportWallet, getWalletConfig, showWallet } from './wallet.js';
|
|
12
12
|
import { signEd25519, base58Decode, parseAmount, getTokenInfo } from './transfer.js';
|
|
13
13
|
import { signSolanaTransaction, resolveTokenAddress } from './trading.js';
|
|
14
|
-
import {
|
|
14
|
+
import {
|
|
15
|
+
assertSolanaInstructionsSafe,
|
|
16
|
+
assertLimitOrderDepositOutcome,
|
|
17
|
+
assertLimitOrderCancelOutcome,
|
|
18
|
+
NATIVE_FEE_RENT_SLACK_LAMPORTS,
|
|
19
|
+
} from './trade-validation.js';
|
|
20
|
+
import {
|
|
21
|
+
simulateSolanaAssetChanges,
|
|
22
|
+
SolanaSimulationError,
|
|
23
|
+
hasSolanaSimulationRpc,
|
|
24
|
+
} from './solana-simulation.js';
|
|
15
25
|
import { validateTokenAddress, telemetryHeaders, packageVersion } from './api.js';
|
|
16
26
|
import { getWalletConnectAddress, sendSolanaTransactionViaWalletConnect, signSolanaMessageViaWalletConnect } from './walletconnect-trading.js';
|
|
17
27
|
import { retrievePassword } from './keychain.js';
|
|
@@ -22,6 +32,7 @@ import { CHAIN_RPCS } from './rpc-urls.js';
|
|
|
22
32
|
const TRADING_API_URL = process.env.NANSEN_TRADING_API_URL || 'https://trading-api.nansen.ai';
|
|
23
33
|
const LO_PREFIX = '/limit-order/v2';
|
|
24
34
|
const SOLSCAN_TX_URL = 'https://solscan.io/tx/';
|
|
35
|
+
const WSOL_MINT = 'So11111111111111111111111111111111111111112';
|
|
25
36
|
|
|
26
37
|
// ============= JWT Auth & Caching (Local File) =============
|
|
27
38
|
|
|
@@ -383,6 +394,88 @@ export async function signTransaction(txBase64, walletType, walletInfo) {
|
|
|
383
394
|
throw new Error(`Unsupported wallet type: ${walletType}`);
|
|
384
395
|
}
|
|
385
396
|
|
|
397
|
+
/**
|
|
398
|
+
* The limit-order sibling of verifySolanaSwapOutcome: simulates the deposit/
|
|
399
|
+
* cancel transaction and checks the resulting balance deltas against the
|
|
400
|
+
* requested operation, degrading (warn + proceed) on any RPC/sim outage so an
|
|
401
|
+
* outage never blocks an order — only a real outcome mismatch or an
|
|
402
|
+
* in-simulation revert refuses to sign.
|
|
403
|
+
*/
|
|
404
|
+
async function verifyLimitOrderOutcome({ kind, walletAddress, txBase64, inputMint, amount, log = () => {} }) {
|
|
405
|
+
if (!hasSolanaSimulationRpc('solana')) {
|
|
406
|
+
log(' ⚠ Outcome verification unavailable (no Solana simulation endpoint); proceeding without it.');
|
|
407
|
+
return { proceed: true };
|
|
408
|
+
}
|
|
409
|
+
try {
|
|
410
|
+
const sim = await simulateSolanaAssetChanges('solana', txBase64, { walletAddress });
|
|
411
|
+
if (kind === 'deposit') {
|
|
412
|
+
assertLimitOrderDepositOutcome(sim, { inputMint, amount });
|
|
413
|
+
} else {
|
|
414
|
+
assertLimitOrderCancelOutcome(sim, { inputMint, amount });
|
|
415
|
+
}
|
|
416
|
+
log(` ✓ ${kind === 'deposit' ? 'Deposit' : 'Cancellation'} outcome verified (via ${sim.method}).`);
|
|
417
|
+
return { proceed: true };
|
|
418
|
+
} catch (e) {
|
|
419
|
+
if (e instanceof SolanaSimulationError && ['NO_SIM_RPC', 'SIM_RPC_ERROR'].includes(e.code)) {
|
|
420
|
+
log(` ⚠ Outcome verification could not run (${e.message}); proceeding without it.`);
|
|
421
|
+
return { proceed: true };
|
|
422
|
+
}
|
|
423
|
+
return { proceed: false, reason: e.message };
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
// Page size and scan ceiling for the pre-cancel order lookup. The ceiling is a
|
|
428
|
+
// defensive bound: it stops an unbounded loop if the API never surfaces the order
|
|
429
|
+
// and never reports a total or a short page, at the cost of not finding a target
|
|
430
|
+
// buried beyond it (which then fails closed, same as any not-found order).
|
|
431
|
+
const ACTIVE_ORDER_PAGE = 100;
|
|
432
|
+
const MAX_ACTIVE_ORDERS_SCANNED = 5000;
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* Find one active order by id, paginating state:'active' until the order is found or
|
|
436
|
+
* the active set is exhausted, so a user with more than one page of active orders can
|
|
437
|
+
* still cancel one that doesn't land on page 1. Returns the order object or undefined.
|
|
438
|
+
*/
|
|
439
|
+
async function findActiveOrder(token, userPubkey, orderId) {
|
|
440
|
+
let offset = 0;
|
|
441
|
+
while (offset < MAX_ACTIVE_ORDERS_SCANNED) {
|
|
442
|
+
const page = await listOrders(token, userPubkey, { limit: ACTIVE_ORDER_PAGE, offset, state: 'active' });
|
|
443
|
+
const orders = page.orders || [];
|
|
444
|
+
const found = orders.find((o) => o.id === orderId);
|
|
445
|
+
if (found) return found;
|
|
446
|
+
offset += orders.length;
|
|
447
|
+
if (orders.length < ACTIVE_ORDER_PAGE) break; // short/empty page — no more to fetch
|
|
448
|
+
const total = page.pagination?.total;
|
|
449
|
+
if (total != null && offset >= total) break; // consumed everything the API reports
|
|
450
|
+
}
|
|
451
|
+
return undefined;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/**
|
|
455
|
+
* Classify how much a cancel should refund: the order's input less whatever has
|
|
456
|
+
* already been filled (partial fills consume escrow). Returns one of:
|
|
457
|
+
* { amount: <bigint> } the unfilled remainder still owed (always > 0)
|
|
458
|
+
* { error: 'unparseable' } the order's amounts couldn't be parsed as integers
|
|
459
|
+
* { error: 'fully-filled' } parsing succeeded but nothing is left to refund
|
|
460
|
+
*
|
|
461
|
+
* The two error cases are kept distinct (not collapsed to a single undefined) so the
|
|
462
|
+
* cancel command can surface an actionable message: 'unparseable' is an unexpected
|
|
463
|
+
* API-shape problem, 'fully-filled' is a normal user-facing state (the order already
|
|
464
|
+
* executed). Both are fatal for the caller — a cancel whose refund magnitude can't be
|
|
465
|
+
* bound must not be signed — but the user needs to know which one they hit.
|
|
466
|
+
*/
|
|
467
|
+
function classifyCancelRefund(order) {
|
|
468
|
+
let remaining;
|
|
469
|
+
try {
|
|
470
|
+
const total = BigInt(order.inputAmount);
|
|
471
|
+
const filled = (order.fills || []).reduce((sum, f) => sum + BigInt(f.inputAmount ?? 0), 0n);
|
|
472
|
+
remaining = total - filled;
|
|
473
|
+
} catch {
|
|
474
|
+
return { error: 'unparseable' };
|
|
475
|
+
}
|
|
476
|
+
return remaining > 0n ? { amount: remaining } : { error: 'fully-filled' };
|
|
477
|
+
}
|
|
478
|
+
|
|
386
479
|
// ============= Expiry Parsing =============
|
|
387
480
|
|
|
388
481
|
/**
|
|
@@ -621,6 +714,22 @@ EXAMPLES:
|
|
|
621
714
|
return;
|
|
622
715
|
}
|
|
623
716
|
|
|
717
|
+
// Fail fast on a native-SOL amount too small for outcome verification to bound by
|
|
718
|
+
// magnitude (see assertLimitOrderDepositOutcome's NATIVE_FEE_RENT_SLACK_LAMPORTS
|
|
719
|
+
// floor) — otherwise this would only surface as a LIMIT_ORDER_OUTCOME_MISMATCH
|
|
720
|
+
// after crafting and simulating the deposit transaction, well into the flow.
|
|
721
|
+
// Gated on hasSolanaSimulationRpc deliberately: the floor is a pre-empt of the
|
|
722
|
+
// magnitude check, so it only applies when that check would actually run. In a
|
|
723
|
+
// degraded (no-sim-RPC) environment there is no magnitude bound to pre-empt — the
|
|
724
|
+
// deposit falls back to the static gate alone (verifyLimitOrderOutcome already warns
|
|
725
|
+
// that outcome verification is unavailable), so blocking a small amount here would
|
|
726
|
+
// add a floor that the rest of that path doesn't enforce.
|
|
727
|
+
if (from === WSOL_MINT && hasSolanaSimulationRpc('solana') && BigInt(amountBaseUnits) <= NATIVE_FEE_RENT_SLACK_LAMPORTS) {
|
|
728
|
+
log(`Error: SOL deposit amount (${amountBaseUnits} lamports) is too small to verify against network fee/rent noise (${NATIVE_FEE_RENT_SLACK_LAMPORTS} lamports). Use a larger amount.`);
|
|
729
|
+
exit(1);
|
|
730
|
+
return;
|
|
731
|
+
}
|
|
732
|
+
|
|
624
733
|
if (triggerCondition !== 'above' && triggerCondition !== 'below') {
|
|
625
734
|
log('Error: --trigger-condition must be "above" or "below".');
|
|
626
735
|
exit(1);
|
|
@@ -699,17 +808,26 @@ EXAMPLES:
|
|
|
699
808
|
});
|
|
700
809
|
|
|
701
810
|
// 5. Sign deposit transaction
|
|
702
|
-
//
|
|
703
|
-
// moves the input token into the
|
|
704
|
-
//
|
|
705
|
-
// when selling native SOL, a
|
|
706
|
-
// the wallet (permitted).
|
|
707
|
-
// close-to-stranger checks, so this
|
|
708
|
-
// it only fires if the crafted tx
|
|
709
|
-
// authority, or closes to a
|
|
710
|
-
//
|
|
711
|
-
//
|
|
811
|
+
// Two layers of pre-signing defense, same as the swap path. First, the
|
|
812
|
+
// static gate: the legitimate deposit moves the input token into the
|
|
813
|
+
// already-registered vault (step 3) with an SPL Transfer/TransferChecked —
|
|
814
|
+
// which this gate does not classify — plus, when selling native SOL, a
|
|
815
|
+
// temp-WSOL CloseAccount whose rent returns to the wallet (permitted).
|
|
816
|
+
// Neither trips the delegate/authority/close-to-stranger checks, so this
|
|
817
|
+
// does not reject a well-formed deposit; it only fires if the crafted tx
|
|
818
|
+
// additionally grants a delegate, reassigns authority, or closes to a
|
|
819
|
+
// stranger. Second, balance-delta outcome verification below binds the
|
|
820
|
+
// deposit's magnitude: the input token must leave the wallet by exactly
|
|
821
|
+
// `amount` (± fee/rent slack for native SOL) and no other token may leave.
|
|
822
|
+
// Verified live: a real SOL→USDC create round-trip clears both gates (the
|
|
823
|
+
// API-crafted deposit is a SOL-wrap transfer into the vault plus a
|
|
824
|
+
// temp-WSOL close-to-self).
|
|
712
825
|
assertSolanaInstructionsSafe(deposit.transaction, { walletAddress: pubkey });
|
|
826
|
+
const depositOutcome = await verifyLimitOrderOutcome({
|
|
827
|
+
kind: 'deposit', walletAddress: pubkey, txBase64: deposit.transaction,
|
|
828
|
+
inputMint: from, amount: amountBaseUnits, log,
|
|
829
|
+
});
|
|
830
|
+
if (!depositOutcome.proceed) throw new Error(`Refusing to sign deposit — ${depositOutcome.reason}`);
|
|
713
831
|
log(' Signing deposit transaction...');
|
|
714
832
|
const signedDepositTx = await signTransaction(deposit.transaction, walletType, walletInfo);
|
|
715
833
|
|
|
@@ -839,23 +957,83 @@ EXAMPLES:
|
|
|
839
957
|
// 1. Authenticate
|
|
840
958
|
const token = await authenticate(pubkey, walletType, walletInfo, log);
|
|
841
959
|
|
|
842
|
-
// 2.
|
|
960
|
+
// 2. Look up the order, but only when outcome verification will actually run —
|
|
961
|
+
// cancel only receives an orderId, not order details, from the caller, and the
|
|
962
|
+
// refund check below (see assertLimitOrderCancelOutcome) needs to know both which
|
|
963
|
+
// asset the refund must land in AND how much of it is still owed (the unfilled
|
|
964
|
+
// remainder). Skip the extra lookup entirely when there's no simulation RPC to
|
|
965
|
+
// verify against, so a degraded environment doesn't gain a new API dependency for
|
|
966
|
+
// a check it isn't going to run anyway. Done before requesting cancellation so a
|
|
967
|
+
// lookup failure fails closed without first consuming a one-time withdrawal request
|
|
968
|
+
// server-side. Filtered to state: 'active' (the only state a cancellable order can
|
|
969
|
+
// be in) so filled/cancelled/expired history never crowds out the target — the API
|
|
970
|
+
// only accepts 'active' or 'past' for this filter. Paginated until the order is
|
|
971
|
+
// found or the active set is exhausted, so a user with more than one page of active
|
|
972
|
+
// orders can still cancel one that doesn't land on page 1.
|
|
973
|
+
let cancelInputMint;
|
|
974
|
+
let cancelRefundAmount;
|
|
975
|
+
if (hasSolanaSimulationRpc('solana')) {
|
|
976
|
+
const order = await findActiveOrder(token, pubkey, orderId);
|
|
977
|
+
if (!order) {
|
|
978
|
+
throw new Error(`Could not find order ${orderId} among your active orders; refusing to verify the cancel's refund asset. It may already be filled/cancelled/expired — check with "nansen trade limit-order list --state active".`);
|
|
979
|
+
}
|
|
980
|
+
cancelInputMint = order.inputMint;
|
|
981
|
+
// The whole point of the outcome check is to bind the refund's MAGNITUDE. If the
|
|
982
|
+
// remaining refund can't be pinned to an exact amount, passing amount: undefined
|
|
983
|
+
// would silently downgrade the verifier to a bare positive-inflow check —
|
|
984
|
+
// reopening the dust-refund gap for exactly the metadata we can least trust. Fail
|
|
985
|
+
// closed instead, with a message that distinguishes the two reasons: unparseable
|
|
986
|
+
// amounts are an unexpected API-shape problem, a fully-filled order is a normal
|
|
987
|
+
// state the user should just be told about plainly.
|
|
988
|
+
const refund = classifyCancelRefund(order);
|
|
989
|
+
if (refund.error === 'unparseable') {
|
|
990
|
+
throw new Error(`Found order ${orderId} but its input/fill amounts couldn't be parsed from the order metadata; refusing to sign a cancel whose refund magnitude can't be verified. Check the order with "nansen trade limit-order list --state active".`);
|
|
991
|
+
}
|
|
992
|
+
if (refund.error === 'fully-filled') {
|
|
993
|
+
throw new Error(`Order ${orderId} appears fully filled — there is nothing left to refund, so it can't be cancelled. Check its status with "nansen trade limit-order list --state active".`);
|
|
994
|
+
}
|
|
995
|
+
cancelRefundAmount = refund.amount;
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
// 3. Request cancellation — get unsigned withdrawal tx
|
|
999
|
+
//
|
|
1000
|
+
// NOTE (deliberate, do not "fix" by loosening the check): there is a narrow TOCTOU
|
|
1001
|
+
// window between the lookup in step 2 (which pins cancelRefundAmount to the unfilled
|
|
1002
|
+
// remainder seen then) and this cancellation request. If a partial fill lands in
|
|
1003
|
+
// between, the real withdrawal returns LESS than cancelRefundAmount and the outcome
|
|
1004
|
+
// check in step 4 fails closed on a legitimate cancel. That's acceptable: the user
|
|
1005
|
+
// simply retries and the next lookup sees the new remainder. The safe response to a
|
|
1006
|
+
// spurious failure here is a retry, NOT relaxing the exact-magnitude bind — that bind
|
|
1007
|
+
// is what closes the dust-refund redirect (a crafted withdrawal that reroutes most of
|
|
1008
|
+
// the escrow and returns only a token of the right mint), so widening it reopens the
|
|
1009
|
+
// exact gap this verification exists to close.
|
|
843
1010
|
log(' Requesting cancellation...');
|
|
844
1011
|
const cancelResult = await cancelOrderRequest(token, orderId);
|
|
845
1012
|
|
|
846
|
-
//
|
|
1013
|
+
// 4. Sign the withdrawal transaction
|
|
847
1014
|
// Withdrawal moves the deposited token back out of the vault; that transfer
|
|
848
1015
|
// is authorized by the vault program's PDA, not our wallet, so it isn't a
|
|
849
1016
|
// wallet-authorized drain even if it were classified. Any temp-WSOL close
|
|
850
|
-
// returns rent to the wallet.
|
|
851
|
-
// crafted withdrawal that instead grants a delegate, reassigns
|
|
852
|
-
// closes to a stranger.
|
|
853
|
-
// cancel
|
|
1017
|
+
// returns rent to the wallet. The static gate below is defense-in-depth
|
|
1018
|
+
// against a crafted withdrawal that instead grants a delegate, reassigns
|
|
1019
|
+
// authority, or closes to a stranger. Balance-delta outcome verification
|
|
1020
|
+
// then binds the withdrawal's effect: since a cancel should only return
|
|
1021
|
+
// funds to the wallet, no token may leave it at all (native-SOL fee/rent
|
|
1022
|
+
// dust tolerated), and the order's own input asset must return by the full
|
|
1023
|
+
// expected remaining amount (looked up in step 2) — not merely a positive
|
|
1024
|
+
// delta, so a redirect of most of the escrow paired with a dust or unrelated
|
|
1025
|
+
// inflow no longer counts. Verified live alongside the deposit path via a
|
|
1026
|
+
// real cancel round-trip.
|
|
854
1027
|
assertSolanaInstructionsSafe(cancelResult.transaction, { walletAddress: pubkey });
|
|
1028
|
+
const cancelOutcome = await verifyLimitOrderOutcome({
|
|
1029
|
+
kind: 'cancel', walletAddress: pubkey, txBase64: cancelResult.transaction,
|
|
1030
|
+
inputMint: cancelInputMint, amount: cancelRefundAmount, log,
|
|
1031
|
+
});
|
|
1032
|
+
if (!cancelOutcome.proceed) throw new Error(`Refusing to sign withdrawal — ${cancelOutcome.reason}`);
|
|
855
1033
|
log(' Signing withdrawal transaction...');
|
|
856
1034
|
const signedTx = await signTransaction(cancelResult.transaction, walletType, walletInfo);
|
|
857
1035
|
|
|
858
|
-
//
|
|
1036
|
+
// 5. Confirm cancellation
|
|
859
1037
|
log(' Confirming cancellation...');
|
|
860
1038
|
const confirmed = await confirmCancelOrder(token, orderId, {
|
|
861
1039
|
signedTransaction: signedTx,
|
package/src/schema.json
CHANGED
|
@@ -2545,9 +2545,18 @@
|
|
|
2545
2545
|
"description": "Disable automatic retry on rate limits/errors"
|
|
2546
2546
|
},
|
|
2547
2547
|
"retries": {
|
|
2548
|
-
"type": "
|
|
2548
|
+
"type": "integer",
|
|
2549
|
+
"minimum": 0,
|
|
2550
|
+
"maximum": 9007199254740991,
|
|
2549
2551
|
"default": 3,
|
|
2550
|
-
"description": "Max retry attempts"
|
|
2552
|
+
"description": "Max retry attempts (non-negative safe integer)"
|
|
2553
|
+
},
|
|
2554
|
+
"cache-ttl": {
|
|
2555
|
+
"type": "integer",
|
|
2556
|
+
"minimum": 0,
|
|
2557
|
+
"maximum": 9007199254740991,
|
|
2558
|
+
"default": 300,
|
|
2559
|
+
"description": "Cache TTL in seconds (non-negative safe integer; 0 disables cache reads)"
|
|
2551
2560
|
},
|
|
2552
2561
|
"format": {
|
|
2553
2562
|
"type": "string",
|
package/src/telemetry.js
CHANGED
|
@@ -31,6 +31,16 @@ const TELEMETRY_URL =
|
|
|
31
31
|
|
|
32
32
|
const TIMEOUT_MS = 1000;
|
|
33
33
|
|
|
34
|
+
// Every other module that writes under ~/.nansen (api.js, wallet.js, keychain.js,
|
|
35
|
+
// trading.js, update-check.js, …) creates directories 0700 and files 0600, because
|
|
36
|
+
// the same directory also holds the API key and the encrypted wallet keystores.
|
|
37
|
+
// Telemetry writes there too, so it uses the same modes: mkdir with recursive:true
|
|
38
|
+
// leaves an existing directory's mode alone, so whichever module creates ~/.nansen
|
|
39
|
+
// first fixes its permissions for good — and on the documented NANSEN_API_KEY path
|
|
40
|
+
// no config is ever saved, so that first writer is this file.
|
|
41
|
+
const DIR_MODE = 0o700;
|
|
42
|
+
const FILE_MODE = 0o600;
|
|
43
|
+
|
|
34
44
|
// ─── opt-out ──────────────────────────────────────────────
|
|
35
45
|
|
|
36
46
|
/**
|
|
@@ -83,8 +93,8 @@ export function getAnonymousId() {
|
|
|
83
93
|
if (!_anonymousId) {
|
|
84
94
|
_anonymousId = crypto.randomUUID();
|
|
85
95
|
try {
|
|
86
|
-
fs.mkdirSync(path.dirname(TELEMETRY_ID_FILE), { recursive: true });
|
|
87
|
-
fs.writeFileSync(TELEMETRY_ID_FILE, _anonymousId, 'utf8');
|
|
96
|
+
fs.mkdirSync(path.dirname(TELEMETRY_ID_FILE), { mode: DIR_MODE, recursive: true });
|
|
97
|
+
fs.writeFileSync(TELEMETRY_ID_FILE, _anonymousId, { encoding: 'utf8', mode: FILE_MODE });
|
|
88
98
|
} catch { /* best-effort persist */ }
|
|
89
99
|
}
|
|
90
100
|
}
|
|
@@ -121,7 +131,7 @@ export function getSessionId() {
|
|
|
121
131
|
_sessionId = raw.id;
|
|
122
132
|
// touch timestamp, but only if >1 min elapsed to reduce writes
|
|
123
133
|
if (now - raw.ts > 60_000) {
|
|
124
|
-
try { fs.writeFileSync(SESSION_FILE, JSON.stringify({ id: _sessionId, ts: now }), 'utf8'); } catch { /* best-effort touch */ }
|
|
134
|
+
try { fs.writeFileSync(SESSION_FILE, JSON.stringify({ id: _sessionId, ts: now }), { encoding: 'utf8', mode: FILE_MODE }); } catch { /* best-effort touch */ }
|
|
125
135
|
}
|
|
126
136
|
return _sessionId;
|
|
127
137
|
}
|
|
@@ -129,8 +139,8 @@ export function getSessionId() {
|
|
|
129
139
|
|
|
130
140
|
_sessionId = crypto.randomUUID();
|
|
131
141
|
try {
|
|
132
|
-
fs.mkdirSync(path.dirname(SESSION_FILE), { recursive: true });
|
|
133
|
-
fs.writeFileSync(SESSION_FILE, JSON.stringify({ id: _sessionId, ts: now }), 'utf8');
|
|
142
|
+
fs.mkdirSync(path.dirname(SESSION_FILE), { mode: DIR_MODE, recursive: true });
|
|
143
|
+
fs.writeFileSync(SESSION_FILE, JSON.stringify({ id: _sessionId, ts: now }), { encoding: 'utf8', mode: FILE_MODE });
|
|
134
144
|
} catch { /* best-effort */ }
|
|
135
145
|
return _sessionId;
|
|
136
146
|
}
|
package/src/trade-validation.js
CHANGED
|
@@ -1225,7 +1225,7 @@ const NATIVE_SIBLING_DUST_LAMPORTS = 3_000_000n; // ~0.003 SOL
|
|
|
1225
1225
|
// leaves the wallet as native SOL regardless of whether SOL is the input,
|
|
1226
1226
|
// output, or an uninvolved sibling of the swap, so all three assertions below
|
|
1227
1227
|
// need the same combined slack or a legitimate high-priority-fee trade false-blocks.
|
|
1228
|
-
const NATIVE_FEE_RENT_SLACK_LAMPORTS = MAX_PRIORITY_FEE_LAMPORTS + NATIVE_SIBLING_DUST_LAMPORTS;
|
|
1228
|
+
export const NATIVE_FEE_RENT_SLACK_LAMPORTS = MAX_PRIORITY_FEE_LAMPORTS + NATIVE_SIBLING_DUST_LAMPORTS;
|
|
1229
1229
|
|
|
1230
1230
|
/**
|
|
1231
1231
|
* The Solana sibling of assertSwapOutcome. Solana signs the aggregator's
|
|
@@ -1477,6 +1477,217 @@ export function assertSolanaSwapOutcome(request, quote, sim, { slippage, sibling
|
|
|
1477
1477
|
return { verified: true, inputAssertionSkipped: inputIsNative, outputAssertionSkipped: isBridge };
|
|
1478
1478
|
}
|
|
1479
1479
|
|
|
1480
|
+
/**
|
|
1481
|
+
* Verify a limit-order DEPOSIT's simulated wallet effect against intent.
|
|
1482
|
+
* Fails closed (code LIMIT_ORDER_OUTCOME_MISMATCH) unless:
|
|
1483
|
+
* 1. the input token leaves the wallet by EXACTLY `amount` for an SPL input, or
|
|
1484
|
+
* within `amount` ± NATIVE_FEE_RENT_SLACK_LAMPORTS for a native-SOL input
|
|
1485
|
+
* (two-sided: upper bound caps the drain, lower bound rejects a partial reroute), and
|
|
1486
|
+
* 2. no token OTHER than the input leaves the wallet (native-SOL dust tolerated).
|
|
1487
|
+
* NOTE: this bounds MAGNITUDE, not destination — a full-`amount` transfer to a non-vault
|
|
1488
|
+
* address still passes; that is closed by the vault-destination binding (fast-follow).
|
|
1489
|
+
* There is no output leg — the deposit funds the vault, nothing returns to the wallet.
|
|
1490
|
+
*
|
|
1491
|
+
* @param {{deltas: Record<string, bigint|string|number>}} sim - simulateSolanaAssetChanges result
|
|
1492
|
+
* @param {{inputMint: string, amount: bigint|string|number}} ctx
|
|
1493
|
+
* (walletAddress is NOT needed here — the sim already keyed its deltas relative to the wallet)
|
|
1494
|
+
* @throws {Error} with `code = 'LIMIT_ORDER_OUTCOME_MISMATCH'` on any failed assertion.
|
|
1495
|
+
*/
|
|
1496
|
+
export function assertLimitOrderDepositOutcome(sim, { inputMint, amount }) {
|
|
1497
|
+
const fail = (detail) => {
|
|
1498
|
+
const e = new Error(`Limit-order deposit outcome mismatch (LIMIT_ORDER_OUTCOME_MISMATCH): ${detail} Refusing to sign.`);
|
|
1499
|
+
e.code = 'LIMIT_ORDER_OUTCOME_MISMATCH';
|
|
1500
|
+
return e;
|
|
1501
|
+
};
|
|
1502
|
+
|
|
1503
|
+
if (!sim || typeof sim !== 'object' || sim.deltas == null) {
|
|
1504
|
+
throw fail('simulation returned no asset changes to verify.');
|
|
1505
|
+
}
|
|
1506
|
+
|
|
1507
|
+
const deltas = {};
|
|
1508
|
+
for (const [k, v] of Object.entries(sim.deltas)) {
|
|
1509
|
+
let amt;
|
|
1510
|
+
try {
|
|
1511
|
+
amt = typeof v === 'bigint' ? v : BigInt(v);
|
|
1512
|
+
} catch {
|
|
1513
|
+
throw fail(`simulated delta for ${k} (${v}) is not an integer.`);
|
|
1514
|
+
}
|
|
1515
|
+
deltas[k] = amt;
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
const foldNative = (mint) => (mint && SOLANA_NATIVE_SOL_ALIASES.has(mint) ? SOL_SENTINEL : mint);
|
|
1519
|
+
const inputAsset = foldNative(inputMint);
|
|
1520
|
+
if (!inputAsset) {
|
|
1521
|
+
throw fail('deposit is missing the input token address.');
|
|
1522
|
+
}
|
|
1523
|
+
const inputIsNative = inputAsset === SOL_SENTINEL;
|
|
1524
|
+
|
|
1525
|
+
let cap;
|
|
1526
|
+
try {
|
|
1527
|
+
cap = BigInt(amount);
|
|
1528
|
+
} catch {
|
|
1529
|
+
throw fail(`deposit amount (${amount}) is not an integer.`);
|
|
1530
|
+
}
|
|
1531
|
+
|
|
1532
|
+
const effectiveCap = inputIsNative ? cap + NATIVE_FEE_RENT_SLACK_LAMPORTS : cap;
|
|
1533
|
+
const inputDelta = deltas[inputAsset] || 0n;
|
|
1534
|
+
const outflow = inputDelta < 0n ? -inputDelta : 0n;
|
|
1535
|
+
|
|
1536
|
+
// --- magnitude bound: UPPER ---
|
|
1537
|
+
if (outflow > effectiveCap) {
|
|
1538
|
+
throw fail(`the input token (${inputAsset}) left the wallet by ${outflow}, exceeding the deposit amount (${cap}${inputIsNative ? ` plus fee/rent slack` : ''}).`);
|
|
1539
|
+
}
|
|
1540
|
+
|
|
1541
|
+
// --- magnitude bound: LOWER (floor) ---
|
|
1542
|
+
// The deposit must actually escrow the full `amount`; a partial outflow means the tx
|
|
1543
|
+
// rerouted or under-funded the deposit. Two cases, because native SOL carries fee/rent noise:
|
|
1544
|
+
if (inputIsNative) {
|
|
1545
|
+
// A native deposit's outflow is amount + base/priority fee + net ATA rent, so it is
|
|
1546
|
+
// normally ABOVE cap; the floor mainly catches a grossly under-funded deposit. But for
|
|
1547
|
+
// a tiny `amount` (<= the slack itself) the (cap - slack) window swallows the entire
|
|
1548
|
+
// requested amount, so outflow magnitude alone can no longer distinguish a genuine
|
|
1549
|
+
// (if undersized) deposit from an unrelated fee-only outflow that never escrowed
|
|
1550
|
+
// anything — admitting any nonzero outflow there would reopen exactly that gap.
|
|
1551
|
+
// Fail closed instead of trying to verify an amount the slack makes unverifiable.
|
|
1552
|
+
if (cap <= NATIVE_FEE_RENT_SLACK_LAMPORTS) {
|
|
1553
|
+
throw fail(`the deposit amount (${cap}) is too small relative to the fee/rent slack (${NATIVE_FEE_RENT_SLACK_LAMPORTS}) to verify by outflow magnitude.`);
|
|
1554
|
+
}
|
|
1555
|
+
const floor = cap - NATIVE_FEE_RENT_SLACK_LAMPORTS;
|
|
1556
|
+
if (outflow < floor) {
|
|
1557
|
+
throw fail(`the input token (${inputAsset}) left the wallet by only ${outflow}, below the deposit amount (${cap} minus fee/rent slack).`);
|
|
1558
|
+
}
|
|
1559
|
+
} else {
|
|
1560
|
+
// SPL deposit escrows EXACTLY `amount`; no fee is taken in the token, so the delta is
|
|
1561
|
+
// exact. Require equality — any shortfall is a partial drain / reroute (fail closed).
|
|
1562
|
+
if (outflow !== cap) {
|
|
1563
|
+
throw fail(`the input token (${inputAsset}) left the wallet by ${outflow}, not the exact deposit amount (${cap}).`);
|
|
1564
|
+
}
|
|
1565
|
+
}
|
|
1566
|
+
|
|
1567
|
+
// --- sibling loop: no OTHER token leaves the wallet (native-SOL dust tolerated) ---
|
|
1568
|
+
for (const [token, delta] of Object.entries(deltas)) {
|
|
1569
|
+
if (token === inputAsset) continue;
|
|
1570
|
+
if (delta >= 0n) continue;
|
|
1571
|
+
const dust = token === SOL_SENTINEL ? NATIVE_FEE_RENT_SLACK_LAMPORTS : 0n;
|
|
1572
|
+
if (-delta > dust) {
|
|
1573
|
+
throw fail(`a token other than the one you are depositing (${token}) left the wallet (delta ${delta}).`);
|
|
1574
|
+
}
|
|
1575
|
+
}
|
|
1576
|
+
|
|
1577
|
+
return { verified: true };
|
|
1578
|
+
}
|
|
1579
|
+
|
|
1580
|
+
/**
|
|
1581
|
+
* Verify a limit-order CANCEL's simulated wallet effect. A withdrawal is authorised by the
|
|
1582
|
+
* vault PDA and only returns funds TO the wallet, so NO token may leave the wallet except
|
|
1583
|
+
* native-SOL fee/rent dust, AND the order's own input asset must be refunded — by the full
|
|
1584
|
+
* expected remaining amount when it is known (`amount`), otherwise at least a genuine
|
|
1585
|
+
* inflow (> 0). Binding to the amount matters: a crafted "cancel" that redirects nearly all
|
|
1586
|
+
* the escrow elsewhere and refunds only a single dust unit of the right mint (or produces an
|
|
1587
|
+
* unrelated inflow, e.g. closing an empty token account back to the wallet for its rent)
|
|
1588
|
+
* would satisfy a bare > 0 check while draining the deposit. Fails closed otherwise.
|
|
1589
|
+
*
|
|
1590
|
+
* NOTE: this bounds MAGNITUDE (the right asset returns in the right amount), not destination
|
|
1591
|
+
* — a redirect of the correct asset+amount to a non-wallet address first, followed by a
|
|
1592
|
+
* genuine top-up of that same asset back to the wallet from elsewhere, would still pass.
|
|
1593
|
+
* That is closed by the vault-destination binding fast-follow, not here.
|
|
1594
|
+
*
|
|
1595
|
+
* @param {{deltas: Record<string, bigint|string|number>}} sim
|
|
1596
|
+
* (no walletAddress in ctx — the sim already keyed its deltas relative to the wallet)
|
|
1597
|
+
* @param {{inputMint: string, amount?: bigint|string|number}} ctx - the order's own deposited
|
|
1598
|
+
* asset (the refund must land here) and its expected remaining refund in base units. When
|
|
1599
|
+
* `amount` is OMITTED the check falls back to requiring a positive inflow only — this fallback
|
|
1600
|
+
* is DELIBERATELY WEAKER than the magnitude bind and is not a safe default: a caller that can
|
|
1601
|
+
* know the expected refund MUST pass it and fail closed when it is absent (as the cancel
|
|
1602
|
+
* command does — see classifyCancelRefund in limit-order.js), rather than relying on this
|
|
1603
|
+
* bare-inflow path, which admits a dust-refund/redirect it cannot catch. A non-null `amount`
|
|
1604
|
+
* that won't parse to an integer is a call-site bug and throws (never silently degrades).
|
|
1605
|
+
* @throws {Error} with `code = 'LIMIT_ORDER_OUTCOME_MISMATCH'` on any failed assertion.
|
|
1606
|
+
*/
|
|
1607
|
+
export function assertLimitOrderCancelOutcome(sim, { inputMint, amount } = {}) {
|
|
1608
|
+
const fail = (detail) => {
|
|
1609
|
+
const e = new Error(`Limit-order cancel outcome mismatch (LIMIT_ORDER_OUTCOME_MISMATCH): ${detail} Refusing to sign.`);
|
|
1610
|
+
e.code = 'LIMIT_ORDER_OUTCOME_MISMATCH';
|
|
1611
|
+
return e;
|
|
1612
|
+
};
|
|
1613
|
+
|
|
1614
|
+
if (!inputMint) {
|
|
1615
|
+
throw fail('the order\'s input mint is missing; cannot verify which asset the withdrawal must refund.');
|
|
1616
|
+
}
|
|
1617
|
+
|
|
1618
|
+
if (!sim || typeof sim !== 'object' || sim.deltas == null) {
|
|
1619
|
+
throw fail('simulation returned no asset changes to verify.');
|
|
1620
|
+
}
|
|
1621
|
+
|
|
1622
|
+
const deltas = {};
|
|
1623
|
+
for (const [k, v] of Object.entries(sim.deltas)) {
|
|
1624
|
+
let amt;
|
|
1625
|
+
try {
|
|
1626
|
+
amt = typeof v === 'bigint' ? v : BigInt(v);
|
|
1627
|
+
} catch {
|
|
1628
|
+
throw fail(`simulated delta for ${k} (${v}) is not an integer.`);
|
|
1629
|
+
}
|
|
1630
|
+
deltas[k] = amt;
|
|
1631
|
+
}
|
|
1632
|
+
|
|
1633
|
+
const foldNative = (mint) => (mint && SOLANA_NATIVE_SOL_ALIASES.has(mint) ? SOL_SENTINEL : mint);
|
|
1634
|
+
const inputAsset = foldNative(inputMint);
|
|
1635
|
+
|
|
1636
|
+
for (const [token, delta] of Object.entries(deltas)) {
|
|
1637
|
+
if (delta >= 0n) continue;
|
|
1638
|
+
const dust = token === SOL_SENTINEL ? NATIVE_FEE_RENT_SLACK_LAMPORTS : 0n;
|
|
1639
|
+
if (-delta > dust) {
|
|
1640
|
+
throw fail(`a token (${token}) left your wallet during cancellation (delta ${delta}); a withdrawal should only return funds to you.`);
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1643
|
+
|
|
1644
|
+
const inflow = deltas[inputAsset] || 0n;
|
|
1645
|
+
if (inflow <= 0n) {
|
|
1646
|
+
throw fail(`the withdrawal produced no inflow of the deposited asset (${inputAsset}) to your wallet; a cancel must return your deposited funds.`);
|
|
1647
|
+
}
|
|
1648
|
+
|
|
1649
|
+
// Bind the refund MAGNITUDE to the order's expected remaining input when it is known.
|
|
1650
|
+
// Without this, the > 0 check above is satisfied by a single dust unit, so a crafted
|
|
1651
|
+
// cancel could reroute nearly the whole escrow and still verify.
|
|
1652
|
+
// A caller either KNOWS the expected refund (pass it) or genuinely doesn't (omit it, taking
|
|
1653
|
+
// the deliberately weaker bare-inflow path — see the @param note). A non-null value that
|
|
1654
|
+
// won't parse is neither: it's a bug at the call site, so fail closed rather than silently
|
|
1655
|
+
// drop to the weak path and hand back the stronger-sounding guarantee the name implies.
|
|
1656
|
+
let expected;
|
|
1657
|
+
if (amount != null) {
|
|
1658
|
+
try {
|
|
1659
|
+
expected = BigInt(amount);
|
|
1660
|
+
} catch {
|
|
1661
|
+
throw fail(`the expected refund amount (${amount}) is not an integer; cannot verify refund magnitude.`);
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
if (expected != null && expected > 0n) {
|
|
1665
|
+
if (inputAsset === SOL_SENTINEL) {
|
|
1666
|
+
// Net native inflow is the refund minus this tx's fee, plus any temp-WSOL rent
|
|
1667
|
+
// returned, so it sits within ± fee/rent slack of the expected refund. Two-sided —
|
|
1668
|
+
// BUT when the expected refund is itself <= that slack, the lower bound
|
|
1669
|
+
// (expected - slack) collapses to <= 0 and the band degenerates to the bare
|
|
1670
|
+
// inflow > 0 floor above: a single dust lamport would verify while the rest of the
|
|
1671
|
+
// escrow is rerouted elsewhere. Fail closed instead, exactly as the deposit asserter
|
|
1672
|
+
// does for an amount the slack makes unverifiable, rather than admit a floor below a
|
|
1673
|
+
// meaningful bound.
|
|
1674
|
+
if (expected <= NATIVE_FEE_RENT_SLACK_LAMPORTS) {
|
|
1675
|
+
throw fail(`the expected remaining refund (${expected}) is too small relative to the fee/rent slack (${NATIVE_FEE_RENT_SLACK_LAMPORTS}) to verify by native-SOL inflow magnitude.`);
|
|
1676
|
+
}
|
|
1677
|
+
const lo = expected - NATIVE_FEE_RENT_SLACK_LAMPORTS;
|
|
1678
|
+
const hi = expected + NATIVE_FEE_RENT_SLACK_LAMPORTS;
|
|
1679
|
+
if (inflow < lo || inflow > hi) {
|
|
1680
|
+
throw fail(`the withdrawal returned ${inflow} of native SOL, outside the expected remaining refund (${expected} ± fee/rent slack); a cancel must return the full remaining deposit.`);
|
|
1681
|
+
}
|
|
1682
|
+
} else if (inflow !== expected) {
|
|
1683
|
+
// SPL escrow returns EXACTLY the remaining input — no fee is taken in the token.
|
|
1684
|
+
throw fail(`the withdrawal returned ${inflow} of the deposited asset (${inputAsset}), not the expected remaining refund (${expected}); a cancel must return the full remaining deposit.`);
|
|
1685
|
+
}
|
|
1686
|
+
}
|
|
1687
|
+
|
|
1688
|
+
return { verified: true };
|
|
1689
|
+
}
|
|
1690
|
+
|
|
1480
1691
|
/**
|
|
1481
1692
|
* Statically inspect a Solana transaction's instructions for drain vectors a
|
|
1482
1693
|
* balance-delta simulation can't see — granting a token delegate, changing a
|
|
@@ -1505,10 +1716,16 @@ export function assertSolanaSwapOutcome(request, quote, sim, { slippage, sibling
|
|
|
1505
1716
|
* proceeds) when no simulation RPC endpoint is configured, so this static
|
|
1506
1717
|
* check plus the metadata binding remain the ONLY transaction-level guards
|
|
1507
1718
|
* whenever a sim RPC is unavailable. Limit-order vault deposit/cancel
|
|
1508
|
-
* (limit-order.js)
|
|
1509
|
-
*
|
|
1510
|
-
*
|
|
1511
|
-
*
|
|
1719
|
+
* (limit-order.js) have no swap quote (no declared input/output pair), so they
|
|
1720
|
+
* use their own outcome asserters instead — assertLimitOrderDepositOutcome and
|
|
1721
|
+
* assertLimitOrderCancelOutcome, run via verifyLimitOrderOutcome immediately
|
|
1722
|
+
* after this check — which close the sibling-transfer gap and bound the
|
|
1723
|
+
* deposit/withdrawal magnitude the same way assertSolanaSwapOutcome does for
|
|
1724
|
+
* swaps. What those asserters cannot see is *destination*: a deposit that
|
|
1725
|
+
* moves exactly `amount` of the input token to a non-vault address still
|
|
1726
|
+
* passes, since balance-delta simulation of the wallet's own accounts can't
|
|
1727
|
+
* tell where funds landed. That is tracked as a separate fast-follow (binding
|
|
1728
|
+
* the vault's token-account destination), not covered here.
|
|
1512
1729
|
*
|
|
1513
1730
|
* Within that scope, the SPL Token program requires the *authority* of
|
|
1514
1731
|
* Approve/ApproveChecked/SetAuthority/CloseAccount to sign the transaction,
|
package/src/trading.js
CHANGED
|
@@ -288,10 +288,11 @@ export async function executeTransaction(params, { retries = 2, retryDelayMs = 1
|
|
|
288
288
|
|
|
289
289
|
if (!parsed) {
|
|
290
290
|
// Non-JSON on a sub-500 status (a Cloudflare challenge or HTML error
|
|
291
|
-
// page).
|
|
291
|
+
// page). A clean sub-500 HTTP response is a definitive edge/backend
|
|
292
|
+
// rejection, so it stays nonfatal and leaves the quote reusable.
|
|
292
293
|
lastError = Object.assign(
|
|
293
294
|
new Error(`Execute API returned non-JSON response (status ${res.status}). This may be a Cloudflare challenge or server error.`),
|
|
294
|
-
{ code: '
|
|
295
|
+
{ code: 'EXECUTE_ERROR', status: res.status, details: text.slice(0, 200) }
|
|
295
296
|
);
|
|
296
297
|
throw lastError;
|
|
297
298
|
}
|
|
@@ -8,7 +8,6 @@
|
|
|
8
8
|
import crypto from 'crypto';
|
|
9
9
|
import { NansenError, ErrorCode } from './api.js';
|
|
10
10
|
import { wcExec } from './walletconnect-exec.js';
|
|
11
|
-
import { EVM_CHAIN_IDS } from './chain-ids.js';
|
|
12
11
|
import { evaluatePaymentRequirement, resolvePaymentAmount, resolvePayTo } from './x402-policy.js';
|
|
13
12
|
|
|
14
13
|
/**
|
|
@@ -54,11 +53,33 @@ function parseChainId(network) {
|
|
|
54
53
|
*/
|
|
55
54
|
export function buildEIP712TypedData({ fromAddress, requirement }) {
|
|
56
55
|
const payTo = resolvePayTo(requirement);
|
|
57
|
-
const { asset,
|
|
56
|
+
const { asset, maxTimeoutSeconds } = requirement;
|
|
57
|
+
const extra = requirement.extra || {};
|
|
58
58
|
const amount = resolvePaymentAmount(requirement);
|
|
59
59
|
|
|
60
|
-
|
|
61
|
-
|
|
60
|
+
if (!extra.name || !extra.version) {
|
|
61
|
+
throw new Error(
|
|
62
|
+
'Refusing to sign x402 payment: EIP-712 domain name/version missing from requirement.extra.',
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Chain id comes only from the CAIP-2 network the policy validated — not from
|
|
67
|
+
// a remote extra.chainId override, which could change the signing domain.
|
|
68
|
+
const chainId = parseChainId(requirement.network);
|
|
69
|
+
if (chainId === null) {
|
|
70
|
+
throw new Error(
|
|
71
|
+
`Refusing to sign x402 payment: unsupported or missing EVM network ${requirement.network}.`,
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
// A remote extra.chainId that disagrees with the network is a domain-binding
|
|
75
|
+
// mismatch — refuse rather than sign under either interpretation. A null or
|
|
76
|
+
// empty extra.chainId means "unspecified", not a conflict, so treat it as absent.
|
|
77
|
+
if (extra.chainId != null && extra.chainId !== '' && Number(extra.chainId) !== chainId) {
|
|
78
|
+
throw new Error(
|
|
79
|
+
`Refusing to sign x402 payment: extra.chainId ${extra.chainId} conflicts with ` +
|
|
80
|
+
`network ${requirement.network} (chain id ${chainId}).`,
|
|
81
|
+
);
|
|
82
|
+
}
|
|
62
83
|
|
|
63
84
|
const now = Math.floor(Date.now() / 1000);
|
|
64
85
|
const nonce = '0x' + crypto.randomBytes(32).toString('hex');
|
package/src/x402-evm.js
CHANGED
|
@@ -215,12 +215,16 @@ export function createEvmPaymentPayload(requirements, privateKeyHex, walletAddre
|
|
|
215
215
|
throw new Error(`Unsupported assetTransferMethod: ${method}`);
|
|
216
216
|
}
|
|
217
217
|
|
|
218
|
-
// Token name and version from requirements.extra (set by server/facilitator)
|
|
218
|
+
// Token name and version from requirements.extra (set by server/facilitator).
|
|
219
|
+
// Both are required: the EIP-712 domain version varies by token (USDC on Base
|
|
220
|
+
// is "2", USDT0/BSC tokens are "1"), so guessing a default would silently
|
|
221
|
+
// produce an invalid signature. Refuse instead — matches the walletconnect/Privy
|
|
222
|
+
// path in buildEIP712TypedData.
|
|
219
223
|
const tokenName = extra.name;
|
|
220
|
-
const tokenVersion = extra.version
|
|
224
|
+
const tokenVersion = extra.version;
|
|
221
225
|
|
|
222
|
-
if (!tokenName) {
|
|
223
|
-
throw new Error('EIP-712 domain name missing from requirements.extra');
|
|
226
|
+
if (!tokenName || !tokenVersion) {
|
|
227
|
+
throw new Error('EIP-712 domain name/version missing from requirements.extra');
|
|
224
228
|
}
|
|
225
229
|
|
|
226
230
|
// Generate random nonce (32 bytes)
|
package/src/x402-policy.js
CHANGED
|
@@ -7,6 +7,11 @@
|
|
|
7
7
|
import { EVM_X402_TOKENS, SVM_X402_TOKENS } from './x402-tokens.js';
|
|
8
8
|
import { getWalletConfig } from './wallet.js';
|
|
9
9
|
|
|
10
|
+
// The only x402 scheme this client can honour. "exact" = a fixed-amount transfer
|
|
11
|
+
// authorization (EIP-3009 / Permit2 on EVM, SPL TransferChecked on SVM). Any other
|
|
12
|
+
// scheme must be refused before signing, not silently accepted.
|
|
13
|
+
export const SUPPORTED_X402_SCHEMES = new Set(['exact']);
|
|
14
|
+
|
|
10
15
|
/**
|
|
11
16
|
* True for the exact Solana CAIP-2 network prefix ("solana:..."), matching
|
|
12
17
|
* isSvmNetwork() in x402-svm.js. Duplicated here (rather than imported) to
|
|
@@ -36,7 +41,7 @@ export function resolveKnownToken(network, asset) {
|
|
|
36
41
|
return table.find(t => t.token.toLowerCase() === asset.toLowerCase()) || null;
|
|
37
42
|
}
|
|
38
43
|
if (isSvmNetworkString(network)) {
|
|
39
|
-
const table = SVM_X402_TOKENS['solana'
|
|
44
|
+
const table = SVM_X402_TOKENS[network]; // exact CAIP-2 key, not the bare 'solana' prefix
|
|
40
45
|
if (!table) return null;
|
|
41
46
|
return table.find(t => t.token === asset) || null;
|
|
42
47
|
}
|
|
@@ -130,6 +135,16 @@ export function resolvePayTo(requirement) {
|
|
|
130
135
|
* allowlist, per-payment USD cap. Never signs; pure decision.
|
|
131
136
|
*/
|
|
132
137
|
export function evaluatePaymentRequirement(requirement) {
|
|
138
|
+
const scheme = requirement.scheme;
|
|
139
|
+
if (!SUPPORTED_X402_SCHEMES.has(scheme)) {
|
|
140
|
+
return {
|
|
141
|
+
ok: false,
|
|
142
|
+
reason:
|
|
143
|
+
`Refusing to auto-pay: unsupported payment scheme ${scheme == null ? '(missing)' : `"${scheme}"`}. ` +
|
|
144
|
+
`Only "exact" is supported. No signature was produced.`,
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
133
148
|
const network = requirement.network;
|
|
134
149
|
const asset = requirement.asset;
|
|
135
150
|
const payTo = resolvePayTo(requirement);
|
package/src/x402-svm.js
CHANGED
|
@@ -7,6 +7,7 @@ import crypto from 'crypto';
|
|
|
7
7
|
import { base58Encode, base58DecodePubkey } from './wallet.js';
|
|
8
8
|
import { encodeCompactU16, deriveATA as _deriveATA } from './transfer.js';
|
|
9
9
|
import { resolvePaymentAmount, resolvePayTo } from './x402-policy.js';
|
|
10
|
+
import { SOLANA_MAINNET_NETWORK } from './x402-tokens.js';
|
|
10
11
|
|
|
11
12
|
// ============= Constants =============
|
|
12
13
|
|
|
@@ -329,13 +330,14 @@ export async function fetchRecentBlockhash(rpcUrl = 'https://api.mainnet-beta.so
|
|
|
329
330
|
* Get RPC URL for a Solana network identifier.
|
|
330
331
|
*/
|
|
331
332
|
export function getSolanaRpcUrl(network) {
|
|
332
|
-
if (network
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
return 'https://api.
|
|
333
|
+
if (network === SOLANA_MAINNET_NETWORK) return 'https://api.mainnet-beta.solana.com';
|
|
334
|
+
// Devnet/testnet resolve for tooling (e.g. balance checks), but the x402 pay
|
|
335
|
+
// path never reaches them: SVM_X402_TOKENS is mainnet-only, so the policy layer
|
|
336
|
+
// refuses a devnet/testnet requirement before signing. Adding a non-mainnet
|
|
337
|
+
// token entry would silently enable signing here — revisit this gate if you do.
|
|
338
|
+
if (network === 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1') return 'https://api.devnet.solana.com';
|
|
339
|
+
if (network === 'solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z') return 'https://api.testnet.solana.com';
|
|
340
|
+
throw new Error(`Unsupported Solana network for x402: ${network}`);
|
|
339
341
|
}
|
|
340
342
|
|
|
341
343
|
/**
|
package/src/x402-tokens.js
CHANGED
|
@@ -21,9 +21,14 @@ export const EVM_X402_TOKENS = {
|
|
|
21
21
|
],
|
|
22
22
|
};
|
|
23
23
|
|
|
24
|
-
//
|
|
24
|
+
// Canonical Solana mainnet CAIP-2 id.
|
|
25
|
+
// x402 payment tokens are mainnet mints, so mainnet is the only valid payment network.
|
|
26
|
+
export const SOLANA_MAINNET_NETWORK = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';
|
|
27
|
+
|
|
28
|
+
// Known payment tokens on Solana, keyed by exact CAIP-2 network (symmetric with EVM_X402_TOKENS).
|
|
29
|
+
// Unknown or devnet/testnet solana:* ids resolve to no token and are refused by the policy.
|
|
25
30
|
export const SVM_X402_TOKENS = {
|
|
26
|
-
|
|
31
|
+
[SOLANA_MAINNET_NETWORK]: [
|
|
27
32
|
{ token: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', symbol: 'USDC', decimals: 6 },
|
|
28
33
|
],
|
|
29
34
|
};
|