nansen-cli 1.44.0 → 1.44.2

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.
@@ -4,8 +4,10 @@
4
4
  * bad amounts) before any network call.
5
5
  */
6
6
 
7
+ import crypto from 'crypto';
7
8
  import { validateAddress } from './api.js';
8
9
  import { CHAIN_RPCS } from './rpc-urls.js';
10
+ import { base58Encode } from './wallet.js';
9
11
  import { parseTransactionMessage, resolveStaticAccount } from './solana-tx.js';
10
12
  import { SOL_SENTINEL } from './solana-simulation.js';
11
13
  import { EVM_NATIVE_SENTINEL } from './swap-simulation.js';
@@ -20,10 +22,20 @@ const SPL_TOKEN_PROGRAMS = new Set([
20
22
  'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',
21
23
  'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb',
22
24
  ]);
25
+ const SPL_TRANSFER = 3;
23
26
  const SPL_APPROVE = 4;
24
27
  const SPL_SET_AUTHORITY = 6;
25
28
  const SPL_CLOSE_ACCOUNT = 9;
29
+ const SPL_TRANSFER_CHECKED = 12;
26
30
  const SPL_APPROVE_CHECKED = 13;
31
+ const SPL_INITIALIZE_ACCOUNT = 1;
32
+ const SPL_INITIALIZE_ACCOUNT2 = 16;
33
+ const SPL_INITIALIZE_ACCOUNT3 = 18;
34
+
35
+ const SYSTEM_PROGRAM = '11111111111111111111111111111111';
36
+ const SYSTEM_INSTR_TRANSFER = 2;
37
+ const SYSTEM_INSTR_CREATE_ACCOUNT_WITH_SEED = 3;
38
+ const WSOL_MINT = 'So11111111111111111111111111111111111111112';
27
39
 
28
40
  const COMPUTE_BUDGET_PROGRAM = 'ComputeBudget111111111111111111111111111111';
29
41
  const COMPUTE_BUDGET_SET_UNIT_LIMIT = 2;
@@ -1225,7 +1237,7 @@ const NATIVE_SIBLING_DUST_LAMPORTS = 3_000_000n; // ~0.003 SOL
1225
1237
  // leaves the wallet as native SOL regardless of whether SOL is the input,
1226
1238
  // output, or an uninvolved sibling of the swap, so all three assertions below
1227
1239
  // need the same combined slack or a legitimate high-priority-fee trade false-blocks.
1228
- const NATIVE_FEE_RENT_SLACK_LAMPORTS = MAX_PRIORITY_FEE_LAMPORTS + NATIVE_SIBLING_DUST_LAMPORTS;
1240
+ export const NATIVE_FEE_RENT_SLACK_LAMPORTS = MAX_PRIORITY_FEE_LAMPORTS + NATIVE_SIBLING_DUST_LAMPORTS;
1229
1241
 
