nansen-cli 1.43.1 → 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 +94 -0
- package/README.md +34 -0
- package/package.json +1 -1
- package/src/api.js +206 -28
- package/src/bridge.js +103 -5
- package/src/cli.js +81 -56
- package/src/commands/alerts.js +56 -16
- package/src/commands/completion.js +652 -0
- package/src/commands/mcp.js +19 -3
- package/src/commands/research.js +199 -25
- package/src/hl-client.js +20 -8
- package/src/limit-order.js +223 -34
- package/src/mcp-verify.js +66 -1
- package/src/perp.js +72 -24
- package/src/query-options.js +32 -0
- package/src/schema.json +642 -133
- package/src/semver.js +26 -0
- package/src/telemetry.js +133 -24
- package/src/trade-validation.js +222 -5
- package/src/trading.js +198 -23
- package/src/update-check.js +13 -6
- 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/src/x402.js +8 -1
package/src/semver.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compare two semver strings. Returns 1 if a > b, -1 if a < b, 0 if equal.
|
|
3
|
+
*
|
|
4
|
+
* A missing trailing component is treated as 0 ("1.43" reads as "1.43.0"),
|
|
5
|
+
* not as `undefined` — `undefined` would make every `>` comparison against it
|
|
6
|
+
* false in both directions, so a version that matches on major.minor always
|
|
7
|
+
* came out "less than" a value that only specified major.minor (e.g.
|
|
8
|
+
* `compareSemver('1.43.1', '1.43')` fell through to comparing `1 > undefined`,
|
|
9
|
+
* which is false, so it returned -1 instead of 1).
|
|
10
|
+
*
|
|
11
|
+
* Shared by `nansen changelog --since` (src/cli.js) and the update-notifier's
|
|
12
|
+
* version check (src/update-check.js) so both compare versions the same,
|
|
13
|
+
* correct way instead of each hand-rolling its own parser.
|
|
14
|
+
*/
|
|
15
|
+
export function compareSemver(a, b) {
|
|
16
|
+
const parse = v => {
|
|
17
|
+
const parts = String(v).replace(/^v/, '').split('.').map(Number);
|
|
18
|
+
return [parts[0] || 0, parts[1] || 0, parts[2] || 0];
|
|
19
|
+
};
|
|
20
|
+
const [aM, am, ap] = parse(a);
|
|
21
|
+
const [bM, bm, bp] = parse(b);
|
|
22
|
+
if (aM !== bM) return aM > bM ? 1 : -1;
|
|
23
|
+
if (am !== bm) return am > bm ? 1 : -1;
|
|
24
|
+
if (ap !== bp) return ap > bp ? 1 : -1;
|
|
25
|
+
return 0;
|
|
26
|
+
}
|
package/src/telemetry.js
CHANGED
|
@@ -5,10 +5,13 @@
|
|
|
5
5
|
* how long they take, and where errors occur. Events are fire-and-forget —
|
|
6
6
|
* failures are silently ignored and never block the CLI.
|
|
7
7
|
*
|
|
8
|
-
* Perp `order`/`close` additionally emit
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
8
|
+
* Perp `order`/`close` additionally emit one canonical `trade_perps_*` outcome
|
|
9
|
+
* event per Hyperliquid response leg. Each event carries the leg's side,
|
|
10
|
+
* outcome and order id plus a shared submission id and SHA-256 wallet
|
|
11
|
+
* identifier. Raw wallet addresses, prices, sizes and exchange error text are
|
|
12
|
+
* never sent. The standard anonymous_id lets BI resolve a Nansen user when
|
|
13
|
+
* one is available.
|
|
14
|
+
* All telemetry is opt-out via DO_NOT_TRACK=1 or NANSEN_NO_TELEMETRY=1.
|
|
12
15
|
*/
|
|
13
16
|
|
|
14
17
|
import fs from 'fs';
|
|
@@ -28,6 +31,16 @@ const TELEMETRY_URL =
|
|
|
28
31
|
|
|
29
32
|
const TIMEOUT_MS = 1000;
|
|
30
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
|
+
|
|
31
44
|
// ─── opt-out ──────────────────────────────────────────────
|
|
32
45
|
|
|
33
46
|
/**
|
|
@@ -80,8 +93,8 @@ export function getAnonymousId() {
|
|
|
80
93
|
if (!_anonymousId) {
|
|
81
94
|
_anonymousId = crypto.randomUUID();
|
|
82
95
|
try {
|
|
83
|
-
fs.mkdirSync(path.dirname(TELEMETRY_ID_FILE), { recursive: true });
|
|
84
|
-
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 });
|
|
85
98
|
} catch { /* best-effort persist */ }
|
|
86
99
|
}
|
|
87
100
|
}
|
|
@@ -118,7 +131,7 @@ export function getSessionId() {
|
|
|
118
131
|
_sessionId = raw.id;
|
|
119
132
|
// touch timestamp, but only if >1 min elapsed to reduce writes
|
|
120
133
|
if (now - raw.ts > 60_000) {
|
|
121
|
-
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 */ }
|
|
122
135
|
}
|
|
123
136
|
return _sessionId;
|
|
124
137
|
}
|
|
@@ -126,8 +139,8 @@ export function getSessionId() {
|
|
|
126
139
|
|
|
127
140
|
_sessionId = crypto.randomUUID();
|
|
128
141
|
try {
|
|
129
|
-
fs.mkdirSync(path.dirname(SESSION_FILE), { recursive: true });
|
|
130
|
-
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 });
|
|
131
144
|
} catch { /* best-effort */ }
|
|
132
145
|
return _sessionId;
|
|
133
146
|
}
|
|
@@ -167,6 +180,54 @@ function buildContext() {
|
|
|
167
180
|
};
|
|
168
181
|
}
|
|
169
182
|
|
|
183
|
+
function hashWalletAddress(walletAddress) {
|
|
184
|
+
if (!walletAddress) return undefined;
|
|
185
|
+
return crypto
|
|
186
|
+
.createHash('sha256')
|
|
187
|
+
.update(String(walletAddress).toLowerCase())
|
|
188
|
+
.digest('base64');
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function contentDerivedUuid(value) {
|
|
192
|
+
const bytes = crypto.createHash('sha256').update(value).digest().subarray(0, 16);
|
|
193
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x50;
|
|
194
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
195
|
+
const hex = bytes.toString('hex');
|
|
196
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function perpLegAttemptId({ wallet_address, submission_id, leg_index }) {
|
|
200
|
+
if (
|
|
201
|
+
wallet_address === undefined
|
|
202
|
+
|| wallet_address === null
|
|
203
|
+
|| submission_id === undefined
|
|
204
|
+
|| submission_id === null
|
|
205
|
+
|| leg_index === undefined
|
|
206
|
+
|| leg_index === null
|
|
207
|
+
) {
|
|
208
|
+
return crypto.randomUUID();
|
|
209
|
+
}
|
|
210
|
+
return contentDerivedUuid(`${String(wallet_address).toLowerCase()}:${submission_id}:${leg_index}`);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function perpOutcomeEventId({ wallet_address, submission_id, leg_index, outcome }) {
|
|
214
|
+
if (
|
|
215
|
+
wallet_address === undefined
|
|
216
|
+
|| wallet_address === null
|
|
217
|
+
|| submission_id === undefined
|
|
218
|
+
|| submission_id === null
|
|
219
|
+
|| leg_index === undefined
|
|
220
|
+
|| leg_index === null
|
|
221
|
+
|| outcome === undefined
|
|
222
|
+
|| outcome === null
|
|
223
|
+
) {
|
|
224
|
+
return crypto.randomUUID();
|
|
225
|
+
}
|
|
226
|
+
return contentDerivedUuid(
|
|
227
|
+
`${String(wallet_address).toLowerCase()}:${submission_id}:${leg_index}:${outcome}`,
|
|
228
|
+
);
|
|
229
|
+
}
|
|
230
|
+
|
|
170
231
|
// ─── public API ────────────────────────────────────────────
|
|
171
232
|
|
|
172
233
|
/**
|
|
@@ -258,7 +319,7 @@ export function trackCommandFailed({
|
|
|
258
319
|
}
|
|
259
320
|
|
|
260
321
|
/**
|
|
261
|
-
* Track
|
|
322
|
+
* Track one Hyperliquid perp response leg (`nansen perp order` / `perp close`).
|
|
262
323
|
*
|
|
263
324
|
* Fired from `buildScreenSignSubmit` in perp.js AFTER the HL /exchange response
|
|
264
325
|
* is parsed (`summarizeOrderResult`). This is the only event that sees the order
|
|
@@ -268,25 +329,61 @@ export function trackCommandFailed({
|
|
|
268
329
|
* Hyperliquid — Decision D4), so the backend never sees the response either;
|
|
269
330
|
* this client-side event is the only way order outcomes reach BI.
|
|
270
331
|
*
|
|
271
|
-
*
|
|
272
|
-
*
|
|
332
|
+
* Reuse the canonical trade_perps order/close succeeded/failed event names so
|
|
333
|
+
* CLI, web, mobile, and backend share one BI vocabulary. Exchange rejections
|
|
334
|
+
* with a parsed response emit the matching `*_failed` event before
|
|
335
|
+
* the original command error is rethrown. Network and indeterminate timeout
|
|
336
|
+
* failures remain covered only by `cli_command_failed` because no authoritative
|
|
337
|
+
* exchange response exists.
|
|
273
338
|
*
|
|
274
|
-
*
|
|
275
|
-
*
|
|
276
|
-
*
|
|
277
|
-
*
|
|
278
|
-
*
|
|
339
|
+
* One event is emitted for each response leg. This preserves bracket and batch
|
|
340
|
+
* order identity without putting a nested array contract into the BI pipeline.
|
|
341
|
+
* A trade/fill id is not carried by the placement response; BI joins each safe
|
|
342
|
+
* `oid` to Hyperliquid fills to obtain it. The wallet is SHA-256 hashed using
|
|
343
|
+
* the same lower-case convention as BI's `hash_address` macro.
|
|
279
344
|
*
|
|
280
345
|
* @param {object} opts
|
|
281
346
|
* @param {'order'|'close'} opts.command - Which perp command placed the order (routes `path`)
|
|
282
|
-
* @param {'buy'|'sell'} opts.side -
|
|
283
|
-
* @param {
|
|
347
|
+
* @param {'buy'|'sell'} opts.side - This leg's normalized trade side
|
|
348
|
+
* @param {'long'|'short'} [opts.position_side] - Position side after accounting for reduce-only
|
|
349
|
+
* @param {'filled'|'resting'|'rejected'} opts.outcome - Exchange outcome
|
|
350
|
+
* @param {string} opts.submission_id - Shared id for all legs in one action
|
|
351
|
+
* @param {number} opts.leg_index - Zero-based response-leg index
|
|
352
|
+
* @param {string} opts.leg - parent/take-profit/stop-loss/leg N
|
|
353
|
+
* @param {string} opts.wallet_address - Raw signer address; hashed before send
|
|
354
|
+
* @param {number} [opts.oid] - Hyperliquid order id (omitted if imprecise/unavailable)
|
|
355
|
+
* @param {string} [opts.error_code] - Stable local code; never raw exchange text
|
|
284
356
|
*/
|
|
285
|
-
export function trackPerpOrderCompleted({
|
|
357
|
+
export function trackPerpOrderCompleted({
|
|
358
|
+
command,
|
|
359
|
+
side,
|
|
360
|
+
position_side,
|
|
361
|
+
outcome,
|
|
362
|
+
submission_id,
|
|
363
|
+
leg_index,
|
|
364
|
+
leg,
|
|
365
|
+
wallet_address,
|
|
366
|
+
oid,
|
|
367
|
+
error_code,
|
|
368
|
+
}) {
|
|
369
|
+
const walletAddressHash = hashWalletAddress(wallet_address);
|
|
370
|
+
const attemptId = perpLegAttemptId({ wallet_address, submission_id, leg_index });
|
|
371
|
+
const eventId = perpOutcomeEventId({ wallet_address, submission_id, leg_index, outcome });
|
|
372
|
+
const event = `trade_perps_${command === 'close' ? 'close' : 'order'}_${outcome === 'rejected' ? 'failed' : 'succeeded'}`;
|
|
373
|
+
// position_side is supplied per leg by summarizeOrderResult (reduceOnly-aware,
|
|
374
|
+
// undefined when the leg's own side is unknown). Only derive a fallback when a
|
|
375
|
+
// real leg side is present; never fabricate a position_side from the
|
|
376
|
+
// command-level side when the leg's side is unknown — that would corrupt the
|
|
377
|
+
// wallet-scoped joins in the companion dbt change.
|
|
378
|
+
const positionSide = position_side ?? (side === undefined
|
|
379
|
+
? undefined
|
|
380
|
+
: command === 'close'
|
|
381
|
+
? (side === 'buy' ? 'short' : 'long')
|
|
382
|
+
: (side === 'buy' ? 'long' : 'short'));
|
|
286
383
|
return sendEvent({
|
|
287
|
-
event
|
|
384
|
+
event,
|
|
288
385
|
event_source: getEventSource(),
|
|
289
|
-
event_id:
|
|
386
|
+
event_id: eventId,
|
|
290
387
|
user_id: null,
|
|
291
388
|
anonymous_id: getAnonymousId(),
|
|
292
389
|
session_id: getSessionId(),
|
|
@@ -295,9 +392,21 @@ export function trackPerpOrderCompleted({ command, side, oid }) {
|
|
|
295
392
|
// "/perp/close"), so BI can line the two events up per command.
|
|
296
393
|
path: commandToPath(`perp ${command}`),
|
|
297
394
|
properties: {
|
|
298
|
-
source
|
|
299
|
-
|
|
395
|
+
// Canonical trade events use a stable product source. The CLI release is
|
|
396
|
+
// already preserved in context.client_version by buildContext().
|
|
397
|
+
source: 'cli',
|
|
398
|
+
chain: 'hyperliquid',
|
|
399
|
+
attempt_id: attemptId,
|
|
400
|
+
action: command === 'close' ? 'close' : 'open',
|
|
401
|
+
position_side: positionSide,
|
|
402
|
+
order_side: side,
|
|
403
|
+
execution_status: outcome,
|
|
404
|
+
...(submission_id !== undefined && { submission_id: String(submission_id) }),
|
|
405
|
+
leg_index,
|
|
406
|
+
leg,
|
|
407
|
+
...(walletAddressHash && { wallet_address_hash: walletAddressHash }),
|
|
300
408
|
...(oid !== undefined && { oid }),
|
|
409
|
+
...(error_code && { error_code }),
|
|
301
410
|
},
|
|
302
411
|
context: buildContext(),
|
|
303
412
|
});
|
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,
|