nansen-cli 2.5.0 → 2.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +52 -0
- package/README.md +19 -13
- package/docs/error-codes.md +1 -0
- package/package.json +5 -5
- package/scripts/postinstall.js +36 -11
- package/skills/nansen-alerts-webhook-listener/SKILL.md +1 -1
- package/skills/nansen-limit-orders/SKILL.md +6 -3
- package/skills/nansen-smart-alerts/SKILL.md +0 -21
- package/skills/nansen-token-research/SKILL.md +1 -1
- package/skills/nansen-trading/SKILL.md +18 -15
- package/skills/nansen-web-searcher/SKILL.md +1 -1
- package/src/api.js +0 -14
- package/src/bridge.js +48 -4
- package/src/cli.js +151 -117
- package/src/commands/alerts.js +54 -66
- package/src/commands/completion.js +0 -1
- package/src/commands/research.js +35 -35
- package/src/crypto.js +17 -0
- package/src/error-codes.js +1 -0
- package/src/execute-guard.js +43 -3
- package/src/input-validation.js +32 -3
- package/src/limit-order.js +12 -4
- package/src/perp.js +72 -13
- package/src/privy.js +145 -103
- package/src/schema.json +499 -93
- package/src/trade-validation.js +57 -2
- package/src/trading.js +14 -14
- package/src/transfer.js +65 -7
- package/src/wallet.js +9 -10
- package/skills/nansen-web-fetcher/SKILL.md +0 -53
package/src/limit-order.js
CHANGED
|
@@ -937,7 +937,7 @@ EXAMPLES:
|
|
|
937
937
|
log('');
|
|
938
938
|
|
|
939
939
|
} catch (err) {
|
|
940
|
-
if (err.reported) throw err;
|
|
940
|
+
if (err.reported || err.code === 'CONFIRMATION_REQUIRED') throw err;
|
|
941
941
|
log(`Error: ${err.message}`);
|
|
942
942
|
if (err.details) log(` Details: ${JSON.stringify(err.details)}`);
|
|
943
943
|
if (err.cause) log(` Cause: ${err.cause.message || err.cause}`);
|
|
@@ -946,6 +946,7 @@ EXAMPLES:
|
|
|
946
946
|
},
|
|
947
947
|
|
|
948
948
|
'list': async (args, apiInstance, flags, options) => {
|
|
949
|
+
rejectBlankOption(options.token, 'token', 'SOL');
|
|
949
950
|
rejectBlankOption(options.mint, 'mint', 'SOL');
|
|
950
951
|
rejectBlankOption(options.limit, 'limit', '20');
|
|
951
952
|
rejectBlankOption(options.offset, 'offset', '0');
|
|
@@ -953,7 +954,14 @@ EXAMPLES:
|
|
|
953
954
|
rejectBlankOption(options.wallet, 'wallet', '<name>');
|
|
954
955
|
const walletName = options.wallet;
|
|
955
956
|
const state = options.state;
|
|
956
|
-
|
|
957
|
+
// --mint is the old name of --token.
|
|
958
|
+
if (options.token !== undefined && options.mint !== undefined) {
|
|
959
|
+
log(`Error: --token ${options.token} and --mint ${options.mint} are the same input; pass one.`);
|
|
960
|
+
exit(1);
|
|
961
|
+
return;
|
|
962
|
+
}
|
|
963
|
+
const tokenArg = options.token ?? options.mint;
|
|
964
|
+
const mint = tokenArg ? resolveTokenAddress(tokenArg, 'solana') : undefined;
|
|
957
965
|
const limit = options.limit || 20;
|
|
958
966
|
// parseArgs keeps numbers as strings; the footer below adds to offset.
|
|
959
967
|
const offset = options.offset == null ? 0 : Number(options.offset);
|
|
@@ -969,7 +977,7 @@ EXAMPLES:
|
|
|
969
977
|
if (mint) {
|
|
970
978
|
const mintValidation = validateTokenAddress(mint, 'solana');
|
|
971
979
|
if (!mintValidation.valid) {
|
|
972
|
-
log(`Error: Invalid --
|
|
980
|
+
log(`Error: Invalid --token address: ${mintValidation.error}`);
|
|
973
981
|
exit(1);
|
|
974
982
|
return;
|
|
975
983
|
}
|
|
@@ -1159,7 +1167,7 @@ EXAMPLES:
|
|
|
1159
1167
|
log('');
|
|
1160
1168
|
|
|
1161
1169
|
} catch (err) {
|
|
1162
|
-
if (err.reported) throw err;
|
|
1170
|
+
if (err.reported || err.code === 'CONFIRMATION_REQUIRED') throw err;
|
|
1163
1171
|
log(`Error: ${err.message}`);
|
|
1164
1172
|
if (err.details) log(` Details: ${JSON.stringify(err.details)}`);
|
|
1165
1173
|
exit(1);
|
package/src/perp.js
CHANGED
|
@@ -429,7 +429,7 @@ async function buildScreenSignSubmit(apiInstance, prepared, ctx) {
|
|
|
429
429
|
log(` Filled${tag}: ${o.totalSz} @ ${o.avgPx} (${oidText})`);
|
|
430
430
|
} else {
|
|
431
431
|
log(` Resting order${tag}: ${oidText}`);
|
|
432
|
-
if (coin && o.oidSafe) log(` Cancel: nansen perp cancel --
|
|
432
|
+
if (coin && o.oidSafe) log(` Cancel: nansen perp cancel --symbol ${coin} --oid ${o.oid}`);
|
|
433
433
|
}
|
|
434
434
|
}
|
|
435
435
|
} else if (result.response) {
|
|
@@ -548,6 +548,16 @@ function parsePositiveNumber(raw, name) {
|
|
|
548
548
|
return n;
|
|
549
549
|
}
|
|
550
550
|
|
|
551
|
+
// Canonical form of a decimal string already validated by parsePositiveNumber,
|
|
552
|
+
// using string operations only: "025" -> "25", "12.50" -> "12.5", ".5" -> "0.5".
|
|
553
|
+
function normalizeDecimalString(raw) {
|
|
554
|
+
const s = String(scalar(raw, 'amount') ?? '').trim();
|
|
555
|
+
const [intPart, fracPart = ''] = s.split('.');
|
|
556
|
+
const int = intPart.replace(/^0+/, '') || '0';
|
|
557
|
+
const frac = fracPart.replace(/0+$/, '');
|
|
558
|
+
return frac ? `${int}.${frac}` : int;
|
|
559
|
+
}
|
|
560
|
+
|
|
551
561
|
function parsePositiveInt(raw, name) {
|
|
552
562
|
// Digits-only check before parseInt — parseInt("2.5") floors to 2 and
|
|
553
563
|
// parseInt("123abc") yields 123, so a fractional or garbage value would
|
|
@@ -652,11 +662,16 @@ function assertOrderType(raw) {
|
|
|
652
662
|
return type;
|
|
653
663
|
}
|
|
654
664
|
|
|
655
|
-
// Resolve the asset symbol from --
|
|
665
|
+
// Resolve the asset symbol from --symbol (or its --coin alias), rejecting a
|
|
656
666
|
// duplicated flag. Returns the upper-cased symbol, or '' when neither is set.
|
|
657
667
|
function resolveCoin(options) {
|
|
658
|
-
const
|
|
659
|
-
|
|
668
|
+
const symbol = scalar(options.symbol, 'symbol');
|
|
669
|
+
const coin = scalar(options.coin, 'coin');
|
|
670
|
+
// `--symbol ETH --coin BTC` names the market twice; never pick one silently.
|
|
671
|
+
if (symbol !== undefined && coin !== undefined) {
|
|
672
|
+
throw invalid(`--symbol ${symbol} and --coin ${coin} are the same input (--coin is an alias of --symbol); pass one.`);
|
|
673
|
+
}
|
|
674
|
+
return String(symbol ?? coin ?? '').toUpperCase();
|
|
660
675
|
}
|
|
661
676
|
|
|
662
677
|
// ── Preview + confirmation (--dry-run / --yes) ───────────────────────
|
|
@@ -876,10 +891,10 @@ export function buildPerpCommands(deps = {}) {
|
|
|
876
891
|
|
|
877
892
|
if (!coin || !options.side || options.size === undefined || options.price === undefined) {
|
|
878
893
|
throw new CommandError(
|
|
879
|
-
`Usage: nansen perp order --
|
|
894
|
+
`Usage: nansen perp order --symbol <symbol> --side <buy|sell> --size <amount> --price <price> [options]
|
|
880
895
|
|
|
881
896
|
OPTIONS:
|
|
882
|
-
--
|
|
897
|
+
--symbol Asset symbol (BTC, ETH, etc.; alias --coin)
|
|
883
898
|
--side buy (long) or sell (short)
|
|
884
899
|
--size Position size in base asset units
|
|
885
900
|
--price Limit price (or mark price for market orders)
|
|
@@ -1011,7 +1026,7 @@ OPTIONS:
|
|
|
1011
1026
|
const walletName = scalar(options.wallet, 'wallet');
|
|
1012
1027
|
|
|
1013
1028
|
if (!coin || options.oid === undefined) {
|
|
1014
|
-
throw new CommandError('Usage: nansen perp cancel --
|
|
1029
|
+
throw new CommandError('Usage: nansen perp cancel --symbol <symbol> --oid <orderId> [--wallet <name>] [--dry-run] [--yes]', 'MISSING_PARAM');
|
|
1015
1030
|
}
|
|
1016
1031
|
|
|
1017
1032
|
const oid = parsePositiveInt(options.oid, 'oid');
|
|
@@ -1067,7 +1082,7 @@ OPTIONS:
|
|
|
1067
1082
|
|
|
1068
1083
|
if (!coin || options.size === undefined || options.price === undefined || !options.side) {
|
|
1069
1084
|
throw new CommandError(
|
|
1070
|
-
`Usage: nansen perp close --
|
|
1085
|
+
`Usage: nansen perp close --symbol <symbol> --size <amount> --price <markPrice> --side <buy|sell> [options]
|
|
1071
1086
|
|
|
1072
1087
|
--side buy (closing a short) or sell (closing a long)
|
|
1073
1088
|
--slippage Slippage tolerance (default 0.03 = 3%)
|
|
@@ -1186,7 +1201,7 @@ OPTIONS:
|
|
|
1186
1201
|
const walletName = scalar(options.wallet, 'wallet');
|
|
1187
1202
|
|
|
1188
1203
|
if (!coin || options.leverage === undefined) {
|
|
1189
|
-
throw new CommandError('Usage: nansen perp leverage --
|
|
1204
|
+
throw new CommandError('Usage: nansen perp leverage --symbol <symbol> --leverage <n> [--margin-type cross|isolated] [--wallet <name>] [--dry-run] [--yes]', 'MISSING_PARAM');
|
|
1190
1205
|
}
|
|
1191
1206
|
|
|
1192
1207
|
const marginType = assertMarginType(options['margin-type']);
|
|
@@ -1243,7 +1258,7 @@ OPTIONS:
|
|
|
1243
1258
|
|
|
1244
1259
|
if (!direction || options.amount === undefined) {
|
|
1245
1260
|
throw new CommandError(
|
|
1246
|
-
'Usage: nansen perp transfer --direction <spot-to-perp|perp-to-spot> --amount <usdc> [--wallet <name>]',
|
|
1261
|
+
'Usage: nansen perp transfer --direction <spot-to-perp|perp-to-spot> --amount <usdc> [--wallet <name>] [--dry-run] [--yes]',
|
|
1247
1262
|
'MISSING_PARAM',
|
|
1248
1263
|
);
|
|
1249
1264
|
}
|
|
@@ -1255,13 +1270,41 @@ OPTIONS:
|
|
|
1255
1270
|
throw invalid(`Invalid --direction "${direction}". Must be one of: spot-to-perp, perp-to-spot.`);
|
|
1256
1271
|
}
|
|
1257
1272
|
const amount = parsePositiveNumber(options.amount, 'amount');
|
|
1273
|
+
const guard = resolveExecuteGuard(flags, { env, isTTY });
|
|
1274
|
+
const directionLabel = toPerp ? 'Spot → Perps' : 'Perps → Spot';
|
|
1275
|
+
// Built (pure, nothing signed) before the gate: validates the amount on a
|
|
1276
|
+
// dry run too, and gives the plan the exact amount string that is signed.
|
|
1277
|
+
const signedAmount = buildUsdClassTransferAction({ amount, toPerp, nonce: 0 }).action.amount;
|
|
1278
|
+
// The amount goes through a float and an 8-decimal string; refuse an
|
|
1279
|
+
// input that string can't carry exactly instead of signing another amount.
|
|
1280
|
+
if (normalizeDecimalString(options.amount) !== signedAmount) {
|
|
1281
|
+
throw invalid(`Invalid --amount "${options.amount}". Hyperliquid takes USDC amounts with at most 8 decimal places, and this amount can't be signed exactly; it would be signed as ${signedAmount}.`);
|
|
1282
|
+
}
|
|
1283
|
+
// transfer makes no proxy read before the gate, so check the network here:
|
|
1284
|
+
// otherwise a dry run previews a transfer the real run refuses.
|
|
1285
|
+
assertPerpNetworkSupported();
|
|
1258
1286
|
|
|
1259
1287
|
const wallet = resolveWalletAddress(walletName);
|
|
1260
|
-
|
|
1288
|
+
let ctx = await signingCtxBeforeGate(wallet, guard, log);
|
|
1289
|
+
|
|
1290
|
+
const proceed = await guardPerpAction(apiInstance, {
|
|
1291
|
+
guard,
|
|
1292
|
+
walletAddress: wallet.address,
|
|
1293
|
+
question: 'Submit this transfer to Hyperliquid? [y/N] ',
|
|
1294
|
+
buildPlan: async () => formatPlan('Perp transfer plan — USDC', [
|
|
1295
|
+
['Wallet', wallet.address],
|
|
1296
|
+
['Direction', directionLabel],
|
|
1297
|
+
['Amount', `${signedAmount} USDC`],
|
|
1298
|
+
]),
|
|
1299
|
+
}, guardDeps);
|
|
1300
|
+
if (!proceed) return undefined;
|
|
1301
|
+
ctx ??= await resolveSigningCtx(wallet, log);
|
|
1261
1302
|
|
|
1262
|
-
log(`\n Transfer: ${
|
|
1303
|
+
log(`\n Transfer: ${signedAmount} USDC ${directionLabel}`);
|
|
1263
1304
|
|
|
1264
1305
|
// usdClassTransfer is user-signed: the nonce is embedded in the action.
|
|
1306
|
+
// Taken after the gate, since a prompt can wait long enough for a nonce
|
|
1307
|
+
// taken before it to go stale.
|
|
1265
1308
|
const nonce = hlNonce();
|
|
1266
1309
|
const { action, primaryType, signTypes } = buildUsdClassTransferAction({ amount, toPerp, nonce });
|
|
1267
1310
|
const eip712 = userSignedEip712(primaryType, signTypes, action);
|
|
@@ -1276,15 +1319,31 @@ OPTIONS:
|
|
|
1276
1319
|
// the builder code. order/close auto-fire this on the first trade; this
|
|
1277
1320
|
// command lets a client approve up front. No-op when already approved.
|
|
1278
1321
|
const walletName = scalar(options.wallet, 'wallet');
|
|
1322
|
+
const guard = resolveExecuteGuard(flags, { env, isTTY });
|
|
1279
1323
|
const wallet = resolveWalletAddress(walletName);
|
|
1280
|
-
|
|
1324
|
+
let ctx = await signingCtxBeforeGate(wallet, guard, log);
|
|
1281
1325
|
|
|
1282
1326
|
const builderStatus = await fetchBuilderFee(apiInstance, wallet.address);
|
|
1283
1327
|
if (builderStatus.approved) {
|
|
1328
|
+
// Nothing would be signed, so there is nothing to preview or confirm.
|
|
1284
1329
|
log(`\n Builder fee already approved for ${wallet.address}\n`);
|
|
1285
1330
|
return undefined;
|
|
1286
1331
|
}
|
|
1287
1332
|
|
|
1333
|
+
const proceed = await guardPerpAction(apiInstance, {
|
|
1334
|
+
guard,
|
|
1335
|
+
walletAddress: wallet.address,
|
|
1336
|
+
question: 'Submit this builder-fee approval to Hyperliquid? [y/N] ',
|
|
1337
|
+
buildPlan: async () => formatPlan('Perp builder-fee approval plan', [
|
|
1338
|
+
['Wallet', wallet.address],
|
|
1339
|
+
['Builder', String(builderStatus.builder_address).toLowerCase()],
|
|
1340
|
+
['Max fee rate', `${builderMaxFeeRate(builderStatus.required_fee)} of the order value`],
|
|
1341
|
+
['Effect', 'One-time approval that lets orders carry the Nansen builder code'],
|
|
1342
|
+
]),
|
|
1343
|
+
}, guardDeps);
|
|
1344
|
+
if (!proceed) return undefined;
|
|
1345
|
+
ctx ??= await resolveSigningCtx(wallet, log);
|
|
1346
|
+
|
|
1288
1347
|
log(`\n Approve builder fee: ${wallet.address}`);
|
|
1289
1348
|
await ensureBuilderApproved(apiInstance, builderStatus, ctx);
|
|
1290
1349
|
log('');
|
package/src/privy.js
CHANGED
|
@@ -8,13 +8,12 @@
|
|
|
8
8
|
|
|
9
9
|
import fs from "fs";
|
|
10
10
|
import path from "path";
|
|
11
|
-
import { parsePaymentRequirements } from "./x402.js";
|
|
11
|
+
import { parsePaymentRequirements, rankRequirements } from "./x402.js";
|
|
12
12
|
import { hasSufficientEvmPaymentBalance, hasSufficientSvmPaymentBalance } from "./x402-payment-balance.js";
|
|
13
13
|
import { isEvmNetwork } from "./x402-evm.js";
|
|
14
14
|
import { mkdirPrivateSync, readWalletJson, validateWalletName, withWalletLock, writeWalletJsonAtomic } from "./wallet.js";
|
|
15
15
|
import { evaluatePaymentRequirement, resolvePaymentAmount, resolvePayTo, signWithSessionCharge } from "./x402-policy.js";
|
|
16
16
|
import {
|
|
17
|
-
isSvmNetwork,
|
|
18
17
|
getSolanaRpcUrl,
|
|
19
18
|
fetchRecentBlockhash,
|
|
20
19
|
buildUnsignedSvmTransaction,
|
|
@@ -359,6 +358,11 @@ async function getPrivySolanaWallet(client) {
|
|
|
359
358
|
* Same yield contract as createPaymentSignatures() in x402.js:
|
|
360
359
|
* { signature, network, asset, payment, releaseCharge }
|
|
361
360
|
*
|
|
361
|
+
* Options are tried cheapest first, in the order rankRequirements gives the
|
|
362
|
+
* local and WalletConnect signers. The caller stops at the first payment the
|
|
363
|
+
* server accepts, so server order would let a pricier option be paid while a
|
|
364
|
+
* cheaper one sat in the same response.
|
|
365
|
+
*
|
|
362
366
|
* @param {Response} response - The 402 HTTP response
|
|
363
367
|
* @param {string} url - The original request URL
|
|
364
368
|
* @param {object} [options] - { onCapRefusal }, called with the reason when the session cap refuses an option
|
|
@@ -370,113 +374,151 @@ export async function* createPrivyPaymentSignatures(response, url, options = {})
|
|
|
370
374
|
|
|
371
375
|
const client = getClient();
|
|
372
376
|
|
|
373
|
-
// EVM
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
const typedData = buildEIP712TypedData({
|
|
387
|
-
fromAddress: evmWallet.address,
|
|
388
|
-
requirement,
|
|
389
|
-
});
|
|
390
|
-
|
|
391
|
-
const signed = await signWithSessionCharge(decision, async () => {
|
|
392
|
-
const signResult = await client.ethSignTypedDataV4(evmWallet.id, typedData);
|
|
393
|
-
const signature = signResult.data?.signature || signResult.signature;
|
|
394
|
-
if (!signature) throw new Error('Privy returned no signature');
|
|
395
|
-
|
|
396
|
-
const authorization = {
|
|
397
|
-
from: evmWallet.address,
|
|
398
|
-
to: resolvePayTo(requirement),
|
|
399
|
-
value: resolvePaymentAmount(requirement).toString(),
|
|
400
|
-
validAfter: typedData.message.validAfter.toString(),
|
|
401
|
-
validBefore: typedData.message.validBefore.toString(),
|
|
402
|
-
nonce: typedData.message.nonce,
|
|
403
|
-
};
|
|
404
|
-
|
|
405
|
-
return buildPaymentSignatureHeader({
|
|
406
|
-
signature,
|
|
407
|
-
authorization,
|
|
408
|
-
resource: { url, description: "", mimeType: "" },
|
|
409
|
-
accepted: requirement,
|
|
410
|
-
});
|
|
411
|
-
});
|
|
412
|
-
if (!signed.ok) {
|
|
413
|
-
console.error(`[x402] ${signed.reason}`);
|
|
414
|
-
options.onCapRefusal?.(signed.reason);
|
|
415
|
-
continue;
|
|
416
|
-
}
|
|
417
|
-
|
|
418
|
-
yield { signature: signed.value, network: requirement.network, asset: requirement.asset, payment: decision, releaseCharge: signed.release };
|
|
419
|
-
} catch (err) {
|
|
420
|
-
console.error(`[x402] Privy EVM signing failed for ${requirement.network}: ${err.message}`);
|
|
421
|
-
continue;
|
|
422
|
-
}
|
|
423
|
-
}
|
|
377
|
+
// rankRequirements keeps only EVM and Solana options. Each wallet is looked
|
|
378
|
+
// up once, on the first option for its chain.
|
|
379
|
+
let evmWallet;
|
|
380
|
+
let solWallet;
|
|
381
|
+
let lookupError;
|
|
382
|
+
let signedAny = false;
|
|
383
|
+
const onLookupError = (err) => { if (!lookupError) lookupError = err; };
|
|
384
|
+
for (const requirement of rankRequirements(requirements)) {
|
|
385
|
+
if (isEvmNetwork(requirement.network)) {
|
|
386
|
+
if (evmWallet === undefined) evmWallet = await lookupPrivyWallet('EVM', () => getPrivyEvmWallet(client), onLookupError);
|
|
387
|
+
if (!evmWallet) continue;
|
|
388
|
+
const item = await signPrivyEvmRequirement(client, evmWallet, requirement, url, options);
|
|
389
|
+
if (item) { signedAny = true; yield item; }
|
|
424
390
|
} else {
|
|
425
|
-
|
|
391
|
+
if (solWallet === undefined) solWallet = await lookupPrivyWallet('Solana', () => getPrivySolanaWallet(client), onLookupError);
|
|
392
|
+
if (!solWallet) continue;
|
|
393
|
+
const item = await signPrivySolanaRequirement(client, solWallet, requirement, url, options);
|
|
394
|
+
if (item) { signedAny = true; yield item; }
|
|
426
395
|
}
|
|
427
396
|
}
|
|
397
|
+
// A failed lookup only skips its own chain. When nothing was signed at all,
|
|
398
|
+
// surface the lookup error so a Privy setup problem keeps its reason.
|
|
399
|
+
if (!signedAny && lookupError) throw lookupError;
|
|
400
|
+
}
|
|
428
401
|
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
requirement,
|
|
447
|
-
solWallet.address,
|
|
448
|
-
recentBlockhash,
|
|
449
|
-
);
|
|
450
|
-
|
|
451
|
-
const signed = await signWithSessionCharge(svmDecision, async () => {
|
|
452
|
-
const signResult = await client.signSolanaTransaction(solWallet.id, txBase64);
|
|
453
|
-
const signedTx = signResult.data?.signed_transaction || signResult.signed_transaction;
|
|
454
|
-
if (!signedTx) throw new Error('Privy returned no signed transaction');
|
|
455
|
-
|
|
456
|
-
const payload = {
|
|
457
|
-
x402Version: 2,
|
|
458
|
-
payload: { transaction: signedTx },
|
|
459
|
-
accepted: requirement,
|
|
460
|
-
};
|
|
461
|
-
if (url) {
|
|
462
|
-
payload.resource = { url };
|
|
463
|
-
}
|
|
464
|
-
return Buffer.from(JSON.stringify(payload)).toString("base64");
|
|
465
|
-
});
|
|
466
|
-
if (!signed.ok) {
|
|
467
|
-
console.error(`[x402] ${signed.reason}`);
|
|
468
|
-
options.onCapRefusal?.(signed.reason);
|
|
469
|
-
continue;
|
|
470
|
-
}
|
|
402
|
+
/**
|
|
403
|
+
* Look up the Privy wallet for one chain. A failed lookup only skips that
|
|
404
|
+
* chain's options, so the remaining ranked options on the other chain are
|
|
405
|
+
* still tried. The error is passed to onError so the caller can report it
|
|
406
|
+
* if no option gets signed.
|
|
407
|
+
*/
|
|
408
|
+
async function lookupPrivyWallet(chain, lookup, onError) {
|
|
409
|
+
try {
|
|
410
|
+
const wallet = await lookup();
|
|
411
|
+
if (!wallet) console.error(`[x402] No Privy ${chain} wallet found for payment signing`);
|
|
412
|
+
return wallet || null;
|
|
413
|
+
} catch (err) {
|
|
414
|
+
console.error(`[x402] Privy ${chain} wallet lookup failed: ${err.message}`);
|
|
415
|
+
onError(err);
|
|
416
|
+
return null;
|
|
417
|
+
}
|
|
418
|
+
}
|
|
471
419
|
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
420
|
+
/**
|
|
421
|
+
* Sign one EVM option with the Privy wallet, or return null to skip it.
|
|
422
|
+
*/
|
|
423
|
+
async function signPrivyEvmRequirement(client, evmWallet, requirement, url, options) {
|
|
424
|
+
const decision = evaluatePaymentRequirement(requirement);
|
|
425
|
+
if (!decision.ok) {
|
|
426
|
+
console.error(`[x402] ${decision.reason}`);
|
|
427
|
+
return null;
|
|
428
|
+
}
|
|
429
|
+
// Privy signs an EIP-3009 TransferWithAuthorization. A Permit2 or unknown
|
|
430
|
+
// transfer method needs a different signature, which the server rejects as
|
|
431
|
+
// EIP-3009, so skip it like the WalletConnect signer does.
|
|
432
|
+
const method = requirement.extra?.assetTransferMethod;
|
|
433
|
+
if (method && method !== 'eip3009') {
|
|
434
|
+
console.error(`[x402] Skipping ${requirement.network} option: Privy wallets sign only EIP-3009 payments, not assetTransferMethod "${method}".`);
|
|
435
|
+
return null;
|
|
436
|
+
}
|
|
437
|
+
try {
|
|
438
|
+
if (!await hasSufficientEvmPaymentBalance(requirement, evmWallet.address)) return null;
|
|
439
|
+
const typedData = buildEIP712TypedData({
|
|
440
|
+
fromAddress: evmWallet.address,
|
|
441
|
+
requirement,
|
|
442
|
+
});
|
|
443
|
+
|
|
444
|
+
const signed = await signWithSessionCharge(decision, async () => {
|
|
445
|
+
const signResult = await client.ethSignTypedDataV4(evmWallet.id, typedData);
|
|
446
|
+
const signature = signResult.data?.signature || signResult.signature;
|
|
447
|
+
if (!signature) throw new Error('Privy returned no signature');
|
|
448
|
+
|
|
449
|
+
const authorization = {
|
|
450
|
+
from: evmWallet.address,
|
|
451
|
+
to: resolvePayTo(requirement),
|
|
452
|
+
value: resolvePaymentAmount(requirement).toString(),
|
|
453
|
+
validAfter: typedData.message.validAfter.toString(),
|
|
454
|
+
validBefore: typedData.message.validBefore.toString(),
|
|
455
|
+
nonce: typedData.message.nonce,
|
|
456
|
+
};
|
|
457
|
+
|
|
458
|
+
return buildPaymentSignatureHeader({
|
|
459
|
+
signature,
|
|
460
|
+
authorization,
|
|
461
|
+
resource: { url, description: "", mimeType: "" },
|
|
462
|
+
accepted: requirement,
|
|
463
|
+
});
|
|
464
|
+
});
|
|
465
|
+
if (!signed.ok) {
|
|
466
|
+
console.error(`[x402] ${signed.reason}`);
|
|
467
|
+
options.onCapRefusal?.(signed.reason);
|
|
468
|
+
return null;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
return { signature: signed.value, network: requirement.network, asset: requirement.asset, payment: decision, releaseCharge: signed.release };
|
|
472
|
+
} catch (err) {
|
|
473
|
+
console.error(`[x402] Privy EVM signing failed for ${requirement.network}: ${err.message}`);
|
|
474
|
+
return null;
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/**
|
|
479
|
+
* Sign one Solana option with the Privy wallet, or return null to skip it.
|
|
480
|
+
*/
|
|
481
|
+
async function signPrivySolanaRequirement(client, solWallet, requirement, url, options) {
|
|
482
|
+
const svmDecision = evaluatePaymentRequirement(requirement);
|
|
483
|
+
if (!svmDecision.ok) {
|
|
484
|
+
console.error(`[x402] ${svmDecision.reason}`);
|
|
485
|
+
return null;
|
|
486
|
+
}
|
|
487
|
+
try {
|
|
488
|
+
if (!await hasSufficientSvmPaymentBalance(requirement, solWallet.address)) return null;
|
|
489
|
+
const rpcUrl = getSolanaRpcUrl(requirement.network);
|
|
490
|
+
const recentBlockhash = await fetchRecentBlockhash(rpcUrl);
|
|
491
|
+
|
|
492
|
+
const { txBase64 } = buildUnsignedSvmTransaction(
|
|
493
|
+
requirement,
|
|
494
|
+
solWallet.address,
|
|
495
|
+
recentBlockhash,
|
|
496
|
+
);
|
|
497
|
+
|
|
498
|
+
const signed = await signWithSessionCharge(svmDecision, async () => {
|
|
499
|
+
const signResult = await client.signSolanaTransaction(solWallet.id, txBase64);
|
|
500
|
+
const signedTx = signResult.data?.signed_transaction || signResult.signed_transaction;
|
|
501
|
+
if (!signedTx) throw new Error('Privy returned no signed transaction');
|
|
502
|
+
|
|
503
|
+
const payload = {
|
|
504
|
+
x402Version: 2,
|
|
505
|
+
payload: { transaction: signedTx },
|
|
506
|
+
accepted: requirement,
|
|
507
|
+
};
|
|
508
|
+
if (url) {
|
|
509
|
+
payload.resource = { url };
|
|
477
510
|
}
|
|
478
|
-
|
|
479
|
-
|
|
511
|
+
return Buffer.from(JSON.stringify(payload)).toString("base64");
|
|
512
|
+
});
|
|
513
|
+
if (!signed.ok) {
|
|
514
|
+
console.error(`[x402] ${signed.reason}`);
|
|
515
|
+
options.onCapRefusal?.(signed.reason);
|
|
516
|
+
return null;
|
|
480
517
|
}
|
|
518
|
+
|
|
519
|
+
return { signature: signed.value, network: requirement.network, asset: requirement.asset, payment: svmDecision, releaseCharge: signed.release };
|
|
520
|
+
} catch (err) {
|
|
521
|
+
console.error(`[x402] Privy Solana signing failed for ${requirement.network}: ${err.message}`);
|
|
522
|
+
return null;
|
|
481
523
|
}
|
|
482
524
|
}
|