1230
1242
  /**
1231
1243
  * The Solana sibling of assertSwapOutcome. Solana signs the aggregator's
@@ -1477,6 +1489,218 @@ export function assertSolanaSwapOutcome(request, quote, sim, { slippage, sibling
1477
1489
  return { verified: true, inputAssertionSkipped: inputIsNative, outputAssertionSkipped: isBridge };
1478
1490
  }
1479
1491
 
1492
+ /**
1493
+ * Verify a limit-order DEPOSIT's simulated wallet effect against intent.
1494
+ * Fails closed (code LIMIT_ORDER_OUTCOME_MISMATCH) unless:
1495
+ * 1. the input token leaves the wallet by EXACTLY `amount` for an SPL input, or
1496
+ * within `amount` ± NATIVE_FEE_RENT_SLACK_LAMPORTS for a native-SOL input
1497
+ * (two-sided: upper bound caps the drain, lower bound rejects a partial reroute), and
1498
+ * 2. no token OTHER than the input leaves the wallet (native-SOL dust tolerated).
1499
+ * NOTE: this bounds MAGNITUDE, not destination. The create command pairs it with
1500
+ * assertLimitOrderDepositDestination so a wallet-authorized SPL transfer of the
1501
+ * deposited asset must land in the vault's token account.
1502
+ * There is no output leg — the deposit funds the vault, nothing returns to the wallet.
1503
+ *
1504
+ * @param {{deltas: Record<string, bigint|string|number>}} sim - simulateSolanaAssetChanges result
1505
+ * @param {{inputMint: string, amount: bigint|string|number}} ctx
1506
+ * (walletAddress is NOT needed here — the sim already keyed its deltas relative to the wallet)
1507
+ * @throws {Error} with `code = 'LIMIT_ORDER_OUTCOME_MISMATCH'` on any failed assertion.
1508
+ */
1509
+ export function assertLimitOrderDepositOutcome(sim, { inputMint, amount }) {
1510
+ const fail = (detail) => {
1511
+ const e = new Error(`Limit-order deposit outcome mismatch (LIMIT_ORDER_OUTCOME_MISMATCH): ${detail} Refusing to sign.`);
1512
+ e.code = 'LIMIT_ORDER_OUTCOME_MISMATCH';
1513
+ return e;
1514
+ };
1515
+
1516
+ if (!sim || typeof sim !== 'object' || sim.deltas == null) {
1517
+ throw fail('simulation returned no asset changes to verify.');
1518
+ }
1519
+
1520
+ const deltas = {};
1521
+ for (const [k, v] of Object.entries(sim.deltas)) {
1522
+ let amt;
1523
+ try {
1524
+ amt = typeof v === 'bigint' ? v : BigInt(v);
1525
+ } catch {
1526
+ throw fail(`simulated delta for ${k} (${v}) is not an integer.`);
1527
+ }
1528
+ deltas[k] = amt;
1529
+ }
1530
+
1531
+ const foldNative = (mint) => (mint && SOLANA_NATIVE_SOL_ALIASES.has(mint) ? SOL_SENTINEL : mint);
1532
+ const inputAsset = foldNative(inputMint);
1533
+ if (!inputAsset) {
1534
+ throw fail('deposit is missing the input token address.');
1535
+ }
1536
+ const inputIsNative = inputAsset === SOL_SENTINEL;
1537
+
1538
+ let cap;
1539
+ try {
1540
+ cap = BigInt(amount);
1541
+ } catch {
1542
+ throw fail(`deposit amount (${amount}) is not an integer.`);
1543
+ }
1544
+
1545
+ const effectiveCap = inputIsNative ? cap + NATIVE_FEE_RENT_SLACK_LAMPORTS : cap;
1546
+ const inputDelta = deltas[inputAsset] || 0n;
1547
+ const outflow = inputDelta < 0n ? -inputDelta : 0n;
1548
+
1549
+ // --- magnitude bound: UPPER ---
1550
+ if (outflow > effectiveCap) {
1551
+ throw fail(`the input token (${inputAsset}) left the wallet by ${outflow}, exceeding the deposit amount (${cap}${inputIsNative ? ` plus fee/rent slack` : ''}).`);
1552
+ }
1553
+
1554
+ // --- magnitude bound: LOWER (floor) ---
1555
+ // The deposit must actually escrow the full `amount`; a partial outflow means the tx
1556
+ // rerouted or under-funded the deposit. Two cases, because native SOL carries fee/rent noise:
1557
+ if (inputIsNative) {
1558
+ // A native deposit's outflow is amount + base/priority fee + net ATA rent, so it is
1559
+ // normally ABOVE cap; the floor mainly catches a grossly under-funded deposit. But for
1560
+ // a tiny `amount` (<= the slack itself) the (cap - slack) window swallows the entire
1561
+ // requested amount, so outflow magnitude alone can no longer distinguish a genuine
1562
+ // (if undersized) deposit from an unrelated fee-only outflow that never escrowed
1563
+ // anything — admitting any nonzero outflow there would reopen exactly that gap.
1564
+ // Fail closed instead of trying to verify an amount the slack makes unverifiable.
1565
+ if (cap <= NATIVE_FEE_RENT_SLACK_LAMPORTS) {
1566
+ throw fail(`the deposit amount (${cap}) is too small relative to the fee/rent slack (${NATIVE_FEE_RENT_SLACK_LAMPORTS}) to verify by outflow magnitude.`);
1567
+ }
1568
+ const floor = cap - NATIVE_FEE_RENT_SLACK_LAMPORTS;
1569
+ if (outflow < floor) {
1570
+ throw fail(`the input token (${inputAsset}) left the wallet by only ${outflow}, below the deposit amount (${cap} minus fee/rent slack).`);
1571
+ }
1572
+ } else {
1573
+ // SPL deposit escrows EXACTLY `amount`; no fee is taken in the token, so the delta is
1574
+ // exact. Require equality — any shortfall is a partial drain / reroute (fail closed).
1575
+ if (outflow !== cap) {
1576
+ throw fail(`the input token (${inputAsset}) left the wallet by ${outflow}, not the exact deposit amount (${cap}).`);
1577
+ }
1578
+ }
1579
+
1580
+ // --- sibling loop: no OTHER token leaves the wallet (native-SOL dust tolerated) ---
1581
+ for (const [token, delta] of Object.entries(deltas)) {
1582
+ if (token === inputAsset) continue;
1583
+ if (delta >= 0n) continue;
1584
+ const dust = token === SOL_SENTINEL ? NATIVE_FEE_RENT_SLACK_LAMPORTS : 0n;
1585
+ if (-delta > dust) {
1586
+ throw fail(`a token other than the one you are depositing (${token}) left the wallet (delta ${delta}).`);
1587
+ }
1588
+ }
1589
+
1590
+ return { verified: true };
1591
+ }
1592
+
1593
+ /**
1594
+ * Verify a limit-order CANCEL's simulated wallet effect. A withdrawal is authorised by the
1595
+ * vault PDA and only returns funds TO the wallet, so NO token may leave the wallet except
1596
+ * native-SOL fee/rent dust, AND the order's own input asset must be refunded — by the full
1597
+ * expected remaining amount when it is known (`amount`), otherwise at least a genuine
1598
+ * inflow (> 0). Binding to the amount matters: a crafted "cancel" that redirects nearly all
1599
+ * the escrow elsewhere and refunds only a single dust unit of the right mint (or produces an
1600
+ * unrelated inflow, e.g. closing an empty token account back to the wallet for its rent)
1601
+ * would satisfy a bare > 0 check while draining the deposit. Fails closed otherwise.
1602
+ *
1603
+ * NOTE: this bounds MAGNITUDE (the right asset returns in the right amount), not destination
1604
+ * — a redirect of the correct asset+amount to a non-wallet address first, followed by a
1605
+ * genuine top-up of that same asset back to the wallet from elsewhere, would still pass.
1606
+ * That is closed by the vault-destination binding fast-follow, not here.
1607
+ *
1608
+ * @param {{deltas: Record<string, bigint|string|number>}} sim
1609
+ * (no walletAddress in ctx — the sim already keyed its deltas relative to the wallet)
1610
+ * @param {{inputMint: string, amount?: bigint|string|number}} ctx - the order's own deposited
1611
+ * asset (the refund must land here) and its expected remaining refund in base units. When
1612
+ * `amount` is OMITTED the check falls back to requiring a positive inflow only — this fallback
1613
+ * is DELIBERATELY WEAKER than the magnitude bind and is not a safe default: a caller that can
1614
+ * know the expected refund MUST pass it and fail closed when it is absent (as the cancel
1615
+ * command does — see classifyCancelRefund in limit-order.js), rather than relying on this
1616
+ * bare-inflow path, which admits a dust-refund/redirect it cannot catch. A non-null `amount`
1617
+ * that won't parse to an integer is a call-site bug and throws (never silently degrades).
1618
+ * @throws {Error} with `code = 'LIMIT_ORDER_OUTCOME_MISMATCH'` on any failed assertion.
1619
+ */
1620
+ export function assertLimitOrderCancelOutcome(sim, { inputMint, amount } = {}) {
1621
+ const fail = (detail) => {
1622
+ const e = new Error(`Limit-order cancel outcome mismatch (LIMIT_ORDER_OUTCOME_MISMATCH): ${detail} Refusing to sign.`);
1623
+ e.code = 'LIMIT_ORDER_OUTCOME_MISMATCH';
1624
+ return e;
1625
+ };
1626
+
1627
+ if (!inputMint) {
1628
+ throw fail('the order\'s input mint is missing; cannot verify which asset the withdrawal must refund.');
1629
+ }
1630
+
1631
+ if (!sim || typeof sim !== 'object' || sim.deltas == null) {
1632
+ throw fail('simulation returned no asset changes to verify.');
1633
+ }
1634
+
1635
+ const deltas = {};
1636
+ for (const [k, v] of Object.entries(sim.deltas)) {
1637
+ let amt;
1638
+ try {
1639
+ amt = typeof v === 'bigint' ? v : BigInt(v);
1640
+ } catch {
1641
+ throw fail(`simulated delta for ${k} (${v}) is not an integer.`);
1642
+ }
1643
+ deltas[k] = amt;
1644
+ }
1645
+
1646
+ const foldNative = (mint) => (mint && SOLANA_NATIVE_SOL_ALIASES.has(mint) ? SOL_SENTINEL : mint);
1647
+ const inputAsset = foldNative(inputMint);
1648
+
1649
+ for (const [token, delta] of Object.entries(deltas)) {
1650
+ if (delta >= 0n) continue;
1651
+ const dust = token === SOL_SENTINEL ? NATIVE_FEE_RENT_SLACK_LAMPORTS : 0n;
1652
+ if (-delta > dust) {
1653
+ throw fail(`a token (${token}) left your wallet during cancellation (delta ${delta}); a withdrawal should only return funds to you.`);
1654
+ }
1655
+ }
1656
+
1657
+ const inflow = deltas[inputAsset] || 0n;
1658
+ if (inflow <= 0n) {
1659
+ throw fail(`the withdrawal produced no inflow of the deposited asset (${inputAsset}) to your wallet; a cancel must return your deposited funds.`);
1660
+ }
1661
+
1662
+ // Bind the refund MAGNITUDE to the order's expected remaining input when it is known.
1663
+ // Without this, the > 0 check above is satisfied by a single dust unit, so a crafted
1664
+ // cancel could reroute nearly the whole escrow and still verify.
1665
+ // A caller either KNOWS the expected refund (pass it) or genuinely doesn't (omit it, taking
1666
+ // the deliberately weaker bare-inflow path — see the @param note). A non-null value that
1667
+ // won't parse is neither: it's a bug at the call site, so fail closed rather than silently
1668
+ // drop to the weak path and hand back the stronger-sounding guarantee the name implies.
1669
+ let expected;
1670
+ if (amount != null) {
1671
+ try {
1672
+ expected = BigInt(amount);
1673
+ } catch {
1674
+ throw fail(`the expected refund amount (${amount}) is not an integer; cannot verify refund magnitude.`);
1675
+ }
1676
+ }
1677
+ if (expected != null && expected > 0n) {
1678
+ if (inputAsset === SOL_SENTINEL) {
1679
+ // Net native inflow is the refund minus this tx's fee, plus any temp-WSOL rent
1680
+ // returned, so it sits within ± fee/rent slack of the expected refund. Two-sided —
1681
+ // BUT when the expected refund is itself <= that slack, the lower bound
1682
+ // (expected - slack) collapses to <= 0 and the band degenerates to the bare
1683
+ // inflow > 0 floor above: a single dust lamport would verify while the rest of the
1684
+ // escrow is rerouted elsewhere. Fail closed instead, exactly as the deposit asserter
1685
+ // does for an amount the slack makes unverifiable, rather than admit a floor below a
1686
+ // meaningful bound.
1687
+ if (expected <= NATIVE_FEE_RENT_SLACK_LAMPORTS) {
1688
+ throw fail(`the expected remaining refund (${expected}) is too small relative to the fee/rent slack (${NATIVE_FEE_RENT_SLACK_LAMPORTS}) to verify by native-SOL inflow magnitude.`);
1689
+ }
1690
+ const lo = expected - NATIVE_FEE_RENT_SLACK_LAMPORTS;
1691
+ const hi = expected + NATIVE_FEE_RENT_SLACK_LAMPORTS;
1692
+ if (inflow < lo || inflow > hi) {
1693
+ throw fail(`the withdrawal returned ${inflow} of native SOL, outside the expected remaining refund (${expected} ± fee/rent slack); a cancel must return the full remaining deposit.`);
1694
+ }
1695
+ } else if (inflow !== expected) {
1696
+ // SPL escrow returns EXACTLY the remaining input — no fee is taken in the token.
1697
+ throw fail(`the withdrawal returned ${inflow} of the deposited asset (${inputAsset}), not the expected remaining refund (${expected}); a cancel must return the full remaining deposit.`);
1698
+ }
1699
+ }
1700
+
1701
+ return { verified: true };
1702
+ }
1703
+
1480
1704
  /**
1481
1705
  * Statically inspect a Solana transaction's instructions for drain vectors a
1482
1706
  * balance-delta simulation can't see — granting a token delegate, changing a
@@ -1505,10 +1729,16 @@ export function assertSolanaSwapOutcome(request, quote, sim, { slippage, sibling
1505
1729
  * proceeds) when no simulation RPC endpoint is configured, so this static
1506
1730
  * check plus the metadata binding remain the ONLY transaction-level guards
1507
1731
  * whenever a sim RPC is unavailable. Limit-order vault deposit/cancel
1508
- * (limit-order.js) call only this static check, not verifySolanaSwapOutcome —
1509
- * they have no swap quote (no declared input/output pair) to bind an outcome
1510
- * check against, so the sibling-transfer gap described above is still open
1511
- * there; tracked as a follow-up, not covered here.
1732
+ * (limit-order.js) have no swap quote (no declared input/output pair), so they
1733
+ * use their own outcome asserters instead — assertLimitOrderDepositOutcome and
1734
+ * assertLimitOrderCancelOutcome, run via verifyLimitOrderOutcome immediately
1735
+ * after this check — which close the sibling-transfer gap and bound the
1736
+ * deposit/withdrawal magnitude the same way assertSolanaSwapOutcome does for
1737
+ * swaps. What those asserters cannot see is *destination*: a deposit that
1738
+ * moves exactly `amount` of the input token to a non-vault address still
1739
+ * passes, since balance-delta simulation of the wallet's own accounts can't
1740
+ * tell where funds landed. That is tracked as a separate fast-follow (binding
1741
+ * the vault's token-account destination), not covered here.
1512
1742
  *
1513
1743
  * Within that scope, the SPL Token program requires the *authority* of
1514
1744
  * Approve/ApproveChecked/SetAuthority/CloseAccount to sign the transaction,
@@ -1631,3 +1861,178 @@ export function assertSolanaInstructionsSafe(txBase64, { walletAddress } = {}) {
1631
1861
 
1632
1862
  return parsed;
1633
1863
  }
1864
+
1865
+ /**
1866
+ * Statically bind a limit-order deposit's wallet-sourced outflow to a token
1867
+ * account provably derived from the trusted vault owner. This closes the
1868
+ * destination gap balance-delta simulation cannot see: a tx can spend exactly
1869
+ * the requested amount from the wallet while sending it to an attacker's
1870
+ * account.
1871
+ *
1872
+ * The real on-chain shape (confirmed by a live create round-trip) is NOT the
1873
+ * vault's canonical ATA. Jupiter Trigger V2 funds each order through a fresh
1874
+ * per-order token account created in the same transaction via
1875
+ * System::CreateAccountWithSeed(base = vaultOwner, seed = <per-order>,
1876
+ * owner = Token program), then:
1877
+ * - SPL input → TransferChecked / Transfer of the input token into it, or
1878
+ * - native SOL → System::Transfer of lamports into it, then SyncNative.
1879
+ * So the destination is per-order and changes every craft; we can't pin a fixed
1880
+ * address. Instead we recompute create_with_seed(base, seed, owner) from the
1881
+ * transaction's own CreateAccountWithSeed instruction, require base == the
1882
+ * trusted vaultOwner, and bind every wallet-sourced transfer to that recomputed
1883
+ * account. This is stronger than an ATA equality check: the destination is
1884
+ * provably seeded off the vault the backend told us to deposit into.
1885
+ *
1886
+ * This check is intentionally limit-order-specific; generic swaps cannot
1887
+ * require a single destination.
1888
+ */
1889
+ export function assertLimitOrderDepositDestination(txBase64, { walletAddress, inputMint, vaultOwner } = {}) {
1890
+ const fail = (detail) => {
1891
+ const e = new Error(`Limit-order deposit destination mismatch (LIMIT_ORDER_DESTINATION_MISMATCH): ${detail} Refusing to sign.`);
1892
+ e.code = 'LIMIT_ORDER_DESTINATION_MISMATCH';
1893
+ return e;
1894
+ };
1895
+
1896
+ if (!walletAddress) throw fail('missing signing wallet address.');
1897
+ if (!inputMint) throw fail('missing deposit input mint.');
1898
+ if (!vaultOwner) throw fail('missing vault owner address.');
1899
+
1900
+ const parsed = parseTransactionMessage(txBase64);
1901
+ const accountAt = (ix, position) => resolveStaticAccount(parsed, ix.accountIndexes[position]);
1902
+ const walletAuthorizes = (ix, authorityPos) => {
1903
+ if (accountAt(ix, authorityPos) === null) return true;
1904
+ for (let i = authorityPos; i < ix.accountIndexes.length; i++) {
1905
+ if (accountAt(ix, i) === walletAddress) return true;
1906
+ }
1907
+ return false;
1908
+ };
1909
+
1910
+ const expectedMint = SOLANA_NATIVE_SOL_ALIASES.has(inputMint) ? WSOL_MINT : inputMint;
1911
+
1912
+ // Pass 1: collect the token accounts this transaction creates via
1913
+ // System::CreateAccountWithSeed seeded off the trusted vault owner, plus the
1914
+ // matching SPL InitializeAccount* owner/mint assignment. A seeded address
1915
+ // alone is not enough: the token-account authority must also be the trusted
1916
+ // vault owner, otherwise the deposit can be withdrawn by whoever controls the
1917
+ // initialized account.
1918
+ const vaultSeededAccounts = new Set();
1919
+ const initializedAccounts = new Map();
1920
+ for (const ix of parsed.instructions) {
1921
+ const programId = resolveStaticAccount(parsed, ix.programIdIndex);
1922
+ if (programId === SYSTEM_PROGRAM) {
1923
+ if (ix.data.length < 4 || ix.data.readUInt32LE(0) !== SYSTEM_INSTR_CREATE_ACCOUNT_WITH_SEED) continue;
1924
+ // Layout: u32 index | 32 base | u64 seedLen | seed | u64 lamports | u64 space | 32 owner
1925
+ let off = 4;
1926
+ const need = (n) => { if (off + n > ix.data.length) throw fail('malformed CreateAccountWithSeed instruction.'); };
1927
+ need(32); const base = ix.data.subarray(off, off + 32); off += 32;
1928
+ need(8); const seedLen = Number(ix.data.readBigUInt64LE(off)); off += 8;
1929
+ need(seedLen); const seed = ix.data.subarray(off, off + seedLen); off += seedLen;
1930
+ need(16); off += 16; // skip lamports (u64) + space (u64)
1931
+ need(32); const owner = ix.data.subarray(off, off + 32);
1932
+ if (base58Encode(base) !== vaultOwner) continue; // not seeded off our vault
1933
+ if (!SPL_TOKEN_PROGRAMS.has(base58Encode(owner))) continue; // not a token account
1934
+ // create_with_seed(base, seed, owner) = base58(sha256(base || seed || owner)).
1935
+ const derived = base58Encode(crypto.createHash('sha256').update(Buffer.concat([base, seed, owner])).digest());
1936
+ // The account the instruction creates (index 1) must equal the recomputed
1937
+ // address; a mismatch means a malformed/crafted instruction — fail closed.
1938
+ const created = accountAt(ix, 1);
1939
+ if (created !== null && created !== derived) {
1940
+ throw fail('CreateAccountWithSeed target does not match its base/seed/owner derivation.');
1941
+ }
1942
+ vaultSeededAccounts.add(derived);
1943
+ continue;
1944
+ }
1945
+
1946
+ if (!SPL_TOKEN_PROGRAMS.has(programId) || ix.data.length === 0) continue;
1947
+ const discriminator = ix.data[0];
1948
+ let account;
1949
+ let mint;
1950
+ let owner;
1951
+
1952
+ if (discriminator === SPL_INITIALIZE_ACCOUNT) {
1953
+ // InitializeAccount: accounts [account, mint, owner, rent].
1954
+ account = accountAt(ix, 0);
1955
+ mint = accountAt(ix, 1);
1956
+ owner = accountAt(ix, 2);
1957
+ } else if (discriminator === SPL_INITIALIZE_ACCOUNT2 || discriminator === SPL_INITIALIZE_ACCOUNT3) {
1958
+ // InitializeAccount2/3: accounts [account, mint, ...], data [disc, owner pubkey].
1959
+ if (ix.data.length < 33) throw fail('malformed InitializeAccount owner field.');
1960
+ account = accountAt(ix, 0);
1961
+ mint = accountAt(ix, 1);
1962
+ owner = base58Encode(ix.data.subarray(1, 33));
1963
+ } else {
1964
+ continue;
1965
+ }
1966
+
1967
+ if (account === null || mint === null || owner === null) {
1968
+ throw fail('token account initializer uses an address only resolvable via an address lookup table.');
1969
+ }
1970
+ initializedAccounts.set(account, { mint, owner });
1971
+ }
1972
+
1973
+ // Pass 2: every wallet-sourced transfer of value must land in a vault-seeded
1974
+ // account that is also initialized in this transaction with the vault as its
1975
+ // token-account authority. Covers both deposit shapes — SPL token transfers
1976
+ // and the native-SOL System::Transfer that funds a wrapped-SOL order account.
1977
+ const requireTrustedDestination = (destination, label) => {
1978
+ if (!vaultSeededAccounts.has(destination)) {
1979
+ throw fail(`wallet-authorized ${label} sends funds to ${destination || 'an address only resolvable via an address lookup table'} instead of a vault-seeded deposit account.`);
1980
+ }
1981
+ const initialized = initializedAccounts.get(destination);
1982
+ if (!initialized) {
1983
+ throw fail(`wallet-authorized ${label} sends funds to ${destination} before verifying it is initialized with the trusted vault authority.`);
1984
+ }
1985
+ if (!tokensEqual(initialized.mint, expectedMint, 'solana')) {
1986
+ throw fail(`vault-seeded token account is initialized for mint ${initialized.mint} instead of deposit mint ${expectedMint}.`);
1987
+ }
1988
+ if (initialized.owner !== vaultOwner) {
1989
+ throw fail(`vault-seeded token account authority is ${initialized.owner} instead of expected vault owner ${vaultOwner}.`);
1990
+ }
1991
+ };
1992
+ let sawValidDepositTransfer = false;
1993
+
1994
+ for (const ix of parsed.instructions) {
1995
+ const programId = resolveStaticAccount(parsed, ix.programIdIndex);
1996
+ if (!programId) {
1997
+ throw fail('transaction invokes a program only resolvable via an address lookup table, so transfer destinations cannot be verified.');
1998
+ }
1999
+
2000
+ if (programId === SYSTEM_PROGRAM) {
2001
+ if (ix.data.length < 4) continue;
2002
+ if (ix.data.readUInt32LE(0) !== SYSTEM_INSTR_TRANSFER) continue;
2003
+ // System::Transfer accounts: [from (signer), to]. `from` must be a signer,
2004
+ // so it can never be ALT-resolved; null means a malformed tx — fail closed.
2005
+ const from = accountAt(ix, 0);
2006
+ if (from === null) throw fail('native transfer source is unresolvable (malformed transaction).');
2007
+ if (from !== walletAddress) continue; // not our funds
2008
+ requireTrustedDestination(accountAt(ix, 1), 'native transfer');
2009
+ sawValidDepositTransfer = true;
2010
+ continue;
2011
+ }
2012
+
2013
+ if (!SPL_TOKEN_PROGRAMS.has(programId) || ix.data.length === 0) continue;
2014
+ const discriminator = ix.data[0];
2015
+ if (discriminator === SPL_TRANSFER) {
2016
+ // Classic Transfer carries no mint in its account list, so we bind only the
2017
+ // destination. Not a weakness: the destination is a vault-seeded account and
2018
+ // the balance-delta gate still bounds which token and how much leave the
2019
+ // wallet. Use TransferChecked (below) for instruction-level mint binding.
2020
+ if (!walletAuthorizes(ix, 2)) continue;
2021
+ requireTrustedDestination(accountAt(ix, 1), 'token transfer');
2022
+ sawValidDepositTransfer = true;
2023
+ } else if (discriminator === SPL_TRANSFER_CHECKED) {
2024
+ if (!walletAuthorizes(ix, 3)) continue;
2025
+ const mint = accountAt(ix, 1);
2026
+ if (!tokensEqual(mint, expectedMint, 'solana')) {
2027
+ throw fail(`wallet-authorized TransferChecked uses mint ${mint || 'an address only resolvable via an address lookup table'} instead of deposit mint ${expectedMint}.`);
2028
+ }
2029
+ requireTrustedDestination(accountAt(ix, 2), 'TransferChecked');
2030
+ sawValidDepositTransfer = true;
2031
+ }
2032
+ }
2033
+
2034
+ if (!sawValidDepositTransfer) {
2035
+ throw fail('no wallet-authorized deposit transfer into a vault-seeded account was detected.');
2036
+ }
2037
+ return { verified: true };
2038
+ }
package/src/trading.js CHANGED
@@ -288,10 +288,11 @@ export async function executeTransaction(params, { retries = 2, retryDelayMs = 1
288
288
 
289
289
  if (!parsed) {
290
290
  // Non-JSON on a sub-500 status (a Cloudflare challenge or HTML error
291
- // page). Still uninterpretable after the POST went out, so fail closed.
291
+ // page). A clean sub-500 HTTP response is a definitive edge/backend
292
+ // rejection, so it stays nonfatal and leaves the quote reusable.
292
293
  lastError = Object.assign(
293
294
  new Error(`Execute API returned non-JSON response (status ${res.status}). This may be a Cloudflare challenge or server error.`),
294
- { code: 'BROADCAST_FAILED', status: res.status, details: text.slice(0, 200) }
295
+ { code: 'EXECUTE_ERROR', status: res.status, details: text.slice(0, 200) }
295
296
  );
296
297
  throw lastError;
297
298
  }
@@ -2212,9 +2213,19 @@ CROSS-CHAIN NOTES (when using --to-chain):
2212
2213
  let walletProvider = 'local';
2213
2214
  let privyWalletIds = null;
2214
2215
  if (isWalletConnect) {
2215
- walletAddress = await getWalletConnectAddress(chainType);
2216
+ // Scoped to this chain's ID (see getWalletConnectAddress's chainId
2217
+ // param): a session approved only for a different EVM chain must
2218
+ // not be treated as valid here just because it's "some eip155:*"
2219
+ // account -- EVM addresses are identical across chains. chainId is
2220
+ // only ever passed for 'evm': Solana's chainConfig.chainId (501) is
2221
+ // not a CAIP-2 EIP-155 chain ID, and getWalletConnectAddress's own
2222
+ // Solana branch already does its own exact match unconditionally --
2223
+ // passing 501 through here would break it, not narrow it further.
2224
+ walletAddress = chainType === 'evm'
2225
+ ? await getWalletConnectAddress(chainType, chainConfig.chainId)
2226
+ : await getWalletConnectAddress(chainType);
2216
2227
  if (!walletAddress) {
2217
- throw new CommandError('No WalletConnect session active. Run: walletconnect connect', 'NO_WALLET');
2228
+ throw new CommandError(`No WalletConnect session active for chain "${chain}". Run: walletconnect connect`, 'NO_WALLET');
2218
2229
  }
2219
2230
  } else if (walletName) {
2220
2231
  const wallet = showWallet(walletName);
@@ -2563,10 +2574,20 @@ EXAMPLES:
2563
2574
 
2564
2575
  exported = exportWallet(effectiveWalletName, password);
2565
2576
  } else {
2566
- // Verify WalletConnect session is still active and address matches quote
2567
- const wcAddress = await getWalletConnectAddress(chainType);
2577
+ // Verify WalletConnect session is still active, approved for this
2578
+ // chain, and its address matches the quote. Chain-scoped (see
2579
+ // getWalletConnectAddress's chainId param) because an address
2580
+ // match alone can't tell a session on the right chain from one on
2581
+ // the wrong chain -- EVM addresses are identical across chains.
2582
+ // chainId is only ever passed for 'evm': Solana's chainConfig.chainId
2583
+ // (501) is not a CAIP-2 EIP-155 chain ID, and getWalletConnectAddress's
2584
+ // own Solana branch already does its own exact match unconditionally --
2585
+ // passing 501 through here would break it, not narrow it further.
2586
+ const wcAddress = chainType === 'evm'
2587
+ ? await getWalletConnectAddress(chainType, chainConfig.chainId)
2588
+ : await getWalletConnectAddress(chainType);
2568
2589
  if (!wcAddress) {
2569
- throw new CommandError('No WalletConnect session active. Run: walletconnect connect', 'NO_WALLET');
2590
+ throw new CommandError(`No WalletConnect session active for chain "${chain}". Run: walletconnect connect`, 'NO_WALLET');
2570
2591
  }
2571
2592
  // Check address matches the one used during quoting
2572
2593
  const quoteWallet = quoteData.response?.quotes?.[0]?.transaction?.from
@@ -3026,14 +3047,24 @@ EXAMPLES:
3026
3047
  requestId = currentQuote.metadata?.requestId;
3027
3048
 
3028
3049
  } else if (isWalletConnect) {
3029
- // EVM via WalletConnect: wallet signs and may broadcast
3030
- const wcAddress = await getWalletConnectAddress(chainType);
3031
- // A session dropped mid-execute returns null here. Without this
3050
+ // EVM via WalletConnect: wallet signs and may broadcast.
3051
+ // chainType is always 'evm' here (unguarded, unlike the two
3052
+ // other call sites) -- the Solana WalletConnect path is fully
3053
+ // handled above in the `if (chainConfig.type === 'solana')`
3054
+ // branch, so this `else if` is only ever reached for EVM.
3055
+ // Scoped to this chain's ID, not just "any EVM account" -- a
3056
+ // session approved only for a different chain must not sign
3057
+ // here. EVM addresses are identical across chains, so the
3058
+ // address-based checks below (assertQuoteMatchesRequest) can't
3059
+ // catch a session connected to the wrong chain on their own.
3060
+ const wcAddress = await getWalletConnectAddress(chainType, chainConfig.chainId);
3061
+ // A session dropped mid-execute, or one that's connected but not
3062
+ // approved for this chain, returns null here. Without this
3032
3063
  // guard a null address would fall through to assertQuoteMatchesRequest,
3033
3064
  // whose `request.walletAddress && walletAddress` condition would
3034
3065
  // silently skip the signer-binding check. Fail closed instead.
3035
3066
  if (!wcAddress) {
3036
- throw new CommandError('WalletConnect session lost during execute. Reconnect with `walletconnect connect` and retry.', 'NO_WALLET');
3067
+ throw new CommandError('No WalletConnect session for this chain. Reconnect with `walletconnect connect` and retry.', 'NO_WALLET');
3037
3068
  }
3038
3069
  const isNative = isNativeToken(currentQuote.inputMint);
3039
3070
 
package/src/transfer.js CHANGED
@@ -116,8 +116,9 @@ function bigIntToHex(n) {
116
116
  // ============= EVM Transaction =============
117
117
 
118
118
  async function buildEvmTransaction({ to, amount, token, privateKey, chain, max = false }) {
119
+ const chainId = CHAIN_IDS[chain];
120
+ if (!chainId) throw new Error(`Unsupported chain: ${chain} (no chain ID configured for EVM transfers)`);
119
121
  const rpcUrl = CHAIN_RPCS[chain] || CHAIN_RPCS.evm;
120
- const chainId = CHAIN_IDS[chain] || 1;
121
122
 
122
123
  // Derive address and buffer for signing
123
124
  const privBuf = Buffer.from(privateKey, 'hex');
@@ -829,11 +830,16 @@ export async function sendTokens({ to, amount, chain, token = null, wallet = nul
829
830
  * Send tokens via WalletConnect (EVM only).
830
831
  */
831
832
  async function sendTokensViaWalletConnect({ to, amount, chain, token, max, dryRun }) {
833
+ const chainId = CHAIN_IDS[chain];
834
+ if (!chainId) throw new Error(`Unsupported chain: ${chain} (no chain ID configured for EVM transfers)`);
832
835
  const rpcUrl = CHAIN_RPCS[chain] || CHAIN_RPCS.evm;
833
- const chainId = CHAIN_IDS[chain] || 1;
834
836
 
835
- const wcAddress = await getWalletConnectAddress();
836
- if (!wcAddress) throw new Error('No WalletConnect session active. Run: walletconnect connect');
837
+ // Scoped to this specific chain, not just "any EVM account" — a session
838
+ // approved only for a different chain must not be used to sign a transfer
839
+ // on this one (addresses are identical across EVM chains, so an address
840
+ // match alone can't catch this; the CAIP-2 chain tag can).
841
+ const wcAddress = await getWalletConnectAddress('evm', chainId);
842
+ if (!wcAddress) throw new Error(`No WalletConnect session active for chain "${chain}" (eip155:${chainId}). Run: walletconnect connect`);
837
843
 
838
844
  let txTo, txValue, txData;
839
845
 
@@ -43,8 +43,19 @@ function parseWcJson(output) {
43
43
  *
44
44
  * @param {string} [chainType] - Optional: 'evm' or 'solana'. Filters accounts by chain prefix.
45
45
  * No arg = first account (backward compat).
46
+ * @param {number} [chainId] - Optional, 'evm' only: the specific EIP-155 chain ID the
47
+ * caller is about to sign/broadcast on. When given, only an account the session has
48
+ * actually approved for THAT chain (`eip155:<chainId>`) is returned — a session
49
+ * connected only to, say, Ethereum mainnet must not be handed back as if it were
50
+ * approved for Base just because both are "eip155:*". Mirrors the mainnet-only
51
+ * exact-match already done for Solana above. Only meaningful for
52
+ * chainType === 'evm' -- the Solana branch already does its own exact
53
+ * match unconditionally, so omit chainId there (a chain-config chain ID
54
+ * like Solana's 501 is not a CAIP-2 EIP-155 chain ID and would not match
55
+ * anything); also omit it when no specific chain needs verifying at all
56
+ * (chainType itself omitted, for first-account backward compat).
46
57
  */
47
- export async function getWalletConnectAddress(chainType) {
58
+ export async function getWalletConnectAddress(chainType, chainId) {
48
59
  try {
49
60
  const output = await wcExec('walletconnect', ['whoami', '--json'], 3000);
50
61
  const data = JSON.parse(output);
@@ -58,6 +69,10 @@ export async function getWalletConnectAddress(chainType) {
58
69
  return solAccount?.address || null;
59
70
  }
60
71
  if (chainType === 'evm') {
72
+ if (chainId != null) {
73
+ const evmAccount = accounts.find(a => a.chain === `eip155:${chainId}`);
74
+ return evmAccount?.address || null;
75
+ }
61
76
  const evmAccount = accounts.find(a => a.chain?.startsWith('eip155:'));
62
77
  return evmAccount?.address || null;
63
78
  }
@@ -8,7 +8,6 @@
8
8
  import crypto from 'crypto';
9
9
  import { NansenError, ErrorCode } from './api.js';
10
10
  import { wcExec } from './walletconnect-exec.js';
11
- import { EVM_CHAIN_IDS } from './chain-ids.js';
12
11
  import { evaluatePaymentRequirement, resolvePaymentAmount, resolvePayTo } from './x402-policy.js';
13
12
 
14
13
  /**
@@ -54,11 +53,33 @@ function parseChainId(network) {
54
53
  */
55
54
  export function buildEIP712TypedData({ fromAddress, requirement }) {
56
55
  const payTo = resolvePayTo(requirement);
57
- const { asset, extra, maxTimeoutSeconds } = requirement;
56
+ const { asset, maxTimeoutSeconds } = requirement;
57
+ const extra = requirement.extra || {};
58
58
  const amount = resolvePaymentAmount(requirement);
59
59
 
60
- // Determine chain ID: extra.chainId > parsed from network > fallback map > base
61
- const chainId = extra.chainId || parseChainId(requirement.network) || EVM_CHAIN_IDS[requirement.chain] || EVM_CHAIN_IDS.base;
60
+ if (!extra.name || !extra.version) {
61
+ throw new Error(
62
+ 'Refusing to sign x402 payment: EIP-712 domain name/version missing from requirement.extra.',
63
+ );
64
+ }
65
+
66
+ // Chain id comes only from the CAIP-2 network the policy validated — not from
67
+ // a remote extra.chainId override, which could change the signing domain.
68
+ const chainId = parseChainId(requirement.network);
69
+ if (chainId === null) {
70
+ throw new Error(
71
+ `Refusing to sign x402 payment: unsupported or missing EVM network ${requirement.network}.`,
72
+ );
73
+ }
74
+ // A remote extra.chainId that disagrees with the network is a domain-binding
75
+ // mismatch — refuse rather than sign under either interpretation. A null or
76
+ // empty extra.chainId means "unspecified", not a conflict, so treat it as absent.
77
+ if (extra.chainId != null && extra.chainId !== '' && Number(extra.chainId) !== chainId) {
78
+ throw new Error(
79
+ `Refusing to sign x402 payment: extra.chainId ${extra.chainId} conflicts with ` +
80
+ `network ${requirement.network} (chain id ${chainId}).`,
81
+ );
82
+ }
62
83
 
63
84
  const now = Math.floor(Date.now() / 1000);
64
85
  const nonce = '0x' + crypto.randomBytes(32).toString('hex');