nansen-cli 2.2.0 → 2.4.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 +108 -0
- package/README.md +109 -33
- package/docs/auth.md +56 -0
- package/docs/browser-login.md +101 -7
- package/docs/error-codes.md +249 -0
- package/package.json +10 -4
- package/skills/nansen-agent-guide/SKILL.md +54 -1
- package/skills/nansen-alerts-webhook-listener/SKILL.md +1 -1
- package/skills/nansen-dca-tracker/SKILL.md +1 -1
- package/skills/nansen-defi-positions/SKILL.md +1 -1
- package/skills/nansen-exit-signals/SKILL.md +2 -2
- package/skills/nansen-fund-tracker/SKILL.md +1 -1
- package/skills/nansen-general-search/SKILL.md +1 -1
- package/skills/nansen-holder-analysis/SKILL.md +2 -2
- package/skills/nansen-limit-orders/SKILL.md +1 -1
- package/skills/nansen-mpp-payment/SKILL.md +2 -2
- package/skills/nansen-perp-screener/SKILL.md +1 -1
- package/skills/nansen-perp-trader-profile/SKILL.md +1 -1
- package/skills/nansen-polymarket-deep-dive/SKILL.md +1 -1
- package/skills/nansen-polymarket-insider-scan/SKILL.md +1 -1
- package/skills/nansen-polymarket-trader-profile/SKILL.md +1 -1
- package/skills/nansen-portfolio-tracker/SKILL.md +1 -1
- package/skills/nansen-prediction-markets/SKILL.md +1 -1
- package/skills/nansen-sm-cross-chain-flows/SKILL.md +1 -1
- package/skills/nansen-smart-alerts/SKILL.md +2 -1
- package/skills/nansen-smart-money-alpha/SKILL.md +1 -1
- package/skills/nansen-smart-money-tracker/SKILL.md +8 -7
- package/skills/nansen-smart-money-trend/SKILL.md +1 -1
- package/skills/nansen-token-research/SKILL.md +1 -1
- package/skills/nansen-token-screener/SKILL.md +1 -1
- package/skills/nansen-token-transfer-analysis/SKILL.md +1 -1
- package/skills/nansen-trading/SKILL.md +1 -1
- package/skills/nansen-wallet-batch/SKILL.md +1 -1
- package/skills/nansen-wallet-clustering/SKILL.md +1 -1
- package/skills/nansen-wallet-deep-dive/SKILL.md +1 -1
- package/skills/nansen-wallet-keychain-migration/SKILL.md +1 -1
- package/skills/nansen-wallet-manager/SKILL.md +1 -1
- package/skills/nansen-wallet-profiler/SKILL.md +1 -1
- package/skills/nansen-web-fetcher/SKILL.md +1 -1
- package/skills/nansen-web-searcher/SKILL.md +1 -1
- package/src/api-endpoints.json +1605 -0
- package/src/api.js +336 -121
- package/src/auth-credentials.js +1 -0
- package/src/auth-state.js +2 -2
- package/src/auth-store-native.js +6 -1
- package/src/auth-store-worker.js +1 -1
- package/src/auth-store.js +9 -4
- package/src/bridge.js +19 -10
- package/src/cli.js +258 -107
- package/src/commands/agent.js +2 -3
- package/src/commands/alerts.js +277 -9
- package/src/commands/completion.js +6 -1
- package/src/commands/feedback.js +413 -0
- package/src/commands/mcp.js +1 -1
- package/src/commands/research.js +14 -37
- package/src/cost-cache.js +33 -7
- package/src/doctor.js +14 -5
- package/src/error-codes.js +226 -0
- package/src/feedback-journal.js +86 -0
- package/src/input-validation.js +551 -0
- package/src/limit-order.js +12 -3
- package/src/perp.js +2 -1
- package/src/privy.js +144 -48
- package/src/query-options.js +30 -7
- package/src/rpc-urls.js +3 -1
- package/src/schema.json +1254 -150
- package/src/solana-tx.js +4 -0
- package/src/telemetry.js +5 -1
- package/src/trade-validation.js +190 -21
- package/src/trading.js +229 -129
- package/src/transfer.js +7 -1
- package/src/update-check.js +32 -5
- package/src/wallet.js +220 -57
- package/src/walletconnect-x402.js +152 -52
- package/src/x402-audit.js +191 -0
- package/src/x402-payment-balance.js +90 -0
- package/src/x402-policy.js +151 -4
- package/src/x402.js +51 -22
|
@@ -9,20 +9,33 @@ import crypto from 'crypto';
|
|
|
9
9
|
import { NansenError, ErrorCode } from './api.js';
|
|
10
10
|
import { wcExec } from './walletconnect-exec.js';
|
|
11
11
|
import { getWalletConnectAddress, parseWcJson } from './walletconnect-trading.js';
|
|
12
|
-
import { evaluatePaymentRequirement, resolvePaymentAmount, resolvePayTo } from './x402-policy.js';
|
|
12
|
+
import { evaluatePaymentRequirement, resolvePaymentAmount, resolvePayTo, signWithSessionCharge } from './x402-policy.js';
|
|
13
|
+
import { isEvmNetwork } from './x402-evm.js';
|
|
14
|
+
import { rankRequirements } from './x402.js';
|
|
15
|
+
import { hasSufficientEvmPaymentBalance } from './x402-payment-balance.js';
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* True for an option this path can sign: scheme=exact with EIP-3009
|
|
19
|
+
* TransferWithAuthorization support (extra.name + extra.version). Like the
|
|
20
|
+
* local EVM signer, only an absent or "eip3009" transfer method is signed as
|
|
21
|
+
* EIP-3009; Permit2 and unknown methods are not compatible.
|
|
22
|
+
*/
|
|
23
|
+
function isCompatible(req) {
|
|
24
|
+
const method = req?.extra?.assetTransferMethod;
|
|
25
|
+
return Boolean(
|
|
26
|
+
req?.scheme === 'exact' &&
|
|
27
|
+
req.extra?.name &&
|
|
28
|
+
req.extra?.version &&
|
|
29
|
+
(!method || method === 'eip3009')
|
|
30
|
+
);
|
|
31
|
+
}
|
|
13
32
|
|
|
14
33
|
/**
|
|
15
34
|
* Select a compatible payment requirement from the accepts array.
|
|
16
|
-
* Requires scheme=exact and EIP-3009 TransferWithAuthorization support (extra.name + extra.version).
|
|
17
35
|
*/
|
|
18
36
|
export function selectPaymentRequirement(accepts) {
|
|
19
37
|
if (!Array.isArray(accepts) || accepts.length === 0) return null;
|
|
20
|
-
|
|
21
|
-
return accepts.find(req =>
|
|
22
|
-
req.scheme === 'exact' &&
|
|
23
|
-
req.extra?.name &&
|
|
24
|
-
req.extra?.version
|
|
25
|
-
) || null;
|
|
38
|
+
return accepts.find(isCompatible) || null;
|
|
26
39
|
}
|
|
27
40
|
|
|
28
41
|
/**
|
|
@@ -126,45 +139,35 @@ export function buildPaymentSignatureHeader({ signature, authorization, resource
|
|
|
126
139
|
|
|
127
140
|
/**
|
|
128
141
|
* Format amount for human-readable display (e.g., "0.01 USDC")
|
|
142
|
+
*
|
|
143
|
+
* Prefers the policy decision, which scaled the amount with the known token's
|
|
144
|
+
* decimals; the server's `extra` rarely carries decimals, and the BSC tokens
|
|
145
|
+
* use 18, not 6.
|
|
129
146
|
*/
|
|
130
|
-
function formatPaymentAmount(requirement) {
|
|
147
|
+
function formatPaymentAmount(requirement, payment) {
|
|
131
148
|
const { extra } = requirement;
|
|
132
|
-
const
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
149
|
+
const symbol = payment?.symbol || extra.symbol || extra.name || 'tokens';
|
|
150
|
+
let amount = payment?.usd;
|
|
151
|
+
if (typeof amount !== 'number') {
|
|
152
|
+
const decimals = extra.decimals || 6;
|
|
153
|
+
amount = Number(resolvePaymentAmount(requirement)) / Math.pow(10, decimals);
|
|
154
|
+
}
|
|
136
155
|
const chain = requirement.network || requirement.chain || 'unknown';
|
|
137
156
|
return `${amount} ${symbol} on ${chain}`;
|
|
138
157
|
}
|
|
139
158
|
|
|
140
159
|
/**
|
|
141
|
-
*
|
|
142
|
-
*
|
|
143
|
-
*
|
|
144
|
-
*
|
|
145
|
-
* @returns {string} Base64-encoded Payment-Signature header value
|
|
146
|
-
* @throws {NansenError} On failure
|
|
160
|
+
* Prepare one option for signing: policy, chain-scoped session, balance,
|
|
161
|
+
* typed data. Returns { fromAddress, typedData, payment } (payment is the
|
|
162
|
+
* policy decision) or { error } explaining why
|
|
163
|
+
* the option is skipped; `logged` marks an error already reported on stderr.
|
|
147
164
|
*/
|
|
148
|
-
|
|
149
|
-
//
|
|
150
|
-
const accepts = paymentRequirements.accepts || paymentRequirements;
|
|
151
|
-
const requirement = selectPaymentRequirement(Array.isArray(accepts) ? accepts : [accepts]);
|
|
152
|
-
if (!requirement) {
|
|
153
|
-
const available = (Array.isArray(accepts) ? accepts : []).map(r => r.scheme).join(', ');
|
|
154
|
-
throw new NansenError(
|
|
155
|
-
`x402 payment required but no compatible payment method found. Available: ${available || 'none'}. Need scheme=exact with EIP-3009 support.`,
|
|
156
|
-
ErrorCode.PAYMENT_REQUIRED,
|
|
157
|
-
402
|
|
158
|
-
);
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
// 2. Evaluate payment policy before touching any signing material
|
|
165
|
+
async function prepareRequirement(requirement) {
|
|
166
|
+
// Evaluate payment policy before touching any signing material
|
|
162
167
|
const decision = evaluatePaymentRequirement(requirement);
|
|
163
|
-
if (!decision.ok) {
|
|
164
|
-
throw new Error(decision.reason);
|
|
165
|
-
}
|
|
168
|
+
if (!decision.ok) return { error: new Error(decision.reason) };
|
|
166
169
|
|
|
167
|
-
//
|
|
170
|
+
// Resolve the WalletConnect signer scoped to this exact chain. EVM
|
|
168
171
|
// addresses are identical across chains, so "some account exists in the
|
|
169
172
|
// session" can't prove the session was actually approved for THIS chain --
|
|
170
173
|
// only the CAIP-2 chain tag can (mirrors getWalletConnectAddress's chainId
|
|
@@ -176,28 +179,54 @@ export async function handleX402Payment(paymentRequirements) {
|
|
|
176
179
|
// with no chain filter at all.
|
|
177
180
|
const chainId = parseChainId(requirement.network);
|
|
178
181
|
if (chainId === null) {
|
|
179
|
-
|
|
182
|
+
return { error: new Error(`Refusing to auto-pay: unsupported or missing EVM network ${requirement.network}.`) };
|
|
180
183
|
}
|
|
181
184
|
const fromAddress = await getWalletConnectAddress('evm', chainId);
|
|
182
185
|
if (!fromAddress) {
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
186
|
+
return {
|
|
187
|
+
error: new NansenError(
|
|
188
|
+
`x402 payment required but no WalletConnect session is active for chain ${requirement.network}. ` +
|
|
189
|
+
'To pay automatically: create a local wallet with `nansen wallet create` (then set NANSEN_WALLET_PASSWORD), ' +
|
|
190
|
+
'or connect an external wallet approved for this chain via the `walletconnect` CLI (`walletconnect connect`).',
|
|
191
|
+
ErrorCode.PAYMENT_REQUIRED,
|
|
192
|
+
402
|
|
193
|
+
),
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// Don't ask the user to approve a payment the wallet can't cover.
|
|
198
|
+
if (!await hasSufficientEvmPaymentBalance(requirement, fromAddress)) {
|
|
199
|
+
return {
|
|
200
|
+
logged: true,
|
|
201
|
+
error: new NansenError(
|
|
202
|
+
`x402 payment required but the WalletConnect wallet has an insufficient token balance on ${requirement.network}. ` +
|
|
203
|
+
'Fund the token on this network or use another funded payment option.',
|
|
204
|
+
ErrorCode.PAYMENT_REQUIRED,
|
|
205
|
+
402
|
|
206
|
+
),
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
try {
|
|
211
|
+
return { fromAddress, typedData: buildEIP712TypedData({ fromAddress, requirement }), payment: decision };
|
|
212
|
+
} catch (error) {
|
|
213
|
+
return { error };
|
|
190
214
|
}
|
|
215
|
+
}
|
|
191
216
|
|
|
192
|
-
|
|
193
|
-
|
|
217
|
+
/**
|
|
218
|
+
* Ask the connected wallet to sign one option and build its header.
|
|
219
|
+
* A rejected, timed-out, or malformed signature throws: the user was already
|
|
220
|
+
* prompted, so the caller must not prompt again for another option.
|
|
221
|
+
*/
|
|
222
|
+
async function signRequirement(requirement, fromAddress, typedData, resource, payment) {
|
|
194
223
|
const typedDataJson = JSON.stringify(typedData);
|
|
195
224
|
|
|
196
|
-
//
|
|
197
|
-
const amountStr = formatPaymentAmount(requirement);
|
|
225
|
+
// Log payment info to stderr (stdout is for JSON output)
|
|
226
|
+
const amountStr = formatPaymentAmount(requirement, payment);
|
|
198
227
|
process.stderr.write(`x402: Requesting payment approval (${amountStr})...\n`);
|
|
199
228
|
|
|
200
|
-
//
|
|
229
|
+
// Sign via walletconnect CLI (120s timeout for user approval)
|
|
201
230
|
let signResult;
|
|
202
231
|
try {
|
|
203
232
|
const output = await wcExec('walletconnect', ['sign-typed-data', typedDataJson], 120000);
|
|
@@ -217,7 +246,7 @@ export async function handleX402Payment(paymentRequirements) {
|
|
|
217
246
|
);
|
|
218
247
|
}
|
|
219
248
|
|
|
220
|
-
//
|
|
249
|
+
// Build Payment-Signature header (authorization values must be strings per x402 spec)
|
|
221
250
|
const authorization = {
|
|
222
251
|
from: fromAddress,
|
|
223
252
|
to: resolvePayTo(requirement),
|
|
@@ -230,10 +259,81 @@ export async function handleX402Payment(paymentRequirements) {
|
|
|
230
259
|
const headerValue = buildPaymentSignatureHeader({
|
|
231
260
|
signature: signResult.signature,
|
|
232
261
|
authorization,
|
|
233
|
-
resource
|
|
262
|
+
resource,
|
|
234
263
|
accepted: requirement,
|
|
235
264
|
});
|
|
236
265
|
|
|
237
266
|
process.stderr.write(`x402: Payment signed successfully.\n`);
|
|
238
267
|
return headerValue;
|
|
239
268
|
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Generate WalletConnect payment signatures for every viable option, cheapest
|
|
272
|
+
* first (the same ranking the local wallet uses). Options refused by policy,
|
|
273
|
+
* without a session for their chain, or known to be unfunded are skipped
|
|
274
|
+
* before the user is prompted. Caller tries each until the server accepts one.
|
|
275
|
+
*
|
|
276
|
+
* Throws when nothing can be signed (the last skip reason) or when signing
|
|
277
|
+
* itself fails.
|
|
278
|
+
*
|
|
279
|
+
* Yields the same { signature, network, asset, payment, releaseCharge } shape
|
|
280
|
+
* as createPaymentSignatures() in x402.js.
|
|
281
|
+
*
|
|
282
|
+
* @param {Object} paymentRequirements - Decoded payment requirements from 402 response
|
|
283
|
+
* @param {object} [options] - { onCapRefusal }, called with the reason when the session cap refuses an option
|
|
284
|
+
* @returns {AsyncGenerator<{ signature: string, network: string, asset: string, payment: object, releaseCharge: Function }>}
|
|
285
|
+
*/
|
|
286
|
+
export async function* createWalletConnectPaymentSignatures(paymentRequirements, options = {}) {
|
|
287
|
+
const accepts = paymentRequirements.accepts || paymentRequirements;
|
|
288
|
+
const list = Array.isArray(accepts) ? accepts : [accepts];
|
|
289
|
+
const compatible = rankRequirements(list.filter(isCompatible))
|
|
290
|
+
.filter(req => isEvmNetwork(req.network));
|
|
291
|
+
if (compatible.length === 0) {
|
|
292
|
+
const available = list.map(r => r?.scheme).join(', ');
|
|
293
|
+
throw new NansenError(
|
|
294
|
+
`x402 payment required but no compatible payment method found. Available: ${available || 'none'}. Need scheme=exact with EIP-3009 support.`,
|
|
295
|
+
ErrorCode.PAYMENT_REQUIRED,
|
|
296
|
+
402
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
const resource = paymentRequirements.resource || { url: '', description: '', mimeType: '' };
|
|
301
|
+
let lastError = null;
|
|
302
|
+
let yielded = false;
|
|
303
|
+
for (const requirement of compatible) {
|
|
304
|
+
const { fromAddress, typedData, payment, error, logged } = await prepareRequirement(requirement);
|
|
305
|
+
if (error) {
|
|
306
|
+
if (compatible.length > 1 && !logged) console.error(`[x402] Skipping ${requirement.network} WalletConnect option: ${error.message}`);
|
|
307
|
+
lastError = error;
|
|
308
|
+
continue;
|
|
309
|
+
}
|
|
310
|
+
// The charge comes before the approval prompt, so an over-cap option never prompts.
|
|
311
|
+
const signed = await signWithSessionCharge(payment, () => signRequirement(requirement, fromAddress, typedData, resource, payment));
|
|
312
|
+
if (!signed.ok) {
|
|
313
|
+
console.error(`[x402] Skipping ${requirement.network} WalletConnect option: ${signed.reason}`);
|
|
314
|
+
options.onCapRefusal?.(signed.reason);
|
|
315
|
+
lastError = new Error(signed.reason);
|
|
316
|
+
continue;
|
|
317
|
+
}
|
|
318
|
+
yielded = true;
|
|
319
|
+
yield { signature: signed.value, network: requirement.network, asset: requirement.asset, payment, releaseCharge: signed.release };
|
|
320
|
+
}
|
|
321
|
+
if (!yielded && lastError) throw lastError;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Handle x402 payment: return the first viable Payment-Signature header.
|
|
326
|
+
* For fallback across options, use createWalletConnectPaymentSignatures().
|
|
327
|
+
* The signature's session-cap charge is never released, so a payment the
|
|
328
|
+
* server rejects still counts against the cap.
|
|
329
|
+
*
|
|
330
|
+
* @param {Object} paymentRequirements - Decoded payment requirements from 402 response
|
|
331
|
+
* @returns {string} Base64-encoded Payment-Signature header value
|
|
332
|
+
* @throws {NansenError} On failure
|
|
333
|
+
*/
|
|
334
|
+
export async function handleX402Payment(paymentRequirements) {
|
|
335
|
+
for await (const { signature } of createWalletConnectPaymentSignatures(paymentRequirements)) {
|
|
336
|
+
return signature;
|
|
337
|
+
}
|
|
338
|
+
throw new NansenError('x402 payment required but no WalletConnect payment option could be signed.', ErrorCode.PAYMENT_REQUIRED, 402);
|
|
339
|
+
}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local audit log of x402 auto-payments: ~/.nansen/x402/payments.jsonl.
|
|
3
|
+
*
|
|
4
|
+
* One JSON line when a signed payment is sent, and one for its outcome
|
|
5
|
+
* (accepted, rejected or ambiguous), sharing an id. Lines never carry the
|
|
6
|
+
* payment signature, request or response bodies, or the URL's query string.
|
|
7
|
+
*
|
|
8
|
+
* Writes are best-effort: a failure warns once on stderr and never blocks a
|
|
9
|
+
* payment. The log is for auditing; it is not a safety control. A symlinked or
|
|
10
|
+
* hard-linked log, or a symlinked ~/.nansen or x402 directory, is refused
|
|
11
|
+
* rather than followed, so records never land in (or re-permission) another
|
|
12
|
+
* file.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import crypto from 'node:crypto';
|
|
16
|
+
import fs from 'node:fs';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
import { authDirectory } from './auth-credentials.js';
|
|
19
|
+
import { openLocalFile } from './local-file.js';
|
|
20
|
+
|
|
21
|
+
let warned = false;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Throws when no absolute home directory is known, rather than resolving
|
|
25
|
+
* against the working directory (which could be a git checkout).
|
|
26
|
+
*/
|
|
27
|
+
export function x402AuditLogPath() {
|
|
28
|
+
return path.join(authDirectory(), 'x402', 'payments.jsonl');
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function newPaymentId() {
|
|
32
|
+
return crypto.randomUUID();
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Origin and path only. The query string can carry addresses or other
|
|
37
|
+
* user-supplied values, and a URL that doesn't parse is dropped entirely.
|
|
38
|
+
*/
|
|
39
|
+
export function sanitizeRequestUrl(url) {
|
|
40
|
+
try {
|
|
41
|
+
const parsed = new URL(url);
|
|
42
|
+
return `${parsed.origin}${parsed.pathname}`;
|
|
43
|
+
} catch {
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* chmod a descriptor to `mode` only when group or other users have access.
|
|
50
|
+
* A file the user can write but not chmod (owned by another user) is fine
|
|
51
|
+
* as long as it is already private.
|
|
52
|
+
*/
|
|
53
|
+
function tightenIfOpen(fd, mode) {
|
|
54
|
+
if (process.platform === 'win32') return;
|
|
55
|
+
if (fs.fstatSync(fd).mode & 0o077) fs.fchmodSync(fd, mode);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Tighten the x402 directory to 0700 through a descriptor opened without
|
|
60
|
+
* following symlinks, and only when it is still the directory `expected`
|
|
61
|
+
* (checked before the log was opened), so a swapped-in link at the x402
|
|
62
|
+
* directory or ~/.nansen can't redirect the chmod.
|
|
63
|
+
*/
|
|
64
|
+
function tightenDirectory(dir, expected) {
|
|
65
|
+
if (process.platform === 'win32') return;
|
|
66
|
+
const { O_RDONLY, O_DIRECTORY, O_NOFOLLOW } = fs.constants;
|
|
67
|
+
const fd = fs.openSync(dir, O_RDONLY | O_DIRECTORY | O_NOFOLLOW);
|
|
68
|
+
try {
|
|
69
|
+
const opened = fs.fstatSync(fd);
|
|
70
|
+
if (opened.dev !== expected.dev || opened.ino !== expected.ino) {
|
|
71
|
+
throw new Error(`refusing ${dir}: directory was replaced while writing`);
|
|
72
|
+
}
|
|
73
|
+
tightenIfOpen(fd, 0o700);
|
|
74
|
+
} finally {
|
|
75
|
+
fs.closeSync(fd);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Run `fn` with a umask of 077, so the paths it creates are exactly 0700/0600
|
|
81
|
+
* whatever the user's umask. A umask such as 0277 would otherwise create a
|
|
82
|
+
* 0500 directory or 0400 file that later records can't be written to.
|
|
83
|
+
* The umask is process-wide, so anything another thread creates in this short
|
|
84
|
+
* synchronous window is only made more private, never less.
|
|
85
|
+
*/
|
|
86
|
+
function withPrivateUmask(fn) {
|
|
87
|
+
let previous;
|
|
88
|
+
try {
|
|
89
|
+
previous = process.umask(0o077);
|
|
90
|
+
} catch {
|
|
91
|
+
// Worker threads can't change the umask; fall back to the user's.
|
|
92
|
+
return fn();
|
|
93
|
+
}
|
|
94
|
+
try {
|
|
95
|
+
return fn();
|
|
96
|
+
} finally {
|
|
97
|
+
process.umask(previous);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Create `dir` if missing (its parent must exist) and refuse anything other
|
|
103
|
+
* than a real directory, so a symlink is never followed into another tree.
|
|
104
|
+
* Returns its lstat.
|
|
105
|
+
*/
|
|
106
|
+
function ensureDirectory(dir) {
|
|
107
|
+
try {
|
|
108
|
+
fs.mkdirSync(dir, { mode: 0o700 });
|
|
109
|
+
} catch (err) {
|
|
110
|
+
if (err.code !== 'EEXIST') throw err;
|
|
111
|
+
}
|
|
112
|
+
const stat = fs.lstatSync(dir);
|
|
113
|
+
if (!stat.isDirectory()) {
|
|
114
|
+
throw new Error(`refusing ${dir}: expected a directory without symlinks`);
|
|
115
|
+
}
|
|
116
|
+
return stat;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Write all of `text` at the end of the log. O_APPEND puts each write at the
|
|
121
|
+
* current end; a short write (nearly full disk) continues with the rest.
|
|
122
|
+
*/
|
|
123
|
+
function appendAll(fd, text) {
|
|
124
|
+
const bytes = Buffer.from(text, 'utf8');
|
|
125
|
+
let offset = 0;
|
|
126
|
+
while (offset < bytes.length) {
|
|
127
|
+
const written = fs.writeSync(fd, bytes, offset, bytes.length - offset);
|
|
128
|
+
if (!written) throw new Error('the disk accepted no more bytes');
|
|
129
|
+
offset += written;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* True when the log is non-empty and its last byte isn't a newline, i.e. an
|
|
135
|
+
* earlier write was cut short. The next record then starts on a fresh line
|
|
136
|
+
* instead of being glued onto the broken one.
|
|
137
|
+
*/
|
|
138
|
+
function endsMidLine(fd) {
|
|
139
|
+
const { size } = fs.fstatSync(fd);
|
|
140
|
+
if (size === 0) return false;
|
|
141
|
+
const last = Buffer.alloc(1);
|
|
142
|
+
fs.readSync(fd, last, 0, 1, size - 1);
|
|
143
|
+
return last[0] !== 0x0a;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Append one record. Never throws.
|
|
148
|
+
*/
|
|
149
|
+
export function appendPaymentRecord(record) {
|
|
150
|
+
let file = null;
|
|
151
|
+
let fd;
|
|
152
|
+
try {
|
|
153
|
+
file = x402AuditLogPath();
|
|
154
|
+
const dir = path.dirname(file);
|
|
155
|
+
const nansenDir = path.dirname(dir);
|
|
156
|
+
const { O_RDWR, O_APPEND, O_CREAT } = fs.constants;
|
|
157
|
+
let dirStat;
|
|
158
|
+
fd = withPrivateUmask(() => {
|
|
159
|
+
ensureDirectory(nansenDir);
|
|
160
|
+
dirStat = ensureDirectory(dir);
|
|
161
|
+
// Rooted at the home directory, which may itself be a symlink (as /var
|
|
162
|
+
// is on macOS). Refuses a symlink or hard link at the log, a symlinked
|
|
163
|
+
// ~/.nansen or x402 directory, and a path swapped while opening.
|
|
164
|
+
return openLocalFile(file, { root: path.dirname(nansenDir), flags: O_RDWR | O_APPEND | O_CREAT, mode: 0o600 });
|
|
165
|
+
});
|
|
166
|
+
// The open mode only applies when the file is created; tighten an
|
|
167
|
+
// existing file too. Records are never written to a file others can read.
|
|
168
|
+
tightenIfOpen(fd, 0o600);
|
|
169
|
+
tightenDirectory(dir, dirStat);
|
|
170
|
+
const line = `${JSON.stringify({ timestamp: new Date().toISOString(), ...record })}\n`;
|
|
171
|
+
appendAll(fd, endsMidLine(fd) ? `\n${line}` : line);
|
|
172
|
+
} catch (err) {
|
|
173
|
+
if (!warned) {
|
|
174
|
+
warned = true;
|
|
175
|
+
// EACCES/EPERM usually means a run under sudo left root-owned files.
|
|
176
|
+
const hint = file && (err.code === 'EACCES' || err.code === 'EPERM')
|
|
177
|
+
? ` If it was created by a run under sudo, take it back with: sudo chown -R "$(id -un)" ${path.dirname(file)}`
|
|
178
|
+
: '';
|
|
179
|
+
console.error(`[x402] Warning: could not write the payment audit log${file ? ` ${file}` : ''} (${err.message}). Payments are not blocked.${hint}`);
|
|
180
|
+
}
|
|
181
|
+
} finally {
|
|
182
|
+
if (fd !== undefined) {
|
|
183
|
+
try { fs.closeSync(fd); } catch { /* already reported or harmless */ }
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Test hook: let the next failure warn again. */
|
|
189
|
+
export function resetAuditWarningForTests() {
|
|
190
|
+
warned = false;
|
|
191
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { CHAIN_RPCS } from './rpc-urls.js';
|
|
2
|
+
import { resolvePaymentAmount, resolveKnownToken } from './x402-policy.js';
|
|
3
|
+
import { deriveATA, getSolanaRpcUrl } from './x402-svm.js';
|
|
4
|
+
|
|
5
|
+
// RPC endpoint per supported x402 EVM network.
|
|
6
|
+
export const EVM_X402_RPCS = {
|
|
7
|
+
'eip155:8453': CHAIN_RPCS.base,
|
|
8
|
+
'eip155:196': CHAIN_RPCS.xlayer,
|
|
9
|
+
'eip155:56': CHAIN_RPCS.bsc,
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
async function rpcResult(rpc, method, params) {
|
|
13
|
+
const response = await fetch(rpc, {
|
|
14
|
+
method: 'POST',
|
|
15
|
+
headers: { 'Content-Type': 'application/json' },
|
|
16
|
+
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
|
|
17
|
+
signal: AbortSignal.timeout(5000),
|
|
18
|
+
});
|
|
19
|
+
const data = await response.json();
|
|
20
|
+
if (response.ok === false || data.error) throw new Error('Balance unavailable');
|
|
21
|
+
return data.result;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Compare a raw balance read with the payment amount. A read that throws is
|
|
26
|
+
* unknown, not zero: let server verification decide.
|
|
27
|
+
*/
|
|
28
|
+
async function hasSufficientBalance(requirement, readBalance) {
|
|
29
|
+
const token = resolveKnownToken(requirement.network, requirement.asset);
|
|
30
|
+
const symbol = token?.symbol || 'token';
|
|
31
|
+
const amount = BigInt(resolvePaymentAmount(requirement));
|
|
32
|
+
let balance;
|
|
33
|
+
try {
|
|
34
|
+
balance = await readBalance();
|
|
35
|
+
} catch {
|
|
36
|
+
console.error(`[x402] Unable to check ${symbol} balance on ${requirement.network}; deferring to server verification.`);
|
|
37
|
+
return true;
|
|
38
|
+
}
|
|
39
|
+
if (balance < amount) {
|
|
40
|
+
console.error(
|
|
41
|
+
`[x402] Skipping ${symbol} on ${requirement.network}: insufficient token balance. ` +
|
|
42
|
+
`Fund this token on this network or use another funded payment option.`,
|
|
43
|
+
);
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Skip known unfunded EVM options before signing. RPC failures remain
|
|
51
|
+
* best-effort: let server verification decide when the balance is unknown.
|
|
52
|
+
*/
|
|
53
|
+
export async function hasSufficientEvmPaymentBalance(requirement, address) {
|
|
54
|
+
const rpc = EVM_X402_RPCS[requirement.network];
|
|
55
|
+
if (!rpc) return true;
|
|
56
|
+
return hasSufficientBalance(requirement, async () => {
|
|
57
|
+
const result = await rpcResult(rpc, 'eth_call', [{
|
|
58
|
+
to: requirement.asset,
|
|
59
|
+
data: `0x70a08231${address.replace(/^0x/, '').toLowerCase().padStart(64, '0')}`,
|
|
60
|
+
}, 'latest']);
|
|
61
|
+
if (!/^0x[0-9a-f]+$/i.test(result)) throw new Error('Balance unavailable');
|
|
62
|
+
return BigInt(result);
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Solana counterpart of hasSufficientEvmPaymentBalance. The payment transfers
|
|
68
|
+
* from the payer's associated token account, so only that account counts: a
|
|
69
|
+
* missing ATA is a zero balance, not an unknown one.
|
|
70
|
+
*/
|
|
71
|
+
export async function hasSufficientSvmPaymentBalance(requirement, address) {
|
|
72
|
+
let rpc;
|
|
73
|
+
try {
|
|
74
|
+
rpc = getSolanaRpcUrl(requirement.network);
|
|
75
|
+
} catch {
|
|
76
|
+
return true;
|
|
77
|
+
}
|
|
78
|
+
return hasSufficientBalance(requirement, async () => {
|
|
79
|
+
const result = await rpcResult(rpc, 'getTokenAccountsByOwner', [
|
|
80
|
+
address, { mint: requirement.asset }, { encoding: 'jsonParsed' },
|
|
81
|
+
]);
|
|
82
|
+
if (!Array.isArray(result?.value)) throw new Error('Balance unavailable');
|
|
83
|
+
const ata = deriveATA(address, requirement.asset);
|
|
84
|
+
const account = result.value.find(entry => entry?.pubkey === ata);
|
|
85
|
+
if (!account) return 0n;
|
|
86
|
+
const raw = account.account?.data?.parsed?.info?.tokenAmount?.amount;
|
|
87
|
+
if (typeof raw !== 'string' || !/^\d+$/.test(raw)) throw new Error('Balance unavailable');
|
|
88
|
+
return BigInt(raw);
|
|
89
|
+
});
|
|
90
|
+
}
|