nansen-cli 2.0.1 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/package.json +2 -2
- package/src/auth-credentials.js +15 -3
- package/src/auth-state.js +8 -6
- package/src/auth-store-worker.js +4 -3
- package/src/bridge.js +105 -77
- package/src/cache-inspect.js +3 -7
- package/src/doctor.js +1 -1
- package/src/local-file.js +75 -0
- package/src/schema.json +26 -1
- package/src/solana-tx.js +74 -0
- package/src/trading.js +76 -40
- package/src/wallet.js +16 -35
- package/src/x402-svm.js +165 -7
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,25 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 2.1.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [#728](https://github.com/nansen-ai/nansen-cli/pull/728) [`c5ef96f`](https://github.com/nansen-ai/nansen-cli/commit/c5ef96f63181711304f832f26c5156c8c2d5841c) Thanks [@gulshngill](https://github.com/gulshngill)! - Drop support for Node.js 20 (EOL since April 2026). The minimum supported version is now Node.js 22: `engines.node` is `>=22.0.0`, CI tests on Node 22 and 24, and `nansen doctor` reports Node 20 as below the required version.
|
|
8
|
+
|
|
9
|
+
- [#584](https://github.com/nansen-ai/nansen-cli/pull/584) [`435ae1a`](https://github.com/nansen-ai/nansen-cli/commit/435ae1a717f7f3771ccce4dd3026851bbccd8166) Thanks [@ygd58](https://github.com/ygd58)! - `nansen wallet list` now prints the standard JSON envelope on stdout, `{"success":true,"data":{"wallets":[...],"defaultWallet":...}}`, so `nansen wallet list | jq .` works and `--pretty`, `--table`, `--format csv` and `--fields` apply to it like any other command. It previously printed a readable summary with no data envelope, which agents could not parse. The output is the same in a terminal and in a pipe; use `--pretty` for readable JSON or `--table` for a table. With no wallets it returns an empty `wallets` list instead of a hint.
|
|
10
|
+
|
|
11
|
+
- [#727](https://github.com/nansen-ai/nansen-cli/pull/727) [`9404c13`](https://github.com/nansen-ai/nansen-cli/commit/9404c13ec32a063cbc54aba697e6297374993591) Thanks [@hulk-linus](https://github.com/apps/hulk-linus)! - `nansen wallet show <name>` now prints the standard JSON envelope on stdout, `{"success":true,"data":{"name":...,"provider":...,"evm":...,"solana":...,"createdAt":...,"isDefault":...}}`, so `nansen wallet show main | jq .` works and `--pretty`, `--table`, `--format csv` and `--fields` apply to it. Privy wallets also include `privyWalletIds`. The redacted default of `nansen wallet export <name>` does the same, returning `{"name":...,"redacted":true,"evm":{"address":...},"solana":{"address":...}}` with no key fields. Both previously printed a readable summary that agents could not parse. `wallet export --reveal` and `--file` are unchanged.
|
|
12
|
+
|
|
13
|
+
### Patch Changes
|
|
14
|
+
|
|
15
|
+
- [#724](https://github.com/nansen-ai/nansen-cli/pull/724) [`1f2fc6e`](https://github.com/nansen-ai/nansen-cli/commit/1f2fc6e3b76ae9faa66202ba295c1d668ae33a73) Thanks [@hulk-linus](https://github.com/apps/hulk-linus)! - Use the resolved gas limit when signing local EVM swaps, including quotes with both gas and gasLimit fields.
|
|
16
|
+
|
|
17
|
+
- [#731](https://github.com/nansen-ai/nansen-cli/pull/731) [`f4cf188`](https://github.com/nansen-ai/nansen-cli/commit/f4cf188191b0973d7058381febccf36149cfaba5) Thanks [@hulk-linus](https://github.com/apps/hulk-linus)! - Reject symlinks, hard links, and replaced files when reading saved authentication and trading quotes. Validate authentication lock descriptors before use. Claim bridge quotes before signing and block reuse if a post-broadcast execution marker cannot be saved. Authentication reads now require user-owned paths without group or other write permissions on POSIX; repair permissions before retrying an unsafe saved-key read.
|
|
18
|
+
|
|
19
|
+
- [#729](https://github.com/nansen-ai/nansen-cli/pull/729) [`7b54c0e`](https://github.com/nansen-ai/nansen-cli/commit/7b54c0e5448f672dadb071a467f7812ad6775581) Thanks [@gulshngill](https://github.com/gulshngill)! - Solana-source bridge routes that are too large to fit in a transaction without address lookup tables (for example a token swap ahead of the bridge deposit) now compile and sign. The CLI fetches the route's lookup tables, checks that each one is active and on-chain, and uses them to compress accounts. Routes that already fit are compiled as before.
|
|
20
|
+
|
|
21
|
+
- [#733](https://github.com/nansen-ai/nansen-cli/pull/733) [`353629a`](https://github.com/nansen-ai/nansen-cli/commit/353629a5ddf8dcace3fe66cba653e33e41330067) Thanks [@kome12](https://github.com/kome12)! - `trade execute`: accept a capitalised chain name. `trade quote --chain Base` stores the chain exactly as you typed it, but the RPC registry is keyed lowercase, so the quote could be created and then never executed ("No RPC URL configured for chain: Base"). The chain is now normalised once when the quote is loaded, which also fixes quotes already on disk.
|
|
22
|
+
|
|
3
23
|
## 2.0.1
|
|
4
24
|
|
|
5
25
|
### Patch Changes
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nansen-cli",
|
|
3
|
-
"version": "2.0
|
|
3
|
+
"version": "2.1.0",
|
|
4
4
|
"description": "AI-agent CLI for Nansen API analytics, DEX swaps, and cross-chain trading",
|
|
5
5
|
"main": "src/index.js",
|
|
6
6
|
"type": "module",
|
|
@@ -64,7 +64,7 @@
|
|
|
64
64
|
},
|
|
65
65
|
"homepage": "https://github.com/nansen-ai/nansen-cli#readme",
|
|
66
66
|
"engines": {
|
|
67
|
-
"node": ">=
|
|
67
|
+
"node": ">=22.0.0"
|
|
68
68
|
},
|
|
69
69
|
"devDependencies": {
|
|
70
70
|
"@changesets/changelog-github": "^0.5.1",
|
package/src/auth-credentials.js
CHANGED
|
@@ -2,6 +2,7 @@ import fs from 'node:fs';
|
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import os from 'node:os';
|
|
4
4
|
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { readLocalFile } from './local-file.js';
|
|
5
6
|
|
|
6
7
|
export const DEFAULT_API_ORIGIN = 'https://api.nansen.ai';
|
|
7
8
|
const DEV_CONFIG = fileURLToPath(new URL('../config.json', import.meta.url));
|
|
@@ -32,17 +33,28 @@ export function validAuthPointer(auth) {
|
|
|
32
33
|
}
|
|
33
34
|
export function readAuthConfig(env = process.env, devConfigPath = DEV_CONFIG) {
|
|
34
35
|
const userPath = path.join(authDirectory(env), 'config.json');
|
|
35
|
-
|
|
36
|
+
let configFileExists;
|
|
37
|
+
try { configFileExists = Boolean(fs.lstatSync(userPath, { throwIfNoEntry: false })); }
|
|
38
|
+
catch { return { config: {}, configPath: userPath, configError: 'unreadable', configFileExists: true, devConfigPath }; }
|
|
39
|
+
const configPath = configFileExists ? userPath : fs.existsSync(devConfigPath) ? devConfigPath : null;
|
|
36
40
|
let config = {};
|
|
37
41
|
let configError = null;
|
|
38
42
|
if (configPath) {
|
|
39
43
|
try {
|
|
40
|
-
|
|
44
|
+
const options = { root: path.dirname(configPath), privateFile: configPath === userPath };
|
|
45
|
+
let contents;
|
|
46
|
+
try { contents = readLocalFile(configPath, options); }
|
|
47
|
+
catch (error) {
|
|
48
|
+
// Login and renewal replace config atomically. Revalidate once from scratch.
|
|
49
|
+
if (!error.localFileRace) throw error;
|
|
50
|
+
contents = readLocalFile(configPath, options);
|
|
51
|
+
}
|
|
52
|
+
config = JSON.parse(contents);
|
|
41
53
|
if (!config || typeof config !== 'object' || Array.isArray(config)) throw new Error();
|
|
42
54
|
} catch (err) { config = {}; configError = err instanceof SyntaxError ? 'parse' : 'unreadable'; }
|
|
43
55
|
}
|
|
44
56
|
if (config.auth && !validAuthPointer(config.auth)) configError = 'format';
|
|
45
|
-
return { config, configPath, configError, configFileExists
|
|
57
|
+
return { config, configPath, configError, configFileExists, devConfigPath };
|
|
46
58
|
}
|
|
47
59
|
export function resolveCredential({ env = process.env, explicitKey, snapshot = readAuthConfig(env) } = {}) {
|
|
48
60
|
if (explicitKey !== undefined) return explicitKey === null ? { kind: 'anonymous', source: null } : { kind: 'api-key', source: 'explicit', apiKey: explicitKey };
|
package/src/auth-state.js
CHANGED
|
@@ -5,6 +5,7 @@ import { setTimeout as delay } from 'node:timers/promises';
|
|
|
5
5
|
import { AuthError, authDirectory, validAuthPointer } from './auth-credentials.js';
|
|
6
6
|
import { createAuthStore } from './auth-store.js';
|
|
7
7
|
import { refreshSession, retireSession, validateSession } from './auth-device.js';
|
|
8
|
+
import { openLocalFile, readLocalFile } from './local-file.js';
|
|
8
9
|
|
|
9
10
|
const queues = new Map();
|
|
10
11
|
const MAX_RETRYABLE_RENEWALS = 5;
|
|
@@ -16,8 +17,8 @@ const journalExists = file => {
|
|
|
16
17
|
};
|
|
17
18
|
const stateError = () => new AuthError('AUTH_STATE_INVALID', 'Saved authentication cannot be read safely. Repair config.json permissions or restore the file; no other credential was selected.');
|
|
18
19
|
function safePath(file, directory = false) {
|
|
19
|
-
|
|
20
|
-
|
|
20
|
+
const stat = fs.lstatSync(file, { throwIfNoEntry: false });
|
|
21
|
+
if (!stat) return;
|
|
21
22
|
if (stat.isSymbolicLink() || (directory ? !stat.isDirectory() : !stat.isFile()) ||
|
|
22
23
|
(process.platform !== 'win32' && ((stat.mode & 0o022) || stat.uid !== process.getuid()))) throw stateError();
|
|
23
24
|
}
|
|
@@ -25,8 +26,7 @@ const uuid = value => typeof value === 'string' && /^[a-f0-9-]{36}$/.test(value)
|
|
|
25
26
|
function readJournal(file, id) {
|
|
26
27
|
try {
|
|
27
28
|
safePath(file);
|
|
28
|
-
|
|
29
|
-
const value = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
29
|
+
const value = JSON.parse(readLocalFile(file, { root: path.dirname(path.dirname(file)), privateFile: true, maxBytes: 4096 }));
|
|
30
30
|
if (value?.id !== id) throw journalError();
|
|
31
31
|
if (value.kind === 'rotation') {
|
|
32
32
|
if (value.version !== 2 || value.id !== value.selectionEpoch || !uuid(value.selectionEpoch) ||
|
|
@@ -96,7 +96,7 @@ export function createAuthState({ directory = authDirectory(), store = createAut
|
|
|
96
96
|
safePath(configFile);
|
|
97
97
|
if (!fs.existsSync(configFile)) return {};
|
|
98
98
|
try {
|
|
99
|
-
const value = JSON.parse(
|
|
99
|
+
const value = JSON.parse(readLocalFile(configFile, { root: directory, privateFile: true }));
|
|
100
100
|
if (!value || typeof value !== 'object' || Array.isArray(value) || (value.auth && !validAuthPointer(value.auth))) throw new Error();
|
|
101
101
|
return value;
|
|
102
102
|
} catch { throw stateError(); }
|
|
@@ -129,7 +129,9 @@ export function createAuthState({ directory = authDirectory(), store = createAut
|
|
|
129
129
|
const native = await locks();
|
|
130
130
|
signal?.throwIfAborted();
|
|
131
131
|
safePath(file);
|
|
132
|
-
|
|
132
|
+
let fd;
|
|
133
|
+
try { fd = openLocalFile(file, { root: directory, flags: fs.constants.O_RDWR | fs.constants.O_CREAT | fs.constants.O_APPEND, privateFile: true }); }
|
|
134
|
+
catch { throw stateError(); }
|
|
133
135
|
|
|
134
136
|
try {
|
|
135
137
|
while (!native.tryLock(fd)) {
|
package/src/auth-store-worker.js
CHANGED
|
@@ -4,6 +4,7 @@ import fs from 'node:fs';
|
|
|
4
4
|
import path from 'node:path';
|
|
5
5
|
import { Worker } from 'node:worker_threads';
|
|
6
6
|
import locks from 'fs-native-extensions';
|
|
7
|
+
import { openLocalFile } from './local-file.js';
|
|
7
8
|
|
|
8
9
|
const stop = () => process.kill(process.pid, 'SIGKILL');
|
|
9
10
|
const timer = setTimeout(stop, 10000);
|
|
@@ -13,8 +14,8 @@ process.stdout.on('error', stop);
|
|
|
13
14
|
let input = '', phase = 'guard';
|
|
14
15
|
let fd;
|
|
15
16
|
function safe(file, directory = false) {
|
|
16
|
-
|
|
17
|
-
|
|
17
|
+
const stat = fs.lstatSync(file, { throwIfNoEntry: false });
|
|
18
|
+
if (!stat) return;
|
|
18
19
|
if (stat.isSymbolicLink() || (directory ? !stat.isDirectory() : !stat.isFile()) ||
|
|
19
20
|
(process.platform !== 'win32' && ((stat.mode & 0o022) || stat.uid !== process.getuid()))) throw new Error();
|
|
20
21
|
}
|
|
@@ -27,7 +28,7 @@ function receive(line) {
|
|
|
27
28
|
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
28
29
|
const file = path.join(directory, 'auth-store.lock');
|
|
29
30
|
safe(file);
|
|
30
|
-
fd =
|
|
31
|
+
fd = openLocalFile(file, { root: directory, flags: fs.constants.O_RDWR | fs.constants.O_CREAT | fs.constants.O_APPEND, privateFile: true });
|
|
31
32
|
// Independent acquisition: no cross-platform inherited-lock assumptions.
|
|
32
33
|
// This stable inode is never unlinked, including by recovery.
|
|
33
34
|
if (!locks.tryLock(fd)) throw new Error();
|
package/src/bridge.js
CHANGED
|
@@ -9,11 +9,13 @@
|
|
|
9
9
|
import * as crypto from 'node:crypto';
|
|
10
10
|
import * as fs from 'node:fs';
|
|
11
11
|
import * as path from 'node:path';
|
|
12
|
+
import { readLocalFile, writeLocalFile } from './local-file.js';
|
|
12
13
|
|
|
13
14
|
import { CommandError, validateAddress } from './api.js';
|
|
14
15
|
import { signSecp256k1 } from './crypto.js';
|
|
15
16
|
import {
|
|
16
17
|
assertEvmFeeWithinCap,
|
|
18
|
+
claimQuoteForExecution,
|
|
17
19
|
convertToBaseUnits,
|
|
18
20
|
evmRpcCall,
|
|
19
21
|
getEvmNonce,
|
|
@@ -242,11 +244,19 @@ function saveBridgeQuote(response, originChain, destinationChain, walletProvider
|
|
|
242
244
|
}
|
|
243
245
|
|
|
244
246
|
export function loadBridgeQuote(quoteId) {
|
|
247
|
+
const claimedPath = safeQuotesPath(`${quoteId}.executing.json`);
|
|
248
|
+
if (claimedPath && fs.lstatSync(claimedPath, { throwIfNoEntry: false })) {
|
|
249
|
+
throw new Error(`Bridge quote "${quoteId}" is claimed by another execution. Funds may be in flight. Check "nansen bridge status" before requesting a new quote.`);
|
|
250
|
+
}
|
|
245
251
|
const filePath = safeQuotesPath(`${quoteId}.json`);
|
|
246
252
|
if (!filePath || !fs.existsSync(filePath)) {
|
|
247
253
|
throw new Error(`Bridge quote "${quoteId}" not found. Quotes expire after 1 hour.`);
|
|
248
254
|
}
|
|
249
|
-
|
|
255
|
+
return readBridgeQuoteFile(filePath, quoteId);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function readBridgeQuoteFile(filePath, quoteId) {
|
|
259
|
+
const data = JSON.parse(readLocalFile(filePath, { root: path.dirname(getQuotesDir()) }));
|
|
250
260
|
if (Date.now() - data.timestamp > QUOTE_TTL_MS) {
|
|
251
261
|
fs.unlinkSync(filePath);
|
|
252
262
|
throw new Error('Bridge quote has expired. Please request a new quote.');
|
|
@@ -289,10 +299,15 @@ export function loadBridgeQuote(quoteId) {
|
|
|
289
299
|
// later step throwing must not leave the quote reusable. The step counters make
|
|
290
300
|
// a partial failure legible to the operator (see loadBridgeQuote).
|
|
291
301
|
export function markBridgeQuoteExecuted(quoteId, progress = {}) {
|
|
292
|
-
const
|
|
293
|
-
|
|
302
|
+
const claimedPath = safeQuotesPath(`${quoteId}.executing.json`);
|
|
303
|
+
const filePath = claimedPath && fs.lstatSync(claimedPath, { throwIfNoEntry: false })
|
|
304
|
+
? claimedPath : safeQuotesPath(`${quoteId}.json`);
|
|
294
305
|
try {
|
|
295
|
-
|
|
306
|
+
if (!filePath || !fs.existsSync(filePath)) {
|
|
307
|
+
if (progress.required) throw new Error('Missing execution state');
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
const data = JSON.parse(readLocalFile(filePath, { root: path.dirname(getQuotesDir()) }));
|
|
296
311
|
data.executedAt = data.executedAt || Date.now();
|
|
297
312
|
if (progress.broadcast) {
|
|
298
313
|
data.broadcasts = [...(data.broadcasts || []), { ...progress.broadcast, at: Date.now() }];
|
|
@@ -301,11 +316,9 @@ export function markBridgeQuoteExecuted(quoteId, progress = {}) {
|
|
|
301
316
|
data.broadcastSteps = Math.max(data.broadcastSteps || 0, progress.broadcastSteps);
|
|
302
317
|
}
|
|
303
318
|
if (progress.totalSteps !== undefined) data.totalSteps = progress.totalSteps;
|
|
304
|
-
|
|
319
|
+
writeLocalFile(filePath, JSON.stringify(data, null, 2), { root: path.dirname(getQuotesDir()) });
|
|
305
320
|
} catch {
|
|
306
|
-
|
|
307
|
-
// will still proceed, but that's preferable to crashing after a successful
|
|
308
|
-
// broadcast.
|
|
321
|
+
throw new CommandError('Could not safely record bridge execution. Funds may already be in flight. The quote remains claimed; check "nansen bridge status" before requesting a new quote.', 'QUOTE_STATE_UNSAFE');
|
|
309
322
|
}
|
|
310
323
|
}
|
|
311
324
|
|
|
@@ -2043,90 +2056,105 @@ from a quote are the same ones that got stuck. Check the stuck nonce with
|
|
|
2043
2056
|
preflightResult ??= await preflightPlan();
|
|
2044
2057
|
const { evmIntent, hlIntent } = preflightResult;
|
|
2045
2058
|
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
markBridgeQuoteExecuted(quoteId, {
|
|
2053
|
-
broadcast: { step: stepId, txHash: txHash || null },
|
|
2054
|
-
totalSteps: steps.length,
|
|
2055
|
-
});
|
|
2056
|
-
|
|
2057
|
-
// Step-level counter, recorded only once a step fully completes.
|
|
2058
|
-
const markBroadcast = (index) =>
|
|
2059
|
-
markBridgeQuoteExecuted(quoteId, {
|
|
2060
|
-
broadcastSteps: index + 1,
|
|
2061
|
-
totalSteps: steps.length,
|
|
2062
|
-
});
|
|
2063
|
-
|
|
2064
|
-
if (execution_type === 'evm_transaction') {
|
|
2065
|
-
// Overrides move real money differently from what was quoted, so say so
|
|
2066
|
-
// rather than letting them apply silently.
|
|
2067
|
-
if (overridesSummary) {
|
|
2068
|
-
log(` Overrides: ${overridesSummary}`);
|
|
2059
|
+
const claim = claimQuoteForExecution(quoteId, readBridgeQuoteFile);
|
|
2060
|
+
let handedOff = false;
|
|
2061
|
+
let keepClaimed = false;
|
|
2062
|
+
try {
|
|
2063
|
+
if (JSON.stringify(claim.quote) !== JSON.stringify(quoteData)) {
|
|
2064
|
+
throw new CommandError('Bridge quote changed while awaiting execution. Request a fresh quote.', 'QUOTE_STATE_UNSAFE');
|
|
2069
2065
|
}
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2066
|
+
// Consume the quote at each INDIVIDUAL broadcast, before any receipt wait.
|
|
2067
|
+
// A tx can be accepted by the network and then have waitForReceipt time
|
|
2068
|
+
// out; if the quote were still unspent, a retry would re-sign and re-send
|
|
2069
|
+
// it with a fresh nonce. markBridgeQuoteExecuted pins executedAt on the
|
|
2070
|
+
// first call, so the quote is spent the instant anything is in flight.
|
|
2071
|
+
const onBroadcast = (stepId, txHash) => {
|
|
2072
|
+
handedOff = true;
|
|
2073
|
+
markBridgeQuoteExecuted(quoteId, {
|
|
2074
|
+
required: true,
|
|
2075
|
+
broadcast: { step: stepId, txHash: txHash || null },
|
|
2076
|
+
totalSteps: steps.length,
|
|
2080
2077
|
});
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
intent: hlIntent,
|
|
2097
|
-
});
|
|
2098
|
-
markBroadcast(index);
|
|
2078
|
+
};
|
|
2079
|
+
|
|
2080
|
+
// Step-level counter, recorded only once a step fully completes.
|
|
2081
|
+
const markBroadcast = (index) =>
|
|
2082
|
+
markBridgeQuoteExecuted(quoteId, {
|
|
2083
|
+
required: true,
|
|
2084
|
+
broadcastSteps: index + 1,
|
|
2085
|
+
totalSteps: steps.length,
|
|
2086
|
+
});
|
|
2087
|
+
|
|
2088
|
+
if (execution_type === 'evm_transaction') {
|
|
2089
|
+
// Overrides move real money differently from what was quoted, so say so
|
|
2090
|
+
// rather than letting them apply silently.
|
|
2091
|
+
if (overridesSummary) {
|
|
2092
|
+
log(` Overrides: ${overridesSummary}`);
|
|
2099
2093
|
}
|
|
2100
|
-
} else {
|
|
2101
2094
|
for (const [index, step] of steps.entries()) {
|
|
2102
|
-
await
|
|
2095
|
+
await processEvmStep(step, {
|
|
2096
|
+
chain: quoteData.originChain,
|
|
2103
2097
|
privateKeyHex: creds.privateKey,
|
|
2098
|
+
signerAddress: signer.address,
|
|
2104
2099
|
log,
|
|
2105
|
-
apiInstance,
|
|
2106
2100
|
onBroadcast,
|
|
2107
|
-
|
|
2101
|
+
feeOverrides,
|
|
2102
|
+
nonceSequence,
|
|
2103
|
+
intent: evmIntent,
|
|
2108
2104
|
});
|
|
2109
2105
|
markBroadcast(index);
|
|
2110
2106
|
}
|
|
2107
|
+
} else if (execution_type === 'hyperliquid_signature') {
|
|
2108
|
+
if (creds.provider === 'privy') {
|
|
2109
|
+
const { PrivyClient } = await import('./privy.js');
|
|
2110
|
+
const privyClient = new PrivyClient(process.env.PRIVY_APP_ID, process.env.PRIVY_APP_SECRET);
|
|
2111
|
+
for (const [index, step] of steps.entries()) {
|
|
2112
|
+
await processSignatureStepPrivy(step, {
|
|
2113
|
+
privyClient,
|
|
2114
|
+
// `signer` above — the same resolution that was screened and
|
|
2115
|
+
// matched against the quote, rather than resolving a second time.
|
|
2116
|
+
walletId: signer.privyWalletIds?.evm,
|
|
2117
|
+
log,
|
|
2118
|
+
apiInstance,
|
|
2119
|
+
onBroadcast,
|
|
2120
|
+
intent: hlIntent,
|
|
2121
|
+
});
|
|
2122
|
+
markBroadcast(index);
|
|
2123
|
+
}
|
|
2124
|
+
} else {
|
|
2125
|
+
for (const [index, step] of steps.entries()) {
|
|
2126
|
+
await processSignatureStepLocal(step, {
|
|
2127
|
+
privateKeyHex: creds.privateKey,
|
|
2128
|
+
log,
|
|
2129
|
+
apiInstance,
|
|
2130
|
+
onBroadcast,
|
|
2131
|
+
intent: hlIntent,
|
|
2132
|
+
});
|
|
2133
|
+
markBroadcast(index);
|
|
2134
|
+
}
|
|
2135
|
+
}
|
|
2136
|
+
} else {
|
|
2137
|
+
throw new Error(`Unknown execution type: ${execution_type}`);
|
|
2111
2138
|
}
|
|
2112
|
-
} else {
|
|
2113
|
-
throw new Error(`Unknown execution type: ${execution_type}`);
|
|
2114
|
-
}
|
|
2115
2139
|
|
|
2116
|
-
|
|
2117
|
-
|
|
2140
|
+
// Every step is out; the marker above already consumed the quote.
|
|
2141
|
+
markBridgeQuoteExecuted(quoteId, { required: true, broadcastSteps: steps.length, totalSteps: steps.length });
|
|
2118
2142
|
|
|
2119
|
-
|
|
2120
|
-
|
|
2143
|
+
log(`\n Bridge submitted. Polling for completion...`);
|
|
2144
|
+
const status = await pollBridgeCompletion(apiInstance, { requestId: request_id, log });
|
|
2121
2145
|
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
|
|
2125
|
-
|
|
2146
|
+
if (status.status === 'success') {
|
|
2147
|
+
log(`\n Bridge completed!`);
|
|
2148
|
+
if (status.destination_tx_hashes?.length) {
|
|
2149
|
+
log(` Destination tx: ${status.destination_tx_hashes[0]}`);
|
|
2150
|
+
}
|
|
2126
2151
|
}
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
|
|
2152
|
+
log('');
|
|
2153
|
+
return undefined;
|
|
2154
|
+
} catch (error) {
|
|
2155
|
+
keepClaimed = handedOff && error.code === 'QUOTE_STATE_UNSAFE';
|
|
2156
|
+
throw error;
|
|
2157
|
+
} finally { claim.release({ handedOff, keepClaimed }); }
|
|
2130
2158
|
},
|
|
2131
2159
|
|
|
2132
2160
|
'status': async (args, apiInstance, flags, options) => {
|
package/src/cache-inspect.js
CHANGED
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
|
|
22
22
|
import fs from 'fs';
|
|
23
23
|
import path from 'path';
|
|
24
|
+
import { openLocalFile } from './local-file.js';
|
|
24
25
|
|
|
25
26
|
import { getCacheDir, getConfigDir, DEFAULT_CACHE_TTL, NansenError, ErrorCode } from './api.js';
|
|
26
27
|
import { getCostMapFile, COST_MAP_TTL_MS } from './cost-cache.js';
|
|
@@ -86,15 +87,10 @@ function readTimestamp(file, field) {
|
|
|
86
87
|
let fd;
|
|
87
88
|
let raw;
|
|
88
89
|
try {
|
|
89
|
-
|
|
90
|
-
// Windows does not define it. There, only the earlier lstat check applies;
|
|
91
|
-
// opening with O_RDONLY does not prevent this race.
|
|
92
|
-
const flags = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0);
|
|
93
|
-
fd = fs.openSync(file, flags);
|
|
94
|
-
if (!fs.fstatSync(fd).isFile()) return { raced: true };
|
|
90
|
+
fd = openLocalFile(file, { root: getConfigDir() });
|
|
95
91
|
raw = fs.readFileSync(fd, 'utf8');
|
|
96
92
|
} catch (error) {
|
|
97
|
-
if (error?.code === 'ENOENT' || error?.code === 'ELOOP') return { raced: true };
|
|
93
|
+
if (error?.code === 'ENOENT' || error?.code === 'ELOOP' || error?.code === 'LOCAL_FILE_UNSAFE') return { raced: true };
|
|
98
94
|
throw fsError('read', file, error);
|
|
99
95
|
} finally {
|
|
100
96
|
if (fd !== undefined) fs.closeSync(fd);
|
package/src/doctor.js
CHANGED
|
@@ -251,7 +251,7 @@ export function runDoctorChecks(deps = {}) {
|
|
|
251
251
|
const auth = resolveAuthConfig(env, devConfigPath);
|
|
252
252
|
|
|
253
253
|
// --- environment ---
|
|
254
|
-
const requiredMajor = parseEngineMajor(engines?.node) ??
|
|
254
|
+
const requiredMajor = parseEngineMajor(engines?.node) ?? 22;
|
|
255
255
|
const currentMajor = parseInt(nodeVersion.replace(/^v/, ''), 10);
|
|
256
256
|
checks.push(currentMajor >= requiredMajor
|
|
257
257
|
? check('node-version', 'ok', `Node ${nodeVersion} (>= ${requiredMajor} required)`)
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
|
|
4
|
+
const unsafe = (file, reason) => Object.assign(new Error(`Refusing an unsafe local file at ${file}: ${reason}. Repair that path before retrying.`), { code: 'LOCAL_FILE_UNSAFE' });
|
|
5
|
+
const sameFile = (a, b) => a.dev === b.dev && a.ino === b.ino;
|
|
6
|
+
function checkStat(stat, directory, privateFile, file) {
|
|
7
|
+
if (!stat || (directory ? !stat.isDirectory() : !stat.isFile())) throw unsafe(file, directory ? 'expected a directory without symlinks' : 'expected a regular file without symlinks');
|
|
8
|
+
if (!directory && stat.nlink !== 1) throw unsafe(file, 'file has unexpected hard links');
|
|
9
|
+
if (privateFile && process.platform !== 'win32') {
|
|
10
|
+
if (stat.mode & 0o022) throw unsafe(file, 'authentication path is writable by group or other users');
|
|
11
|
+
if (stat.uid !== process.getuid()) throw unsafe(file, 'authentication path belongs to another user');
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Non-private stores may use an intentionally symlinked storage root.
|
|
16
|
+
// Authentication and all components below either root must be link-free.
|
|
17
|
+
// Descriptor checks reject replacements before any bytes are read or written.
|
|
18
|
+
export function openLocalFile(file, { root, flags = fs.constants.O_RDONLY, mode = 0o600, privateFile = false, maxBytes = Infinity } = {}) {
|
|
19
|
+
const base = path.resolve(root);
|
|
20
|
+
const target = path.resolve(file);
|
|
21
|
+
const relative = path.relative(base, target);
|
|
22
|
+
if (!relative || relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) throw unsafe(target, 'path is outside its storage root');
|
|
23
|
+
const directories = [base];
|
|
24
|
+
for (const part of relative.split(path.sep).slice(0, -1)) directories.push(path.join(directories.at(-1), part));
|
|
25
|
+
const directoryStat = (dir, i) => i === 0 && !privateFile ? fs.statSync(dir) : fs.lstatSync(dir);
|
|
26
|
+
const parents = directories.map((dir, i) => {
|
|
27
|
+
const stat = directoryStat(dir, i);
|
|
28
|
+
checkStat(stat, true, privateFile, dir);
|
|
29
|
+
return stat;
|
|
30
|
+
});
|
|
31
|
+
const before = fs.lstatSync(target, { throwIfNoEntry: false });
|
|
32
|
+
if (before) checkStat(before, false, privateFile, target);
|
|
33
|
+
let fd;
|
|
34
|
+
try {
|
|
35
|
+
fd = fs.openSync(target, flags | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0), mode);
|
|
36
|
+
const opened = fs.fstatSync(fd);
|
|
37
|
+
checkStat(opened, false, privateFile, target);
|
|
38
|
+
if (opened.size > maxBytes) throw unsafe(target, `file exceeds its ${maxBytes}-byte limit`);
|
|
39
|
+
if (before && !sameFile(before, opened)) throw Object.assign(unsafe(target, 'file was replaced while opening'), { localFileRace: true });
|
|
40
|
+
const after = fs.lstatSync(target);
|
|
41
|
+
checkStat(after, false, privateFile, target);
|
|
42
|
+
if (!sameFile(opened, after)) throw Object.assign(unsafe(target, 'file was replaced while opening'), { localFileRace: true });
|
|
43
|
+
directories.forEach((dir, i) => {
|
|
44
|
+
const stat = directoryStat(dir, i);
|
|
45
|
+
checkStat(stat, true, privateFile, dir);
|
|
46
|
+
if (!sameFile(parents[i], stat)) throw unsafe(dir, 'directory was replaced while opening');
|
|
47
|
+
});
|
|
48
|
+
return fd;
|
|
49
|
+
} catch (error) {
|
|
50
|
+
if (fd !== undefined) fs.closeSync(fd);
|
|
51
|
+
if (error.code === 'ELOOP') throw unsafe(target, 'file became a symbolic link while opening');
|
|
52
|
+
throw error;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function readLocalFile(file, options) {
|
|
57
|
+
const fd = openLocalFile(file, options);
|
|
58
|
+
try { return fs.readFileSync(fd, 'utf8'); }
|
|
59
|
+
finally { fs.closeSync(fd); }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function writeLocalFile(file, contents, options) {
|
|
63
|
+
const fd = openLocalFile(file, { ...options, flags: fs.constants.O_WRONLY });
|
|
64
|
+
try {
|
|
65
|
+
const bytes = Buffer.from(contents, 'utf8');
|
|
66
|
+
fs.ftruncateSync(fd, 0);
|
|
67
|
+
let offset = 0;
|
|
68
|
+
while (offset < bytes.length) {
|
|
69
|
+
const written = fs.writeSync(fd, bytes, offset, bytes.length - offset, offset);
|
|
70
|
+
if (!written) throw new Error('Could not write the local file.');
|
|
71
|
+
offset += written;
|
|
72
|
+
}
|
|
73
|
+
fs.fsyncSync(fd);
|
|
74
|
+
} finally { fs.closeSync(fd); }
|
|
75
|
+
}
|
package/src/schema.json
CHANGED
|
@@ -2364,6 +2364,15 @@
|
|
|
2364
2364
|
},
|
|
2365
2365
|
"list": {
|
|
2366
2366
|
"description": "List all wallets",
|
|
2367
|
+
"returns": [
|
|
2368
|
+
"wallets[].name",
|
|
2369
|
+
"wallets[].provider",
|
|
2370
|
+
"wallets[].evm",
|
|
2371
|
+
"wallets[].solana",
|
|
2372
|
+
"wallets[].createdAt",
|
|
2373
|
+
"wallets[].isDefault",
|
|
2374
|
+
"defaultWallet"
|
|
2375
|
+
],
|
|
2367
2376
|
"examples": [
|
|
2368
2377
|
"nansen wallet list",
|
|
2369
2378
|
"nansen wallet list --pretty"
|
|
@@ -2376,6 +2385,16 @@
|
|
|
2376
2385
|
"description": "Wallet name"
|
|
2377
2386
|
}
|
|
2378
2387
|
},
|
|
2388
|
+
"returns": [
|
|
2389
|
+
"name",
|
|
2390
|
+
"provider",
|
|
2391
|
+
"evm",
|
|
2392
|
+
"solana",
|
|
2393
|
+
"createdAt",
|
|
2394
|
+
"isDefault",
|
|
2395
|
+
"privyWalletIds.evm",
|
|
2396
|
+
"privyWalletIds.solana"
|
|
2397
|
+
],
|
|
2379
2398
|
"examples": [
|
|
2380
2399
|
"nansen wallet show <name>"
|
|
2381
2400
|
]
|
|
@@ -2409,7 +2428,7 @@
|
|
|
2409
2428
|
]
|
|
2410
2429
|
},
|
|
2411
2430
|
"export": {
|
|
2412
|
-
"description": "Export private keys (redacted by default; pass --reveal or --file <path> for the actual keys)",
|
|
2431
|
+
"description": "Export private keys (redacted by default: returns the addresses as JSON with no keys; pass --reveal or --file <path> for the actual keys)",
|
|
2413
2432
|
"options": {
|
|
2414
2433
|
"reveal": {
|
|
2415
2434
|
"type": "boolean",
|
|
@@ -2420,6 +2439,12 @@
|
|
|
2420
2439
|
"description": "Write private keys to this path instead of stdout (created with 0600 permissions, refuses to overwrite)"
|
|
2421
2440
|
}
|
|
2422
2441
|
},
|
|
2442
|
+
"returns": [
|
|
2443
|
+
"name",
|
|
2444
|
+
"redacted",
|
|
2445
|
+
"evm.address",
|
|
2446
|
+
"solana.address"
|
|
2447
|
+
],
|
|
2423
2448
|
"examples": [
|
|
2424
2449
|
"nansen wallet export <name>",
|
|
2425
2450
|
"nansen wallet export <name> --file backup.json"
|
package/src/solana-tx.js
CHANGED
|
@@ -151,3 +151,77 @@ export function resolveStaticAccount(parsed, index) {
|
|
|
151
151
|
if (index < parsed.staticAccountKeys.length) return parsed.staticAccountKeys[index];
|
|
152
152
|
return null;
|
|
153
153
|
}
|
|
154
|
+
|
|
155
|
+
// Owner of every address-lookup-table account.
|
|
156
|
+
export const ADDRESS_LOOKUP_TABLE_PROGRAM = 'AddressLookupTab1e1111111111111111111111111';
|
|
157
|
+
// LookupTableMeta: typeIndex u32, deactivationSlot u64, lastExtendedSlot u64,
|
|
158
|
+
// lastExtendedSlotStartIndex u8, authority Option<Pubkey>, padding. The
|
|
159
|
+
// 32-byte addresses start right after it.
|
|
160
|
+
// The program always reserves all 56 bytes, even when authority is None.
|
|
161
|
+
const LOOKUP_TABLE_META_SIZE = 56;
|
|
162
|
+
const LOOKUP_TABLE_TYPE_INDEX = 1;
|
|
163
|
+
// Lookups index a table with a single byte.
|
|
164
|
+
const LOOKUP_TABLE_MAX_ADDRESSES = 256;
|
|
165
|
+
// A table that has never been deactivated stores u64::MAX here.
|
|
166
|
+
const LOOKUP_TABLE_ACTIVE_SLOT = 0xffffffffffffffffn;
|
|
167
|
+
// The SlotHashes sysvar: the recent slots a deactivating table stays usable for.
|
|
168
|
+
export const SLOT_HASHES_SYSVAR = 'SysvarS1otHashes111111111111111111111111111';
|
|
169
|
+
export const SYSVAR_PROGRAM = 'Sysvar1111111111111111111111111111111111111';
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Parse the raw data of an address-lookup-table account into its addresses and
|
|
173
|
+
* its deactivation slot (null when it has never been deactivated). Throws on
|
|
174
|
+
* anything that isn't an initialized table, so a truncated or foreign account
|
|
175
|
+
* can't be read as a short or shifted address list.
|
|
176
|
+
*/
|
|
177
|
+
export function parseAddressLookupTable(data) {
|
|
178
|
+
if (data.length < LOOKUP_TABLE_META_SIZE || (data.length - LOOKUP_TABLE_META_SIZE) % 32 !== 0) {
|
|
179
|
+
throw new Error('Malformed address lookup table: unexpected account data length');
|
|
180
|
+
}
|
|
181
|
+
if ((data.length - LOOKUP_TABLE_META_SIZE) / 32 > LOOKUP_TABLE_MAX_ADDRESSES) {
|
|
182
|
+
throw new Error(`Malformed address lookup table: more than ${LOOKUP_TABLE_MAX_ADDRESSES} addresses`);
|
|
183
|
+
}
|
|
184
|
+
if (data.readUInt32LE(0) !== LOOKUP_TABLE_TYPE_INDEX) {
|
|
185
|
+
throw new Error('Malformed address lookup table: account is not an initialized lookup table');
|
|
186
|
+
}
|
|
187
|
+
const addresses = [];
|
|
188
|
+
for (let offset = LOOKUP_TABLE_META_SIZE; offset < data.length; offset += 32) {
|
|
189
|
+
addresses.push(base58Encode(data.subarray(offset, offset + 32)));
|
|
190
|
+
}
|
|
191
|
+
const deactivationSlot = data.readBigUInt64LE(4);
|
|
192
|
+
return {
|
|
193
|
+
deactivationSlot: deactivationSlot === LOOKUP_TABLE_ACTIVE_SLOT ? null : deactivationSlot,
|
|
194
|
+
addresses,
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Parse the SlotHashes sysvar (u64 count, then count × (u64 slot, 32-byte
|
|
200
|
+
* hash)) into its slots.
|
|
201
|
+
*/
|
|
202
|
+
export function parseSlotHashes(data) {
|
|
203
|
+
if (data.length < 8) throw new Error('Malformed SlotHashes sysvar: unexpected account data length');
|
|
204
|
+
const count = data.readBigUInt64LE(0);
|
|
205
|
+
if (8n + count * 40n > BigInt(data.length)) {
|
|
206
|
+
throw new Error('Malformed SlotHashes sysvar: unexpected account data length');
|
|
207
|
+
}
|
|
208
|
+
const slots = [];
|
|
209
|
+
for (let i = 0; i < Number(count); i++) slots.push(data.readBigUInt64LE(8 + i * 40));
|
|
210
|
+
return slots;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Whether the runtime still resolves addresses through a table, mirroring its
|
|
215
|
+
* LookupTableMeta status rule. Deactivating a table doesn't disable it at
|
|
216
|
+
* once: it stays usable while its deactivation slot is the current slot or is
|
|
217
|
+
* still in SlotHashes, and only then becomes deactivated.
|
|
218
|
+
*
|
|
219
|
+
* A deactivation slot past `currentSlot` also counts as usable. Our two RPC
|
|
220
|
+
* reads can come from nodes at different heights, and a slot we haven't seen
|
|
221
|
+
* yet can't have left SlotHashes.
|
|
222
|
+
*/
|
|
223
|
+
export function isLookupTableUsable(deactivationSlot, currentSlot, slotHashes) {
|
|
224
|
+
if (deactivationSlot === null) return true;
|
|
225
|
+
if (deactivationSlot >= currentSlot) return true;
|
|
226
|
+
return slotHashes.includes(deactivationSlot);
|
|
227
|
+
}
|
package/src/trading.js
CHANGED
|
@@ -9,9 +9,10 @@ import { rejectBlankOption } from './query-options.js';
|
|
|
9
9
|
import crypto from 'crypto';
|
|
10
10
|
import fs from 'fs';
|
|
11
11
|
import path from 'path';
|
|
12
|
+
import { readLocalFile, writeLocalFile } from './local-file.js';
|
|
12
13
|
import { base58Encode, exportWallet, getWalletConfig, showWallet, listWallets } from './wallet.js';
|
|
13
14
|
import { base58Decode, encodeCompactU16 } from './transfer.js';
|
|
14
|
-
import { buildMessageV0, fetchRecentBlockhash } from './x402-svm.js';
|
|
15
|
+
import { buildMessageV0, fetchAddressLookupTables, fetchRecentBlockhash } from './x402-svm.js';
|
|
15
16
|
import { keccak256, signSecp256k1, rlpEncode } from './crypto.js';
|
|
16
17
|
import { getWalletConnectAddress, sendTransactionViaWalletConnect, sendSolanaTransactionViaWalletConnect, sendApprovalViaWalletConnect } from './walletconnect-trading.js';
|
|
17
18
|
import { retrievePassword } from './keychain.js';
|
|
@@ -37,6 +38,13 @@ const CHAIN_MAP = {
|
|
|
37
38
|
base: { index: '8453', type: 'evm', chainId: 8453, name: 'Base', explorer: 'https://basescan.org/tx/', lifiChainId: '8453' },
|
|
38
39
|
};
|
|
39
40
|
|
|
41
|
+
// CHAIN_MAP is keyed lowercase, but a quote stores the chain exactly as the
|
|
42
|
+
// user typed it (`--chain Base`) — only resolveChain() lowercases on the way
|
|
43
|
+
// through, and direct lookups bypass it.
|
|
44
|
+
function chainConfigFor(name) {
|
|
45
|
+
return name ? CHAIN_MAP[String(name).toLowerCase()] : undefined;
|
|
46
|
+
}
|
|
47
|
+
|
|
40
48
|
// Extend when adding new EVM chains (e.g. arbitrum WETH, polygon WMATIC)
|
|
41
49
|
const WRAPPED_NATIVE_TOKENS = {
|
|
42
50
|
base: { address: '0x4200000000000000000000000000000000000006', symbol: 'WETH', nativeSymbol: 'ETH' },
|
|
@@ -135,11 +143,8 @@ export function getQuotesDir() {
|
|
|
135
143
|
|
|
136
144
|
// Resolve a filename inside the quotes dir, rejecting path traversal.
|
|
137
145
|
export function safeQuotesPath(filename) {
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
const relative = path.relative(base, target);
|
|
141
|
-
if (relative.startsWith('..') || path.isAbsolute(relative)) return null;
|
|
142
|
-
return target;
|
|
146
|
+
if (typeof filename !== 'string' || !filename || filename === '.' || filename === '..' || /[/\\:]/.test(filename) || filename.includes('\0')) return null;
|
|
147
|
+
return path.join(path.resolve(getQuotesDir()), filename);
|
|
143
148
|
}
|
|
144
149
|
|
|
145
150
|
// ============= Trading API Client =============
|
|
@@ -272,7 +277,7 @@ export async function executeTransaction(params, { retries = 2, retryDelayMs = 1
|
|
|
272
277
|
// JSON error (e.g. { code: "UPSTREAM_TIMEOUT" }) already explains itself
|
|
273
278
|
// via `details`; tacking "you may be out of SOL" onto a gateway timeout
|
|
274
279
|
// would misdirect the user.
|
|
275
|
-
const chainType = params.chain
|
|
280
|
+
const chainType = chainConfigFor(params.chain)?.type;
|
|
276
281
|
const feeHint = !parsed
|
|
277
282
|
? chainType === 'solana'
|
|
278
283
|
? ' This often means the transaction failed simulation — check that you have enough SOL for fees (~0.005 SOL minimum).'
|
|
@@ -457,7 +462,7 @@ export function loadTxRecord(txHash) {
|
|
|
457
462
|
if (!filePath) return null;
|
|
458
463
|
if (!fs.existsSync(filePath)) return null;
|
|
459
464
|
try {
|
|
460
|
-
const data = JSON.parse(
|
|
465
|
+
const data = JSON.parse(readLocalFile(filePath, { root: path.dirname(getQuotesDir()) }));
|
|
461
466
|
if (Date.now() - data.timestamp > TX_RECORD_TTL_MS) {
|
|
462
467
|
fs.unlinkSync(filePath);
|
|
463
468
|
return null;
|
|
@@ -516,7 +521,7 @@ export function loadQuote(quoteId) {
|
|
|
516
521
|
}
|
|
517
522
|
|
|
518
523
|
function readQuoteFile(filePath, quoteId) {
|
|
519
|
-
const data = JSON.parse(
|
|
524
|
+
const data = JSON.parse(readLocalFile(filePath, { root: path.dirname(getQuotesDir()) }));
|
|
520
525
|
if (Date.now() - data.timestamp > 3600000) {
|
|
521
526
|
fs.unlinkSync(filePath);
|
|
522
527
|
throw new Error('Quote has expired. Please request a new quote.');
|
|
@@ -543,7 +548,7 @@ function readQuoteFile(filePath, quoteId) {
|
|
|
543
548
|
|
|
544
549
|
function quoteClaimedError(quoteId, claimedPath) {
|
|
545
550
|
return new Error(
|
|
546
|
-
`Quote "${quoteId}" is claimed by another execution (${claimedPath}). If that run is still going, wait for it to finish. If it was interrupted, a
|
|
551
|
+
`Quote "${quoteId}" is claimed by another execution (${claimedPath}). If that run is still going, wait for it to finish. If it was interrupted, a transaction may or may not have been broadcast: check the wallet on the explorer, then request a new quote with the matching quote command. The claimed quote is removed when it expires.`,
|
|
547
552
|
);
|
|
548
553
|
}
|
|
549
554
|
|
|
@@ -574,12 +579,14 @@ function quoteClaimedError(quoteId, claimedPath) {
|
|
|
574
579
|
* after its 1-hour lifetime.
|
|
575
580
|
*
|
|
576
581
|
* @param {string} quoteId
|
|
577
|
-
* @
|
|
582
|
+
* @param {function} [readQuote] Validates the claimed quote, including its type.
|
|
583
|
+
* @returns {{ quote: object, release: (opts?: { handedOff?: boolean, keepClaimed?: boolean }) => void }}
|
|
578
584
|
*/
|
|
579
|
-
export function claimQuoteForExecution(quoteId) {
|
|
585
|
+
export function claimQuoteForExecution(quoteId, readQuote = readQuoteFile) {
|
|
580
586
|
const quotePath = safeQuotesPath(`${quoteId}.json`);
|
|
581
587
|
const claimedPath = safeQuotesPath(`${quoteId}.executing.json`);
|
|
582
588
|
if (!quotePath || !claimedPath) throw new Error(`Invalid quote id "${quoteId}".`);
|
|
589
|
+
if (fs.lstatSync(claimedPath, { throwIfNoEntry: false })) throw quoteClaimedError(quoteId, claimedPath);
|
|
583
590
|
|
|
584
591
|
try {
|
|
585
592
|
fs.renameSync(quotePath, claimedPath);
|
|
@@ -592,19 +599,24 @@ export function claimQuoteForExecution(quoteId) {
|
|
|
592
599
|
}
|
|
593
600
|
|
|
594
601
|
let released = false;
|
|
595
|
-
const release = ({ handedOff = false } = {}) => {
|
|
602
|
+
const release = ({ handedOff = false, keepClaimed = false } = {}) => {
|
|
596
603
|
if (released) return;
|
|
597
604
|
released = true;
|
|
605
|
+
if (keepClaimed) return;
|
|
598
606
|
try {
|
|
599
|
-
if (handedOff && !JSON.parse(
|
|
607
|
+
if (handedOff && !JSON.parse(readLocalFile(claimedPath, { root: path.dirname(getQuotesDir()) })).executedAt) return;
|
|
600
608
|
fs.renameSync(claimedPath, quotePath);
|
|
601
609
|
} catch { /* gone (expired and cleaned up): nothing to release */ }
|
|
602
610
|
};
|
|
603
611
|
|
|
604
612
|
try {
|
|
605
|
-
|
|
613
|
+
if (process.platform !== 'win32') {
|
|
614
|
+
const fd = fs.openSync(path.dirname(claimedPath), 'r');
|
|
615
|
+
try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
|
|
616
|
+
}
|
|
617
|
+
return { quote: readQuote(claimedPath, quoteId), release };
|
|
606
618
|
} catch (err) {
|
|
607
|
-
//
|
|
619
|
+
// Invalid, already executed, or expired: nothing is signed, so
|
|
608
620
|
// put back whatever is still there.
|
|
609
621
|
release();
|
|
610
622
|
throw err;
|
|
@@ -624,16 +636,15 @@ export function markQuoteExecuted(quoteId, progress = {}) {
|
|
|
624
636
|
: safeQuotesPath(`${quoteId}.json`);
|
|
625
637
|
if (!filePath || !fs.existsSync(filePath)) return;
|
|
626
638
|
try {
|
|
627
|
-
const data = JSON.parse(
|
|
639
|
+
const data = JSON.parse(readLocalFile(filePath, { root: path.dirname(getQuotesDir()) }));
|
|
628
640
|
data.executedAt = data.executedAt || Date.now();
|
|
629
641
|
if (progress.broadcast) {
|
|
630
642
|
data.broadcasts = [...(data.broadcasts || []), { ...progress.broadcast, at: Date.now() }];
|
|
631
643
|
}
|
|
632
|
-
|
|
644
|
+
writeLocalFile(filePath, JSON.stringify(data, null, 2), { root: path.dirname(getQuotesDir()) });
|
|
633
645
|
} catch {
|
|
634
|
-
//
|
|
635
|
-
//
|
|
636
|
-
// broadcast.
|
|
646
|
+
// The execution claim stays in place without a readable marker, so a
|
|
647
|
+
// later execution cannot sign again after an uncertain broadcast.
|
|
637
648
|
}
|
|
638
649
|
}
|
|
639
650
|
|
|
@@ -650,7 +661,7 @@ export function cleanupQuotes() {
|
|
|
650
661
|
if (!file.endsWith('.json')) continue;
|
|
651
662
|
const ttl = file.startsWith('tx-') ? TX_RECORD_TTL_MS : 3600000;
|
|
652
663
|
try {
|
|
653
|
-
const data = JSON.parse(
|
|
664
|
+
const data = JSON.parse(readLocalFile(path.join(dir, file), { root: path.dirname(dir) }));
|
|
654
665
|
if (now - data.timestamp > ttl) fs.unlinkSync(path.join(dir, file));
|
|
655
666
|
} catch { /* ignore */ }
|
|
656
667
|
}
|
|
@@ -749,10 +760,13 @@ function decodeInstructionData(hex) {
|
|
|
749
760
|
* — into a signable base64 VersionedTransaction. Some aggregators (Relay's Solana-source
|
|
750
761
|
* bridge quotes) return this shape instead of a ready-to-sign serialized transaction.
|
|
751
762
|
*
|
|
752
|
-
*
|
|
753
|
-
*
|
|
754
|
-
*
|
|
755
|
-
*
|
|
763
|
+
* Accounts stay static whenever the transaction fits Solana's packet limit that way, so
|
|
764
|
+
* the common case needs no extra RPC call and the safety checks see every account. Only
|
|
765
|
+
* a route too large to fit (e.g. a source-chain swap ahead of the bridge deposit) has its
|
|
766
|
+
* addressLookupTableAddresses fetched and used to compress accounts. A table only ever
|
|
767
|
+
* replaces an account with a reference to that same address, and lookup-table entries
|
|
768
|
+
* are immutable once written, so compression doesn't change what the instructions touch.
|
|
769
|
+
* Throws instead of building an oversized/invalid transaction.
|
|
756
770
|
*
|
|
757
771
|
* getExpectedSigner is an async thunk resolving to the address of the wallet that is
|
|
758
772
|
* about to sign. The transaction only ever gets a single signature written into slot 0
|
|
@@ -785,6 +799,7 @@ export async function compileRawSolanaTransaction(transaction, rpcUrl, getExpect
|
|
|
785
799
|
);
|
|
786
800
|
}
|
|
787
801
|
|
|
802
|
+
const unsignedSize = (message) => 1 + 64 + message.messageBytes.length; // compact-u16(1) + 1 signature slot
|
|
788
803
|
const preflight = buildMessageV0({ feePayer, instructions, recentBlockhash: SIZE_CHECK_BLOCKHASH });
|
|
789
804
|
if (preflight.numRequiredSignatures !== 1) {
|
|
790
805
|
throw new Error(
|
|
@@ -792,17 +807,32 @@ export async function compileRawSolanaTransaction(transaction, rpcUrl, getExpect
|
|
|
792
807
|
`but only the wallet's own signature can be provided.`
|
|
793
808
|
);
|
|
794
809
|
}
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
)
|
|
810
|
+
|
|
811
|
+
let addressLookupTables = [];
|
|
812
|
+
let size = unsignedSize(preflight);
|
|
813
|
+
if (size > SOLANA_MAX_TX_SIZE) {
|
|
814
|
+
const hint = transaction.addressLookupTableAddresses;
|
|
815
|
+
const tableAddresses = [...new Set(Array.isArray(hint) ? hint : [])];
|
|
816
|
+
if (tableAddresses.length === 0) {
|
|
817
|
+
throw new Error(
|
|
818
|
+
`Solana transaction too large to compile (${size} bytes > ${SOLANA_MAX_TX_SIZE} limit) and ` +
|
|
819
|
+
`the quote supplied no address lookup tables to compress it. Get a new quote.`
|
|
820
|
+
);
|
|
821
|
+
}
|
|
822
|
+
addressLookupTables = await fetchAddressLookupTables(rpcUrl, tableAddresses);
|
|
823
|
+
size = unsignedSize(buildMessageV0({
|
|
824
|
+
feePayer, instructions, recentBlockhash: SIZE_CHECK_BLOCKHASH, addressLookupTables,
|
|
825
|
+
}));
|
|
826
|
+
if (size > SOLANA_MAX_TX_SIZE) {
|
|
827
|
+
throw new Error(
|
|
828
|
+
`Solana transaction too large to compile (${size} bytes > ${SOLANA_MAX_TX_SIZE} limit) even ` +
|
|
829
|
+
`with its ${tableAddresses.length} address lookup table(s). Get a new quote.`
|
|
830
|
+
);
|
|
831
|
+
}
|
|
802
832
|
}
|
|
803
833
|
|
|
804
834
|
const recentBlockhash = await fetchRecentBlockhash(rpcUrl);
|
|
805
|
-
const { messageBytes } = buildMessageV0({ feePayer, instructions, recentBlockhash });
|
|
835
|
+
const { messageBytes } = buildMessageV0({ feePayer, instructions, recentBlockhash, addressLookupTables });
|
|
806
836
|
const unsignedTx = Buffer.concat([encodeCompactU16(1), Buffer.alloc(64), messageBytes]);
|
|
807
837
|
return unsignedTx.toString('base64');
|
|
808
838
|
}
|
|
@@ -847,13 +877,14 @@ export async function normalizeSolanaTransaction(transaction, rpcUrl, getExpecte
|
|
|
847
877
|
* @param {string} chain - Chain name
|
|
848
878
|
* @param {number} nonce - Account nonce
|
|
849
879
|
* @param {object} [opts]
|
|
880
|
+
* @param {string|number|bigint} [opts.gasLimit] - Resolved gas limit, overriding quote transaction fields
|
|
850
881
|
* @param {string} [opts.label='swap'] - What is being signed, for the fee-cap error
|
|
851
882
|
* @param {bigint} [opts.maxTxFeeWei] - Fee cap in wei (--max-tx-fee); 0n disables it
|
|
852
883
|
* @returns {string} 0x-prefixed signed transaction hex
|
|
853
884
|
*/
|
|
854
885
|
// Pure EVM encode/sign primitive. Quote authorization and request-intent binding
|
|
855
886
|
// happen upstream before this function receives transaction calldata.
|
|
856
|
-
export function signEvmTransaction(txData, privateKeyHex, chain, nonce, { label = 'swap', maxTxFeeWei = MAX_EVM_TX_FEE_WEI } = {}) {
|
|
887
|
+
export function signEvmTransaction(txData, privateKeyHex, chain, nonce, { gasLimit, label = 'swap', maxTxFeeWei = MAX_EVM_TX_FEE_WEI } = {}) {
|
|
857
888
|
const chainConfig = CHAIN_MAP[chain];
|
|
858
889
|
if (!chainConfig || chainConfig.type !== 'evm') {
|
|
859
890
|
throw new Error(`Unsupported EVM chain: ${chain}`);
|
|
@@ -861,7 +892,7 @@ export function signEvmTransaction(txData, privateKeyHex, chain, nonce, { label
|
|
|
861
892
|
|
|
862
893
|
const common = {
|
|
863
894
|
nonce,
|
|
864
|
-
gasLimit: toHex(txData.gas || txData.gasLimit || '210000'),
|
|
895
|
+
gasLimit: toHex(gasLimit ?? (txData.gas || txData.gasLimit || '210000')),
|
|
865
896
|
to: txData.to,
|
|
866
897
|
value: toHex(txData.value || '0'),
|
|
867
898
|
data: txData.data || '0x',
|
|
@@ -3122,7 +3153,14 @@ EXAMPLES:
|
|
|
3122
3153
|
let swapHandedOff = false;
|
|
3123
3154
|
try {
|
|
3124
3155
|
const quoteData = loadQuote(quoteId);
|
|
3125
|
-
|
|
3156
|
+
// The quote command stores the chain exactly as the user typed it
|
|
3157
|
+
// (`--chain Base`), but the lookups downstream — CHAIN_RPCS here above
|
|
3158
|
+
// all — are keyed lowercase, and only resolveChain() normalises on its
|
|
3159
|
+
// own. Without this a capitalised spelling quotes fine and then fails at
|
|
3160
|
+
// execute with "No RPC URL configured for chain: Base", so the quote can
|
|
3161
|
+
// never be used. Normalised once here, which also fixes quotes already
|
|
3162
|
+
// on disk.
|
|
3163
|
+
const chain = quoteData.chain?.toLowerCase();
|
|
3126
3164
|
const chainConfig = resolveChain(chain);
|
|
3127
3165
|
const chainType = chainConfig.type;
|
|
3128
3166
|
|
|
@@ -4417,8 +4455,6 @@ EXAMPLES:
|
|
|
4417
4455
|
const txData = currentQuote.transaction;
|
|
4418
4456
|
const finalGas = await resolveEvmSwapGasLimit(currentQuote, { chain, from: walletAddress });
|
|
4419
4457
|
logEvmSwapGasResolution(log, currentQuote, txData, finalGas);
|
|
4420
|
-
if (txData.gasLimit) txData.gasLimit = String(finalGas);
|
|
4421
|
-
else txData.gas = String(finalGas);
|
|
4422
4458
|
|
|
4423
4459
|
log(' Fetching nonce...');
|
|
4424
4460
|
await new Promise(r => setTimeout(r, 1000));
|
|
@@ -4431,7 +4467,7 @@ EXAMPLES:
|
|
|
4431
4467
|
exported.evm.privateKey,
|
|
4432
4468
|
chain,
|
|
4433
4469
|
nonce,
|
|
4434
|
-
{ maxTxFeeWei },
|
|
4470
|
+
{ gasLimit: finalGas, maxTxFeeWei },
|
|
4435
4471
|
);
|
|
4436
4472
|
}
|
|
4437
4473
|
|
package/src/wallet.js
CHANGED
|
@@ -830,20 +830,11 @@ export function buildWalletCommands(deps = {}) {
|
|
|
830
830
|
},
|
|
831
831
|
|
|
832
832
|
'list': async () => {
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
log('');
|
|
839
|
-
for (const w of result.wallets) {
|
|
840
|
-
const star = w.isDefault ? ' ★' : '';
|
|
841
|
-
const providerTag = w.provider === 'privy' ? ' (privy)' : '';
|
|
842
|
-
log(` ${w.name}${star}${providerTag}`);
|
|
843
|
-
log(` EVM: ${w.evm}`);
|
|
844
|
-
log(` Solana: ${w.solana}`);
|
|
845
|
-
log('');
|
|
846
|
-
}
|
|
833
|
+
// Read-only data: return it so the CLI prints the standard JSON
|
|
834
|
+
// envelope on stdout, in a terminal or a pipe alike. A readable
|
|
835
|
+
// summary here would break agents that capture stderr alongside
|
|
836
|
+
// stdout or run under a pseudo-terminal.
|
|
837
|
+
return listWallets();
|
|
847
838
|
},
|
|
848
839
|
|
|
849
840
|
'show': async () => {
|
|
@@ -851,15 +842,9 @@ export function buildWalletCommands(deps = {}) {
|
|
|
851
842
|
if (!name) {
|
|
852
843
|
throw new CommandError('Usage: nansen wallet show <name>', 'MISSING_ARGS');
|
|
853
844
|
}
|
|
845
|
+
// Read-only data, returned for the JSON envelope like `wallet list`.
|
|
854
846
|
try {
|
|
855
|
-
|
|
856
|
-
const star = result.isDefault ? ' ★' : '';
|
|
857
|
-
const providerTag = result.provider === 'privy' ? ' (privy)' : '';
|
|
858
|
-
log(`\n ${result.name}${star}${providerTag}`);
|
|
859
|
-
log(` EVM: ${result.evm}`);
|
|
860
|
-
log(` Solana: ${result.solana}`);
|
|
861
|
-
log(` Created: ${result.createdAt}\n`);
|
|
862
|
-
return;
|
|
847
|
+
return showWallet(name);
|
|
863
848
|
} catch (err) {
|
|
864
849
|
throw new CommandError(`❌ ${err.message}`, 'SHOW_FAILED');
|
|
865
850
|
}
|
|
@@ -891,19 +876,15 @@ export function buildWalletCommands(deps = {}) {
|
|
|
891
876
|
if (result.provider !== 'local') {
|
|
892
877
|
throw new Error(`${result.provider} wallets don't support key export. Keys are managed by the provider.`);
|
|
893
878
|
}
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
log(` nansen wallet export ${result.name} --file <path> safer: writes a file only you can read (0600)`);
|
|
904
|
-
log(` nansen wallet export ${result.name} --reveal prints them in plaintext to stdout`);
|
|
905
|
-
log('');
|
|
906
|
-
return;
|
|
879
|
+
// Same envelope rule as `wallet show`. The shape follows
|
|
880
|
+
// exportWallet() minus the privateKey fields, which are left out
|
|
881
|
+
// rather than filled with a placeholder a caller could mistake for a key.
|
|
882
|
+
return {
|
|
883
|
+
name: result.name,
|
|
884
|
+
redacted: true,
|
|
885
|
+
evm: { address: result.evm },
|
|
886
|
+
solana: { address: result.solana },
|
|
887
|
+
};
|
|
907
888
|
} catch (err) {
|
|
908
889
|
throw new CommandError(`❌ ${err.message}`, 'EXPORT_FAILED');
|
|
909
890
|
}
|
package/src/x402-svm.js
CHANGED
|
@@ -9,6 +9,14 @@ import { encodeCompactU16, deriveATA as _deriveATA } from './transfer.js';
|
|
|
9
9
|
import { resolvePaymentAmount, resolvePayTo } from './x402-policy.js';
|
|
10
10
|
import { SOLANA_MAINNET_NETWORK } from './x402-tokens.js';
|
|
11
11
|
import { CHAIN_RPCS } from './rpc-urls.js';
|
|
12
|
+
import {
|
|
13
|
+
ADDRESS_LOOKUP_TABLE_PROGRAM,
|
|
14
|
+
SLOT_HASHES_SYSVAR,
|
|
15
|
+
SYSVAR_PROGRAM,
|
|
16
|
+
isLookupTableUsable,
|
|
17
|
+
parseAddressLookupTable,
|
|
18
|
+
parseSlotHashes,
|
|
19
|
+
} from './solana-tx.js';
|
|
12
20
|
|
|
13
21
|
// ============= Constants =============
|
|
14
22
|
|
|
@@ -50,8 +58,13 @@ export function deriveATA(ownerBase58, mintBase58, tokenProgramBase58 = TOKEN_PR
|
|
|
50
58
|
* Returns numRequiredSignatures alongside the bytes. Each caller writes a
|
|
51
59
|
* fixed number of signature slots and asserts this value against it, since a
|
|
52
60
|
* header that disagrees with the slot count is rejected at broadcast.
|
|
61
|
+
*
|
|
62
|
+
* addressLookupTables ([{ key, addresses }], resolved on-chain by the caller)
|
|
63
|
+
* moves accounts out of the static key list into table lookups. Only accounts
|
|
64
|
+
* that are neither signers nor invoked as a program are eligible — the runtime
|
|
65
|
+
* requires both to be static keys — so the fee payer always stays static.
|
|
53
66
|
*/
|
|
54
|
-
export function buildMessageV0({ feePayer, instructions, recentBlockhash,
|
|
67
|
+
export function buildMessageV0({ feePayer, instructions, recentBlockhash, addressLookupTables = [] }) {
|
|
55
68
|
// All unique accounts in order: feePayer first, then signers, then rest
|
|
56
69
|
const accountMap = new Map();
|
|
57
70
|
const feePayerKey = feePayer;
|
|
@@ -75,10 +88,37 @@ export function buildMessageV0({ feePayer, instructions, recentBlockhash, accoun
|
|
|
75
88
|
}
|
|
76
89
|
}
|
|
77
90
|
|
|
91
|
+
// Pull lookup-eligible accounts out of the static list, table by table. An
|
|
92
|
+
// account found in more than one table is loaded from the first.
|
|
93
|
+
const invokedPrograms = new Set(instructions.map(ix => ix.programId));
|
|
94
|
+
const lookups = [];
|
|
95
|
+
const loadedWritable = [];
|
|
96
|
+
const loadedReadonly = [];
|
|
97
|
+
const loaded = new Set();
|
|
98
|
+
for (const table of addressLookupTables) {
|
|
99
|
+
const writableIndexes = [];
|
|
100
|
+
const readonlyIndexes = [];
|
|
101
|
+
table.addresses.forEach((address, index) => {
|
|
102
|
+
const meta = accountMap.get(address);
|
|
103
|
+
if (!meta || meta.isSigner || invokedPrograms.has(address) || loaded.has(address)) return;
|
|
104
|
+
loaded.add(address);
|
|
105
|
+
if (meta.isWritable) {
|
|
106
|
+
writableIndexes.push(index);
|
|
107
|
+
loadedWritable.push(address);
|
|
108
|
+
} else {
|
|
109
|
+
readonlyIndexes.push(index);
|
|
110
|
+
loadedReadonly.push(address);
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
if (writableIndexes.length || readonlyIndexes.length) {
|
|
114
|
+
lookups.push({ key: table.key, writableIndexes, readonlyIndexes });
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
78
118
|
// Sort: signers+writable, signers+readonly, non-signer+writable, non-signer+readonly
|
|
79
119
|
// feePayer always at index 0
|
|
80
120
|
const sortedKeys = [feePayerKey];
|
|
81
|
-
const rest = [...accountMap.entries()].filter(([k]) => k !== feePayerKey);
|
|
121
|
+
const rest = [...accountMap.entries()].filter(([k]) => k !== feePayerKey && !loaded.has(k));
|
|
82
122
|
|
|
83
123
|
// Signer+writable
|
|
84
124
|
for (const [k, v] of rest) if (v.isSigner && v.isWritable) sortedKeys.push(k);
|
|
@@ -104,9 +144,15 @@ export function buildMessageV0({ feePayer, instructions, recentBlockhash, accoun
|
|
|
104
144
|
}
|
|
105
145
|
}
|
|
106
146
|
|
|
107
|
-
// Build the account keys index
|
|
147
|
+
// Build the account keys index: static keys, then every table's writable
|
|
148
|
+
// loads, then every table's readonly loads — the order the runtime resolves.
|
|
149
|
+
const allKeys = [...sortedKeys, ...loadedWritable, ...loadedReadonly];
|
|
150
|
+
// Instruction account indexes are single bytes.
|
|
151
|
+
if (allKeys.length > 256) {
|
|
152
|
+
throw new Error(`Solana transaction references ${allKeys.length} accounts; a message can index at most 256.`);
|
|
153
|
+
}
|
|
108
154
|
const keyIndex = new Map();
|
|
109
|
-
|
|
155
|
+
allKeys.forEach((k, i) => keyIndex.set(k, i));
|
|
110
156
|
|
|
111
157
|
// Compile instructions
|
|
112
158
|
const compiledInstructions = instructions.map(ix => {
|
|
@@ -146,8 +192,15 @@ export function buildMessageV0({ feePayer, instructions, recentBlockhash, accoun
|
|
|
146
192
|
parts.push(ix.data);
|
|
147
193
|
}
|
|
148
194
|
|
|
149
|
-
// Address table lookups
|
|
150
|
-
parts.push(encodeCompactU16(
|
|
195
|
+
// Address table lookups
|
|
196
|
+
parts.push(encodeCompactU16(lookups.length));
|
|
197
|
+
for (const lookup of lookups) {
|
|
198
|
+
parts.push(base58DecodePubkey(lookup.key));
|
|
199
|
+
parts.push(encodeCompactU16(lookup.writableIndexes.length));
|
|
200
|
+
parts.push(Buffer.from(lookup.writableIndexes));
|
|
201
|
+
parts.push(encodeCompactU16(lookup.readonlyIndexes.length));
|
|
202
|
+
parts.push(Buffer.from(lookup.readonlyIndexes));
|
|
203
|
+
}
|
|
151
204
|
|
|
152
205
|
return { messageBytes: Buffer.concat(parts), numRequiredSignatures };
|
|
153
206
|
}
|
|
@@ -252,7 +305,6 @@ export function buildUnsignedSvmTransaction(
|
|
|
252
305
|
feePayer: feePayerStr,
|
|
253
306
|
instructions,
|
|
254
307
|
recentBlockhash,
|
|
255
|
-
accounts: null,
|
|
256
308
|
});
|
|
257
309
|
// The header must agree with the signature slots written below. A
|
|
258
310
|
// server-supplied feePayer equal to the paying wallet collapses the two
|
|
@@ -423,6 +475,112 @@ export async function fetchRecentBlockhash(rpcUrl = CHAIN_RPCS.solana) {
|
|
|
423
475
|
}
|
|
424
476
|
}
|
|
425
477
|
|
|
478
|
+
/**
|
|
479
|
+
* getMultipleAccounts (base64) with the shared timeout and actionable errors.
|
|
480
|
+
* Returns the accounts in request order and the slot the RPC read them at.
|
|
481
|
+
*/
|
|
482
|
+
async function getMultipleAccountsBase64(rpcUrl, addresses, purpose) {
|
|
483
|
+
if (!isHttpUrl(rpcUrl)) {
|
|
484
|
+
throw new Error(
|
|
485
|
+
'Invalid Solana RPC URL: expected a full http:// or https:// URL. Check NANSEN_SOLANA_RPC.'
|
|
486
|
+
);
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
const controller = new AbortController();
|
|
490
|
+
const timer = setTimeout(() => controller.abort(), SOLANA_RPC_TIMEOUT_MS);
|
|
491
|
+
const rpcError = (detail, cause) => new Error(
|
|
492
|
+
`Solana RPC ${detail} while fetching ${purpose}. Retry or configure a different RPC endpoint.`,
|
|
493
|
+
cause ? { cause } : undefined
|
|
494
|
+
);
|
|
495
|
+
const timeoutError = (cause) => rpcError(`did not respond within ${SOLANA_RPC_TIMEOUT_MS / 1000}s`, cause);
|
|
496
|
+
|
|
497
|
+
let data;
|
|
498
|
+
try {
|
|
499
|
+
let response;
|
|
500
|
+
try {
|
|
501
|
+
response = await fetch(rpcUrl, {
|
|
502
|
+
method: 'POST',
|
|
503
|
+
headers: { 'Content-Type': 'application/json' },
|
|
504
|
+
body: JSON.stringify({
|
|
505
|
+
jsonrpc: '2.0',
|
|
506
|
+
id: 1,
|
|
507
|
+
method: 'getMultipleAccounts',
|
|
508
|
+
params: [addresses, { encoding: 'base64', commitment: 'confirmed' }],
|
|
509
|
+
}),
|
|
510
|
+
signal: controller.signal,
|
|
511
|
+
});
|
|
512
|
+
} catch (err) {
|
|
513
|
+
if (controller.signal.aborted) throw timeoutError(err);
|
|
514
|
+
throw rpcError('was unavailable', err);
|
|
515
|
+
}
|
|
516
|
+
if (!response.ok) throw rpcError(`returned HTTP ${response.status}`);
|
|
517
|
+
try {
|
|
518
|
+
data = await response.json();
|
|
519
|
+
} catch (err) {
|
|
520
|
+
if (controller.signal.aborted) throw timeoutError(err);
|
|
521
|
+
throw rpcError('returned an invalid response', err);
|
|
522
|
+
}
|
|
523
|
+
} finally {
|
|
524
|
+
clearTimeout(timer);
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
if (data?.error) {
|
|
528
|
+
throw rpcError(`failed (${String(data.error.message ?? data.error.code ?? 'unknown RPC error')})`);
|
|
529
|
+
}
|
|
530
|
+
const accounts = data?.result?.value;
|
|
531
|
+
// Each account is matched to its address by position, so a short or padded
|
|
532
|
+
// array would pair an account with the wrong address.
|
|
533
|
+
if (!Array.isArray(accounts) || accounts.length !== addresses.length) {
|
|
534
|
+
throw rpcError('returned an unexpected account list');
|
|
535
|
+
}
|
|
536
|
+
return { accounts, slot: data.result.context?.slot };
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
const accountBytes = (account) =>
|
|
540
|
+
Buffer.from((Array.isArray(account.data) ? account.data[0] : account.data) ?? '', 'base64');
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* Fetch and parse address-lookup-table accounts, in the order given.
|
|
544
|
+
*
|
|
545
|
+
* Throws unless every address is a table owned by the lookup-table program
|
|
546
|
+
* that the runtime will still resolve: a quote that names a missing, foreign or
|
|
547
|
+
* deactivated table can't be compiled into a transaction the runtime accepts.
|
|
548
|
+
* A table that is only deactivating is still usable (see isLookupTableUsable);
|
|
549
|
+
* telling the two apart needs the SlotHashes sysvar, which is fetched only when
|
|
550
|
+
* some table has a deactivation slot.
|
|
551
|
+
*/
|
|
552
|
+
export async function fetchAddressLookupTables(rpcUrl, addresses) {
|
|
553
|
+
const { accounts } = await getMultipleAccountsBase64(rpcUrl, addresses, 'address lookup tables');
|
|
554
|
+
|
|
555
|
+
const tables = accounts.map((account, i) => {
|
|
556
|
+
const key = addresses[i];
|
|
557
|
+
if (!account) {
|
|
558
|
+
throw new Error(`Address lookup table ${key} not found on-chain. Get a new quote.`);
|
|
559
|
+
}
|
|
560
|
+
if (account.owner !== ADDRESS_LOOKUP_TABLE_PROGRAM) {
|
|
561
|
+
throw new Error(`Account ${key} is not an address lookup table. Get a new quote.`);
|
|
562
|
+
}
|
|
563
|
+
return { key, ...parseAddressLookupTable(accountBytes(account)) };
|
|
564
|
+
});
|
|
565
|
+
|
|
566
|
+
if (tables.some((t) => t.deactivationSlot !== null)) {
|
|
567
|
+
const { accounts: [sysvar], slot } = await getMultipleAccountsBase64(rpcUrl, [SLOT_HASHES_SYSVAR], 'recent slot hashes');
|
|
568
|
+
if (!sysvar || sysvar.owner !== SYSVAR_PROGRAM || !Number.isSafeInteger(slot)) {
|
|
569
|
+
throw new Error(
|
|
570
|
+
'Solana RPC returned no usable SlotHashes sysvar, so a deactivating address lookup table cannot be checked. Retry or configure a different RPC endpoint.'
|
|
571
|
+
);
|
|
572
|
+
}
|
|
573
|
+
const slotHashes = parseSlotHashes(accountBytes(sysvar));
|
|
574
|
+
for (const table of tables) {
|
|
575
|
+
if (!isLookupTableUsable(table.deactivationSlot, BigInt(slot), slotHashes)) {
|
|
576
|
+
throw new Error(`Address lookup table ${table.key} has been deactivated. Get a new quote.`);
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
return tables.map(({ key, addresses: tableAddresses }) => ({ key, addresses: tableAddresses }));
|
|
582
|
+
}
|
|
583
|
+
|
|
426
584
|
/**
|
|
427
585
|
* Get RPC URL for a Solana network identifier.
|
|
428
586
|
*/
|