@continuumdao/ctm-mpc-defi 0.2.3 → 0.2.5

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.
@@ -1,4 +1,4 @@
1
- import { getAddress, zeroAddress, formatUnits, parseUnits, encodeFunctionData, erc20Abi, decodeFunctionData, defineChain, createPublicClient, http, parseGwei, serializeTransaction, keccak256 } from 'viem';
1
+ import { parseAbiParameters, parseAbi, parseAbiItem, getAddress, zeroAddress, formatUnits, parseUnits, encodeFunctionData, erc20Abi, keccak256, encodeAbiParameters, decodeEventLog, defineChain, createPublicClient, http, decodeFunctionData, parseGwei, serializeTransaction } from 'viem';
2
2
  import { nodeFetchWithReadAuth, fetchChainFeeParams, gasLimitFromEstimateAndChainConfig, gweiToDecimalString, proposalTxParamsToFeeSnapshot, alignEip1559FeesWithLatestBase, getClientIdFromKeyGenResult } from '@continuumdao/continuum-node-sdk';
3
3
 
4
4
  // src/core/registry.ts
@@ -88,9 +88,55 @@ var MAX_UINT160 = (1n << 160n) - 1n;
88
88
  var MAX_UINT48 = (1n << 48n) - 1n;
89
89
  var UNISWAP_UNIVERSAL_ROUTER_DEFAULT_GAS_UNITS = 1500000n;
90
90
  var UNISWAP_TRADE_BASE_DEFAULT = "https://trade-api.gateway.uniswap.org/v1";
91
+ var UNISWAP_LP_API_BASE_DEFAULT = "https://api.uniswap.org";
91
92
  var UNISWAP_UNIVERSAL_ROUTER_VERSION_DEFAULT = "2.0";
92
93
  var UNISWAP_SWAP_DEFAULT_EXPIRY_MINUTES = 30;
93
94
  var UNISWAP_SWAP_DEFAULT_DEADLINE_SEC_OFFSET = UNISWAP_SWAP_DEFAULT_EXPIRY_MINUTES * 60;
95
+ var UNISWAP_LP_DEFAULT_EXPIRY_MINUTES = 30;
96
+ var UNISWAP_LP_DEFAULT_DEADLINE_SEC_OFFSET = UNISWAP_LP_DEFAULT_EXPIRY_MINUTES * 60;
97
+ var UNISWAP_LP_DEFAULT_SLIPPAGE_PERCENT = 0.5;
98
+ var POSITION_MANAGER_BY_CHAIN = {
99
+ 1: "0xbd216513d74c8cf14cf4747e6aaa6420ff64ee9e",
100
+ 10: "0x3c3ea4b57a46241e54610e5f022e5c45859a1017",
101
+ 137: "0x1ec2ebf4f37e7363fdfe3551602425af0b3ceef9",
102
+ 42161: "0xd88f38f930b7952f2db2432cb002e7abbf3dd869",
103
+ 8453: "0x7C5f5A4bBd8fD63184577525326123B519429bDc",
104
+ 11155111: "0x4B2C77d209D3405F41a037Ec6c77F7F5b8e2ca80",
105
+ 130: "0x0d97dc33264bfc1c226207428a79b26757fb9dc3",
106
+ 1868: "0x0e2850543f69f678257266e0907ff9a58b3f13de",
107
+ 59144: "0x661e93cca42afacb172121ef892830ca3b70f08d"
108
+ };
109
+ function getUniswapV4PositionManagerOrThrow(chainId) {
110
+ const raw = POSITION_MANAGER_BY_CHAIN[chainId];
111
+ if (!raw || !raw.startsWith("0x") || raw.length !== 42) {
112
+ throw new Error(
113
+ `No Uniswap V4 PositionManager is configured for chainId ${chainId}. Add this chain to uniswap-v4/constants or pass position manager from LP API response.`
114
+ );
115
+ }
116
+ return getAddress(raw);
117
+ }
118
+ function tryGetUniswapV4PositionManager(chainId) {
119
+ try {
120
+ return getUniswapV4PositionManagerOrThrow(chainId);
121
+ } catch {
122
+ return null;
123
+ }
124
+ }
125
+ var POSITION_MANAGER_DEPLOY_BLOCK_BY_CHAIN = {
126
+ /** Ethereum mainnet — Uniswap v4 launch (Jan 2025). */
127
+ 1: 22938741n
128
+ };
129
+ var UNISWAP_V4_LP_LOG_CHUNK_SIZE_DEFAULT = 200n;
130
+ var UNISWAP_V4_LP_LOG_CHUNK_SIZE_MIN = 10n;
131
+ function getUniswapV4PositionManagerDeployBlock(chainId) {
132
+ return POSITION_MANAGER_DEPLOY_BLOCK_BY_CHAIN[chainId];
133
+ }
134
+ var UNISWAP_V4_LP_MINT_DEFAULT_GAS_UNITS = 1800000n;
135
+ var UNISWAP_V4_LP_INCREASE_DEFAULT_GAS_UNITS = 1500000n;
136
+ var UNISWAP_V4_LP_DECREASE_DEFAULT_GAS_UNITS = 1200000n;
137
+ var UNISWAP_V4_LP_COLLECT_DEFAULT_GAS_UNITS = 900000n;
138
+ var UNISWAP_V4_LP_ERC20_APPROVE_FALLBACK = 100000n;
139
+ var UNISWAP_V4_LP_WETH_DEPOSIT_FALLBACK = 120000n;
94
140
  var DEFAULT_TRADE_BASE = "https://trade-api.gateway.uniswap.org/v1";
95
141
  var UNISWAP_QUOTE_HEADERS_BASE = {
96
142
  "Content-Type": "application/json",
@@ -343,7 +389,16 @@ function parseUniswapQuoteClassicInOut(res) {
343
389
  const input = q.input;
344
390
  const output = q.output;
345
391
  const inAm = input?.amount;
346
- const outAm = output?.amount;
392
+ let outAm = output?.amount;
393
+ if (typeof outAm !== "string" || !outAm) {
394
+ const agg = q.aggregatedOutputs;
395
+ if (Array.isArray(agg) && agg.length > 0) {
396
+ const first = agg[0];
397
+ if (typeof first?.amount === "string" && first.amount) {
398
+ outAm = first.amount;
399
+ }
400
+ }
401
+ }
347
402
  if (typeof inAm !== "string" || !inAm || typeof outAm !== "string" || !outAm) return null;
348
403
  try {
349
404
  return { inputWei: BigInt(inAm), outputWei: BigInt(outAm) };
@@ -1321,6 +1376,1075 @@ async function buildEvmMultisignBodyUniswapV4SkipPermit2Batch(args) {
1321
1376
  }
1322
1377
  });
1323
1378
  }
1379
+ var POOL_KEY_ABI = parseAbiParameters(
1380
+ "address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks"
1381
+ );
1382
+ var ZERO_HOOKS = "0x0000000000000000000000000000000000000000";
1383
+ function sortUniswapV4PoolCurrencies(token0Address, token1Address) {
1384
+ const a = normalizePoolCurrency(token0Address);
1385
+ const b = normalizePoolCurrency(token1Address);
1386
+ if (a.toLowerCase() === b.toLowerCase()) {
1387
+ throw new Error("Pool tokens must be distinct.");
1388
+ }
1389
+ return a.toLowerCase() < b.toLowerCase() ? { currency0: a, currency1: b } : { currency0: b, currency1: a };
1390
+ }
1391
+ function normalizePoolCurrency(raw) {
1392
+ const trimmed = raw.trim();
1393
+ if (!trimmed) {
1394
+ throw new Error("Pool token address is required.");
1395
+ }
1396
+ const lower = trimmed.toLowerCase();
1397
+ if (lower === "eth" || lower === "native" || lower === "native_eth" || lower === zeroAddress.toLowerCase()) {
1398
+ return zeroAddress;
1399
+ }
1400
+ return getAddress(trimmed);
1401
+ }
1402
+ function computeUniswapV4PoolReference(args) {
1403
+ const { currency0, currency1 } = sortUniswapV4PoolCurrencies(
1404
+ args.token0Address,
1405
+ args.token1Address
1406
+ );
1407
+ const hooks = args.hooks?.trim() && args.hooks.trim() !== "0x" ? getAddress(args.hooks.trim()) : ZERO_HOOKS;
1408
+ return keccak256(
1409
+ encodeAbiParameters(POOL_KEY_ABI, [
1410
+ currency0,
1411
+ currency1,
1412
+ args.fee,
1413
+ args.tickSpacing,
1414
+ hooks
1415
+ ])
1416
+ );
1417
+ }
1418
+
1419
+ // src/protocols/evm/uniswap-v4/knownLpPools.ts
1420
+ var ZERO_HOOKS2 = "0x0000000000000000000000000000000000000000";
1421
+ var UNISWAP_V4_LP_POOL_LOOKUP_HINT = "Pool may not be initialized on this chain. Call ctm_uniswap_v4_list_lp_pools for other presets, pass a custom existingPool.poolReference, or use newPool to initialize a pool.";
1422
+ var FEE_TIERS = [
1423
+ { fee: 500, feeLabel: "0.05%", tickSpacing: 10 },
1424
+ { fee: 3e3, feeLabel: "0.3%", tickSpacing: 60 },
1425
+ { fee: 1e4, feeLabel: "1%", tickSpacing: 200 }
1426
+ ];
1427
+ var CHAIN_LP_CONFIGS = [
1428
+ {
1429
+ chainId: 1,
1430
+ chainLabel: "Ethereum",
1431
+ nativeWrapped: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
1432
+ tokens: {
1433
+ eth: { symbol: "ETH", address: "0x0000000000000000000000000000000000000000", native: true },
1434
+ usdc: { symbol: "USDC", address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" },
1435
+ usdt: { symbol: "USDT", address: "0xdAC17F958D2ee523a2206206994597C13D831ec7" },
1436
+ wbtc: { symbol: "WBTC", address: "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599" }
1437
+ },
1438
+ pairs: [
1439
+ { slug: "eth-usdc", label: "ETH/USDC", token0Key: "eth", token1Key: "usdc", tiers: [...FEE_TIERS] },
1440
+ { slug: "eth-usdt", label: "ETH/USDT", token0Key: "eth", token1Key: "usdt", tiers: [...FEE_TIERS] },
1441
+ { slug: "eth-wbtc", label: "ETH/WBTC", token0Key: "eth", token1Key: "wbtc", tiers: [...FEE_TIERS] }
1442
+ ]
1443
+ },
1444
+ {
1445
+ chainId: 8453,
1446
+ chainLabel: "Base",
1447
+ nativeWrapped: "0x4200000000000000000000000000000000000006",
1448
+ tokens: {
1449
+ eth: { symbol: "ETH", address: "0x0000000000000000000000000000000000000000", native: true },
1450
+ usdc: { symbol: "USDC", address: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" }
1451
+ },
1452
+ pairs: [
1453
+ { slug: "eth-usdc", label: "ETH/USDC", token0Key: "eth", token1Key: "usdc", tiers: [...FEE_TIERS] }
1454
+ ]
1455
+ },
1456
+ {
1457
+ chainId: 42161,
1458
+ chainLabel: "Arbitrum",
1459
+ nativeWrapped: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
1460
+ tokens: {
1461
+ eth: { symbol: "ETH", address: "0x0000000000000000000000000000000000000000", native: true },
1462
+ usdc: { symbol: "USDC", address: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831" }
1463
+ },
1464
+ pairs: [
1465
+ { slug: "eth-usdc", label: "ETH/USDC", token0Key: "eth", token1Key: "usdc", tiers: [...FEE_TIERS] }
1466
+ ]
1467
+ },
1468
+ {
1469
+ chainId: 10,
1470
+ chainLabel: "Optimism",
1471
+ nativeWrapped: "0x4200000000000000000000000000000000000006",
1472
+ tokens: {
1473
+ eth: { symbol: "ETH", address: "0x0000000000000000000000000000000000000000", native: true },
1474
+ usdc: { symbol: "USDC", address: "0x0b2C639c533813f4Aa9D7837CAa646c993D1B7926" }
1475
+ },
1476
+ pairs: [
1477
+ { slug: "eth-usdc", label: "ETH/USDC", token0Key: "eth", token1Key: "usdc", tiers: [...FEE_TIERS] }
1478
+ ]
1479
+ },
1480
+ {
1481
+ chainId: 137,
1482
+ chainLabel: "Polygon",
1483
+ nativeWrapped: "0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619",
1484
+ tokens: {
1485
+ eth: { symbol: "ETH", address: "0x0000000000000000000000000000000000000000", native: true },
1486
+ usdc: { symbol: "USDC", address: "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359" }
1487
+ },
1488
+ pairs: [
1489
+ { slug: "eth-usdc", label: "ETH/USDC", token0Key: "eth", token1Key: "usdc", tiers: [...FEE_TIERS] }
1490
+ ]
1491
+ }
1492
+ ];
1493
+ function buildPresetId(pairSlug, feeLabel) {
1494
+ const feeSlug = feeLabel.replace("%", "").replace(".", "-");
1495
+ return `${pairSlug}-${feeSlug}`;
1496
+ }
1497
+ function buildPoolRows(config) {
1498
+ const rows = [];
1499
+ for (const pair of config.pairs) {
1500
+ const token0 = config.tokens[pair.token0Key];
1501
+ const token1 = config.tokens[pair.token1Key];
1502
+ if (!token0 || !token1) continue;
1503
+ for (const tier of pair.tiers) {
1504
+ const poolReference = computeUniswapV4PoolReference({
1505
+ token0Address: token0.address,
1506
+ token1Address: token1.address,
1507
+ fee: tier.fee,
1508
+ tickSpacing: tier.tickSpacing,
1509
+ hooks: ZERO_HOOKS2
1510
+ });
1511
+ const usesNativeEth = Boolean(token0.native || token1.native);
1512
+ rows.push({
1513
+ presetId: buildPresetId(pair.slug, tier.feeLabel),
1514
+ pairSlug: pair.slug,
1515
+ pairLabel: pair.label,
1516
+ fee: tier.fee,
1517
+ feeLabel: tier.feeLabel,
1518
+ tickSpacing: tier.tickSpacing,
1519
+ token0Symbol: token0.symbol,
1520
+ token1Symbol: token1.symbol,
1521
+ token0Address: getAddress(token0.address),
1522
+ token1Address: getAddress(token1.address),
1523
+ poolReference,
1524
+ hooks: ZERO_HOOKS2,
1525
+ nativeWrapped: usesNativeEth ? getAddress(config.nativeWrapped) : void 0,
1526
+ usesNativeEth
1527
+ });
1528
+ }
1529
+ }
1530
+ return rows;
1531
+ }
1532
+ function chainConfigOrThrow(chainId) {
1533
+ const config = CHAIN_LP_CONFIGS.find((row) => row.chainId === chainId);
1534
+ if (!config) {
1535
+ throw new Error(
1536
+ `No standard Uniswap V4 LP pool catalog for chainId ${chainId}. Supported catalog chains: ${CHAIN_LP_CONFIGS.map((c) => c.chainId).join(", ")}.`
1537
+ );
1538
+ }
1539
+ if (!isUniswapV4ChainSupported(chainId)) {
1540
+ throw new Error(`chainId ${chainId} is not supported for Uniswap V4 MCP tools.`);
1541
+ }
1542
+ return config;
1543
+ }
1544
+ function listUniswapV4StandardLpPools(args) {
1545
+ const chainId = parseUniswapChainId(args.chainId);
1546
+ const config = chainConfigOrThrow(chainId);
1547
+ let pools = buildPoolRows(config);
1548
+ const pairFilter = args.pair?.trim().toLowerCase();
1549
+ if (pairFilter) {
1550
+ pools = pools.filter(
1551
+ (row) => row.pairSlug.includes(pairFilter) || row.pairLabel.toLowerCase().includes(pairFilter) || row.presetId.includes(pairFilter)
1552
+ );
1553
+ }
1554
+ return {
1555
+ chainId,
1556
+ chainLabel: config.chainLabel,
1557
+ pools,
1558
+ notes: "poolReference is derived from token addresses, fee, tickSpacing, and hooks (no-hook pools). Pass presetId to ctm_uniswap_v4_lp_create_position as poolPreset, or copy existingPool fields. If LP create fails, the pool may not exist on-chain \u2014 try another preset, pass poolReference manually, or use newPool."
1559
+ };
1560
+ }
1561
+ function resolveUniswapV4LpPoolPreset(args) {
1562
+ const chainId = parseUniswapChainId(args.chainId);
1563
+ const preset = args.presetId.trim().toLowerCase();
1564
+ const row = buildPoolRows(chainConfigOrThrow(chainId)).find(
1565
+ (pool) => pool.presetId.toLowerCase() === preset
1566
+ );
1567
+ if (!row) {
1568
+ throw new Error(
1569
+ `Unknown LP pool preset "${args.presetId}" on chainId ${chainId}. Call ctm_uniswap_v4_list_lp_pools to list standard presets.`
1570
+ );
1571
+ }
1572
+ return row;
1573
+ }
1574
+ function resolveUniswapV4LpExistingPoolFromKey(args) {
1575
+ const poolReference = args.poolReference?.trim() || computeUniswapV4PoolReference({
1576
+ token0Address: args.token0Address,
1577
+ token1Address: args.token1Address,
1578
+ fee: args.fee,
1579
+ tickSpacing: args.tickSpacing,
1580
+ hooks: args.hooks
1581
+ });
1582
+ const sorted = sortTokensForExistingPool(args.token0Address, args.token1Address);
1583
+ return {
1584
+ token0Address: sorted.token0Address,
1585
+ token1Address: sorted.token1Address,
1586
+ poolReference
1587
+ };
1588
+ }
1589
+ function sortTokensForExistingPool(token0Address, token1Address) {
1590
+ const sorted = sortUniswapV4PoolCurrencies(token0Address, token1Address);
1591
+ return { token0Address: sorted.currency0, token1Address: sorted.currency1 };
1592
+ }
1593
+ function uniswapV4ListStandardLpPools(args) {
1594
+ return listUniswapV4StandardLpPools(args);
1595
+ }
1596
+
1597
+ // src/protocols/evm/uniswap-v4/liquidityApi.ts
1598
+ var LP_HEADERS_BASE = {
1599
+ "Content-Type": "application/json",
1600
+ Accept: "application/json",
1601
+ "User-Agent": "ctm-mpc-defi uniswapLpApi/1.0 (TS)"
1602
+ };
1603
+ function trimAddr2(a) {
1604
+ return a.trim();
1605
+ }
1606
+ function lpDeadlineUnix(nowSec = Math.floor(Date.now() / 1e3)) {
1607
+ return nowSec + UNISWAP_LP_DEFAULT_DEADLINE_SEC_OFFSET;
1608
+ }
1609
+ function resolveLpBaseUrl(baseUrl) {
1610
+ const raw = (baseUrl ?? UNISWAP_TRADE_BASE_DEFAULT).replace(/\/$/, "");
1611
+ return raw;
1612
+ }
1613
+ function resolveLpPath(baseUrl, action) {
1614
+ const normalized = baseUrl.replace(/\/$/, "");
1615
+ if (normalized.includes("api.uniswap.org")) {
1616
+ return `${normalized}/lp/${action}`;
1617
+ }
1618
+ return `${normalized}/lp/${action}`;
1619
+ }
1620
+ async function postUniswapLpApi(args) {
1621
+ const useProxy = args.useServerProxy !== false && typeof globalThis !== "undefined" && typeof globalThis.window !== "undefined";
1622
+ if (useProxy && args.proxyPath) {
1623
+ const fn2 = args.fetchImpl ?? globalThis.fetch;
1624
+ const res2 = await fn2(args.proxyPath, {
1625
+ method: "POST",
1626
+ headers: { "Content-Type": "application/json" },
1627
+ body: JSON.stringify({
1628
+ uniswapApiKey: args.uniswapApiKey,
1629
+ baseUrl: args.baseUrl,
1630
+ body: args.body
1631
+ }),
1632
+ credentials: "same-origin"
1633
+ });
1634
+ const text2 = await res2.text();
1635
+ if (!res2.ok) {
1636
+ let errMsg = res2.statusText;
1637
+ try {
1638
+ const j = JSON.parse(text2);
1639
+ if (j?.error?.trim()) errMsg = j.error.trim();
1640
+ } catch {
1641
+ if (text2.trim()) errMsg = text2.slice(0, 500);
1642
+ }
1643
+ throw new Error(`Uniswap LP proxy failed: ${errMsg}`);
1644
+ }
1645
+ return JSON.parse(text2);
1646
+ }
1647
+ const base = resolveLpBaseUrl(args.baseUrl);
1648
+ const url = resolveLpPath(base, args.path);
1649
+ const fn = args.fetchImpl ?? globalThis.fetch;
1650
+ const res = await fn(url, {
1651
+ method: "POST",
1652
+ headers: {
1653
+ ...LP_HEADERS_BASE,
1654
+ "x-api-key": args.uniswapApiKey.trim()
1655
+ },
1656
+ body: JSON.stringify(args.body)
1657
+ });
1658
+ const text = await res.text();
1659
+ if (!res.ok) {
1660
+ const base2 = messageFromUniswapHttpResponseBody(text, res.status, res.statusText);
1661
+ const hint = args.path === "create" && args.body.existingPool ? ` ${UNISWAP_V4_LP_POOL_LOOKUP_HINT}` : "";
1662
+ throw new Error(`Uniswap LP POST /${args.path} failed: ${base2}${hint}`);
1663
+ }
1664
+ return JSON.parse(text);
1665
+ }
1666
+ function extractUniswapLpTransaction(response, field) {
1667
+ const tx = response[field];
1668
+ if (!tx || typeof tx !== "object" || Array.isArray(tx)) {
1669
+ throw new Error(`Uniswap LP response missing \`${field}\` transaction object.`);
1670
+ }
1671
+ const o = tx;
1672
+ const to = String(o.to ?? "").trim();
1673
+ const data = String(o.data ?? "").trim();
1674
+ if (!to.startsWith("0x") || !data.startsWith("0x") || data === "0x") {
1675
+ throw new Error(`Uniswap LP \`${field}\` transaction has invalid to/data.`);
1676
+ }
1677
+ return {
1678
+ to,
1679
+ from: o.from != null ? String(o.from) : void 0,
1680
+ data,
1681
+ value: String(o.value ?? "0"),
1682
+ chainId: typeof o.chainId === "number" ? o.chainId : void 0,
1683
+ gasLimit: o.gasLimit != null ? String(o.gasLimit) : void 0,
1684
+ gasPrice: o.gasPrice != null ? String(o.gasPrice) : void 0,
1685
+ maxFeePerGas: o.maxFeePerGas != null ? String(o.maxFeePerGas) : void 0,
1686
+ maxPriorityFeePerGas: o.maxPriorityFeePerGas != null ? String(o.maxPriorityFeePerGas) : void 0
1687
+ };
1688
+ }
1689
+ function extractUniswapLpTokenAmounts(response) {
1690
+ const read = (key) => {
1691
+ const raw = response[key];
1692
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
1693
+ const o = raw;
1694
+ const tokenAddress = String(o.tokenAddress ?? o.token ?? "").trim();
1695
+ const amount = String(o.amount ?? "").trim();
1696
+ if (!tokenAddress.startsWith("0x") || !amount) return void 0;
1697
+ return { tokenAddress, amount };
1698
+ };
1699
+ return { token0: read("token0"), token1: read("token1") };
1700
+ }
1701
+ async function uniswapLpCreatePosition(args) {
1702
+ const body = {
1703
+ protocol: "V4",
1704
+ walletAddress: trimAddr2(args.walletAddress),
1705
+ chainId: args.chainId,
1706
+ independentToken: {
1707
+ tokenAddress: trimAddr2(args.independentToken.tokenAddress),
1708
+ amount: String(args.independentToken.amount).trim()
1709
+ },
1710
+ slippageTolerance: args.slippageTolerance ?? UNISWAP_LP_DEFAULT_SLIPPAGE_PERCENT,
1711
+ deadline: args.deadline ?? lpDeadlineUnix(),
1712
+ simulateTransaction: args.simulateTransaction ?? false
1713
+ };
1714
+ if (args.existingPool) {
1715
+ body.existingPool = {
1716
+ token0Address: trimAddr2(args.existingPool.token0Address),
1717
+ token1Address: trimAddr2(args.existingPool.token1Address),
1718
+ poolReference: trimAddr2(args.existingPool.poolReference)
1719
+ };
1720
+ }
1721
+ if (args.newPool) {
1722
+ body.newPool = {
1723
+ token0Address: trimAddr2(args.newPool.token0Address),
1724
+ token1Address: trimAddr2(args.newPool.token1Address),
1725
+ fee: args.newPool.fee,
1726
+ tickSpacing: args.newPool.tickSpacing,
1727
+ initialPrice: String(args.newPool.initialPrice).trim(),
1728
+ ...args.newPool.hooks ? { hooks: trimAddr2(args.newPool.hooks) } : {}
1729
+ };
1730
+ }
1731
+ if (!args.existingPool && !args.newPool) {
1732
+ throw new Error("Provide existingPool or newPool for LP create.");
1733
+ }
1734
+ if (args.priceBounds) {
1735
+ body.priceBounds = {
1736
+ minPrice: String(args.priceBounds.minPrice).trim(),
1737
+ maxPrice: String(args.priceBounds.maxPrice).trim()
1738
+ };
1739
+ }
1740
+ if (args.tickBounds) {
1741
+ body.tickBounds = {
1742
+ tickLower: args.tickBounds.tickLower,
1743
+ tickUpper: args.tickBounds.tickUpper
1744
+ };
1745
+ }
1746
+ if (!args.priceBounds && !args.tickBounds) {
1747
+ throw new Error("Provide priceBounds or tickBounds for LP create.");
1748
+ }
1749
+ if (args.batchPermitData) body.batchPermitData = args.batchPermitData;
1750
+ if (args.signature) body.signature = args.signature;
1751
+ return postUniswapLpApi({
1752
+ uniswapApiKey: args.uniswapApiKey,
1753
+ path: "create",
1754
+ body,
1755
+ baseUrl: args.baseUrl,
1756
+ fetchImpl: args.fetchImpl,
1757
+ useServerProxy: args.useServerProxy,
1758
+ proxyPath: "/api/uniswap/liquidity/create"
1759
+ });
1760
+ }
1761
+ async function uniswapLpIncreasePosition(args) {
1762
+ const body = {
1763
+ protocol: "V4",
1764
+ walletAddress: trimAddr2(args.walletAddress),
1765
+ chainId: args.chainId,
1766
+ token0Address: trimAddr2(args.token0Address),
1767
+ token1Address: trimAddr2(args.token1Address),
1768
+ nftTokenId: String(args.nftTokenId),
1769
+ independentToken: {
1770
+ tokenAddress: trimAddr2(args.independentToken.tokenAddress),
1771
+ amount: String(args.independentToken.amount).trim()
1772
+ },
1773
+ slippageTolerance: args.slippageTolerance ?? UNISWAP_LP_DEFAULT_SLIPPAGE_PERCENT,
1774
+ deadline: args.deadline ?? lpDeadlineUnix(),
1775
+ simulateTransaction: args.simulateTransaction ?? false
1776
+ };
1777
+ if (args.v4BatchPermitData) body.v4BatchPermitData = args.v4BatchPermitData;
1778
+ if (args.signature) body.signature = args.signature;
1779
+ return postUniswapLpApi({
1780
+ uniswapApiKey: args.uniswapApiKey,
1781
+ path: "increase",
1782
+ body,
1783
+ baseUrl: args.baseUrl,
1784
+ fetchImpl: args.fetchImpl,
1785
+ useServerProxy: args.useServerProxy,
1786
+ proxyPath: "/api/uniswap/liquidity/increase"
1787
+ });
1788
+ }
1789
+ async function uniswapLpDecreasePosition(args) {
1790
+ const pct = Math.trunc(args.liquidityPercentageToDecrease);
1791
+ if (!Number.isFinite(pct) || pct < 1 || pct > 100) {
1792
+ throw new Error("liquidityPercentageToDecrease must be an integer from 1 to 100.");
1793
+ }
1794
+ const body = {
1795
+ protocol: "V4",
1796
+ walletAddress: trimAddr2(args.walletAddress),
1797
+ chainId: args.chainId,
1798
+ token0Address: trimAddr2(args.token0Address),
1799
+ token1Address: trimAddr2(args.token1Address),
1800
+ nftTokenId: String(args.nftTokenId),
1801
+ liquidityPercentageToDecrease: pct,
1802
+ slippageTolerance: args.slippageTolerance ?? UNISWAP_LP_DEFAULT_SLIPPAGE_PERCENT,
1803
+ deadline: args.deadline ?? lpDeadlineUnix(),
1804
+ simulateTransaction: args.simulateTransaction ?? false
1805
+ };
1806
+ return postUniswapLpApi({
1807
+ uniswapApiKey: args.uniswapApiKey,
1808
+ path: "decrease",
1809
+ body,
1810
+ baseUrl: args.baseUrl,
1811
+ fetchImpl: args.fetchImpl,
1812
+ useServerProxy: args.useServerProxy,
1813
+ proxyPath: "/api/uniswap/liquidity/decrease"
1814
+ });
1815
+ }
1816
+ async function uniswapLpClaimFees(args) {
1817
+ const body = {
1818
+ protocol: "V4",
1819
+ walletAddress: trimAddr2(args.walletAddress),
1820
+ chainId: args.chainId,
1821
+ tokenId: String(args.tokenId),
1822
+ simulateTransaction: args.simulateTransaction ?? false
1823
+ };
1824
+ return postUniswapLpApi({
1825
+ uniswapApiKey: args.uniswapApiKey,
1826
+ path: "claim",
1827
+ body,
1828
+ baseUrl: args.baseUrl,
1829
+ fetchImpl: args.fetchImpl,
1830
+ useServerProxy: args.useServerProxy,
1831
+ proxyPath: "/api/uniswap/liquidity/claim"
1832
+ });
1833
+ }
1834
+ var TX_FIELD_BY_ACTION = {
1835
+ mint: "create",
1836
+ increase: "increase",
1837
+ decrease: "decrease",
1838
+ collect: "claim"
1839
+ };
1840
+ function uniswapLpTxFieldForAction(action) {
1841
+ return TX_FIELD_BY_ACTION[action];
1842
+ }
1843
+ function parseUniswapLpApiSnapshot(args) {
1844
+ const field = TX_FIELD_BY_ACTION[args.action];
1845
+ const transaction = extractUniswapLpTransaction(args.lpResponse, field);
1846
+ const amounts = extractUniswapLpTokenAmounts(args.lpResponse);
1847
+ const tickLower = typeof args.lpResponse.tickLower === "number" ? args.lpResponse.tickLower : void 0;
1848
+ const tickUpper = typeof args.lpResponse.tickUpper === "number" ? args.lpResponse.tickUpper : void 0;
1849
+ const minPrice = typeof args.lpResponse.minPrice === "string" ? args.lpResponse.minPrice : void 0;
1850
+ const maxPrice = typeof args.lpResponse.maxPrice === "string" ? args.lpResponse.maxPrice : void 0;
1851
+ return {
1852
+ transaction,
1853
+ token0: amounts.token0,
1854
+ token1: amounts.token1,
1855
+ tickLower,
1856
+ tickUpper,
1857
+ minPrice,
1858
+ maxPrice
1859
+ };
1860
+ }
1861
+ function formatUniswapLpAmountHuman(amountWei, decimals) {
1862
+ try {
1863
+ return formatUnits(BigInt(amountWei), decimals);
1864
+ } catch {
1865
+ return amountWei;
1866
+ }
1867
+ }
1868
+ var erc721BalanceAbi = parseAbi([
1869
+ "function balanceOf(address owner) view returns (uint256)",
1870
+ "function ownerOf(uint256 tokenId) view returns (address)"
1871
+ ]);
1872
+ var positionInfoAbi = parseAbi([
1873
+ "function positionInfo(uint256 tokenId) view returns (uint256 info)"
1874
+ ]);
1875
+ var UNISWAP_V4_LP_POSITION_REGISTRY_HINT = "Add the position NFT to the node token registry (tokenType ERC721: Uniswap V4 Position Manager contract + tokenId). MCP: call ctm_uniswap_v4_register_position_nft (by tokenId) or ctm_uniswap_v4_register_position_from_mint_tx (after mint execute). Or use add_to_token_registry. In the Continuum app: Add Token (ERC721), or Manage liquidity \u2192 Refresh positions (blockchain scan).";
1876
+ function formatUniswapV4PositionNotFoundError(args) {
1877
+ return `Uniswap V4 position #${args.tokenId} is not in the node token registry for chain ${args.chainId}. ` + UNISWAP_V4_LP_POSITION_REGISTRY_HINT;
1878
+ }
1879
+ var positionManagerTransferEvent = parseAbiItem(
1880
+ "event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)"
1881
+ );
1882
+ function uniswapV4PositionMintedTokenIdsFromReceipt(receipt, positionManager, owner) {
1883
+ const pm = getAddress(positionManager);
1884
+ const wallet = getAddress(owner);
1885
+ const ids = [];
1886
+ for (const log of receipt.logs) {
1887
+ try {
1888
+ if (getAddress(log.address) !== pm) continue;
1889
+ const decoded = decodeEventLog({
1890
+ abi: [positionManagerTransferEvent],
1891
+ data: log.data,
1892
+ topics: log.topics
1893
+ });
1894
+ if (decoded.eventName !== "Transfer") continue;
1895
+ const from = decoded.args.from;
1896
+ const to = decoded.args.to;
1897
+ const tokenId = decoded.args.tokenId;
1898
+ if (from === zeroAddress && getAddress(to) === wallet) {
1899
+ ids.push(tokenId);
1900
+ }
1901
+ } catch {
1902
+ }
1903
+ }
1904
+ return ids;
1905
+ }
1906
+ function uniswapV4ListPositionsFromRegistryForMcp(args) {
1907
+ const chainId = typeof args.chainId === "number" ? args.chainId : Number.parseInt(String(args.chainId), 10);
1908
+ if (!Number.isFinite(chainId) || chainId <= 0) {
1909
+ throw new Error("chainId must be a positive integer");
1910
+ }
1911
+ const wallet = getAddress(args.walletAddress);
1912
+ const pm = getAddress(
1913
+ args.positionManagerAddress ? String(args.positionManagerAddress) : getUniswapV4PositionManagerOrThrow(chainId)
1914
+ );
1915
+ const pmLower = pm.toLowerCase();
1916
+ const positions = [];
1917
+ for (const row of args.erc721Tokens) {
1918
+ const addr = (row.contractAddress ?? "").trim();
1919
+ const tokenId = (row.tokenId ?? "").trim();
1920
+ if (!addr || !tokenId) continue;
1921
+ try {
1922
+ if (getAddress(addr).toLowerCase() !== pmLower) continue;
1923
+ } catch {
1924
+ continue;
1925
+ }
1926
+ positions.push({
1927
+ tokenId,
1928
+ positionManager: pm,
1929
+ owner: wallet,
1930
+ name: row.name,
1931
+ symbol: row.symbol
1932
+ });
1933
+ }
1934
+ positions.sort((a, b) => BigInt(a.tokenId) < BigInt(b.tokenId) ? -1 : 1);
1935
+ return { positions, source: "token_registry" };
1936
+ }
1937
+ function throwIfScanAborted(signal) {
1938
+ if (signal?.aborted) {
1939
+ throw new DOMException("Position scan aborted.", "AbortError");
1940
+ }
1941
+ }
1942
+ var TRANSFER_EVENT = {
1943
+ type: "event",
1944
+ name: "Transfer",
1945
+ inputs: [
1946
+ { indexed: true, name: "from", type: "address" },
1947
+ { indexed: true, name: "to", type: "address" },
1948
+ { indexed: true, name: "tokenId", type: "uint256" }
1949
+ ]
1950
+ };
1951
+ function isEthGetLogsBlockRangeTooLargeError(err) {
1952
+ const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();
1953
+ return msg.includes("block range too large") || msg.includes("maximum allowed") || msg.includes("query returned more than") || msg.includes("exceed maximum block range") || msg.includes("block range is too large");
1954
+ }
1955
+ async function getTransferLogsForWalletInRange(args) {
1956
+ const { client, positionManager, wallet, fromBlock, toBlock } = args;
1957
+ let chunkSize = args.chunkSize < UNISWAP_V4_LP_LOG_CHUNK_SIZE_MIN ? UNISWAP_V4_LP_LOG_CHUNK_SIZE_MIN : args.chunkSize;
1958
+ const out = [];
1959
+ let from = fromBlock;
1960
+ while (from <= toBlock) {
1961
+ let to = from + chunkSize - 1n > toBlock ? toBlock : from + chunkSize - 1n;
1962
+ for (; ; ) {
1963
+ try {
1964
+ const [toLogs, fromLogs] = await Promise.all([
1965
+ client.getLogs({
1966
+ address: positionManager,
1967
+ event: TRANSFER_EVENT,
1968
+ args: { to: wallet },
1969
+ fromBlock: from,
1970
+ toBlock: to
1971
+ }),
1972
+ client.getLogs({
1973
+ address: positionManager,
1974
+ event: TRANSFER_EVENT,
1975
+ args: { from: wallet },
1976
+ fromBlock: from,
1977
+ toBlock: to
1978
+ })
1979
+ ]);
1980
+ out.push(...toLogs, ...fromLogs);
1981
+ from = to + 1n;
1982
+ break;
1983
+ } catch (err) {
1984
+ if (!isEthGetLogsBlockRangeTooLargeError(err) || chunkSize <= UNISWAP_V4_LP_LOG_CHUNK_SIZE_MIN) {
1985
+ throw err;
1986
+ }
1987
+ chunkSize = chunkSize / 2n;
1988
+ if (chunkSize < UNISWAP_V4_LP_LOG_CHUNK_SIZE_MIN) {
1989
+ chunkSize = UNISWAP_V4_LP_LOG_CHUNK_SIZE_MIN;
1990
+ }
1991
+ to = from + chunkSize - 1n > toBlock ? toBlock : from + chunkSize - 1n;
1992
+ }
1993
+ }
1994
+ }
1995
+ return out;
1996
+ }
1997
+ function parseUniswapV4ScanFromDateYmd(fromDate) {
1998
+ const trimmed = fromDate.trim();
1999
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(trimmed)) {
2000
+ throw new Error("fromDate must be YYYY-MM-DD");
2001
+ }
2002
+ const ms = Date.parse(`${trimmed}T00:00:00.000Z`);
2003
+ if (!Number.isFinite(ms)) {
2004
+ throw new Error(`Invalid fromDate: ${fromDate}`);
2005
+ }
2006
+ return Math.floor(ms / 1e3);
2007
+ }
2008
+ async function resolveBlockAtOrAfterUnixTime(client, unixTime, bounds) {
2009
+ let lo = bounds.minBlock;
2010
+ let hi = bounds.maxBlock;
2011
+ let ans = hi;
2012
+ while (lo <= hi) {
2013
+ const mid = (lo + hi) / 2n;
2014
+ const block = await client.getBlock({ blockNumber: mid });
2015
+ const ts = Number(block.timestamp);
2016
+ if (ts >= unixTime) {
2017
+ ans = mid;
2018
+ if (mid === 0n) break;
2019
+ hi = mid - 1n;
2020
+ } else {
2021
+ lo = mid + 1n;
2022
+ }
2023
+ }
2024
+ return ans;
2025
+ }
2026
+ async function resolveUniswapV4PositionScanFromDate(args) {
2027
+ const unixTime = parseUniswapV4ScanFromDateYmd(args.fromDate);
2028
+ const chain = defineChain({
2029
+ id: args.chainId,
2030
+ name: `uniswap-v4-${args.chainId}`,
2031
+ nativeCurrency: { name: "ETH", symbol: "ETH", decimals: 18 },
2032
+ rpcUrls: { default: { http: [args.rpcUrl] } }
2033
+ });
2034
+ const client = createPublicClient({ chain, transport: http(args.rpcUrl) });
2035
+ const latest = await client.getBlockNumber();
2036
+ const deploy = getUniswapV4PositionManagerDeployBlock(args.chainId) ?? 0n;
2037
+ const resolved = await resolveBlockAtOrAfterUnixTime(client, unixTime, {
2038
+ minBlock: deploy,
2039
+ maxBlock: latest
2040
+ });
2041
+ return resolved < deploy ? deploy : resolved;
2042
+ }
2043
+ function defaultScanFromBlock(args) {
2044
+ if (args.fromBlock != null) return args.fromBlock;
2045
+ const deploy = getUniswapV4PositionManagerDeployBlock(args.chainId);
2046
+ if (deploy != null) return deploy;
2047
+ return args.latest > args.maxBlocksToScan ? args.latest - args.maxBlocksToScan : 0n;
2048
+ }
2049
+ async function listUniswapV4PositionsForWallet(args) {
2050
+ throwIfScanAborted(args.signal);
2051
+ const wallet = getAddress(args.walletAddress);
2052
+ const pm = getAddress(
2053
+ args.positionManagerAddress ? String(args.positionManagerAddress) : getUniswapV4PositionManagerOrThrow(args.chainId)
2054
+ );
2055
+ const chain = defineChain({
2056
+ id: args.chainId,
2057
+ name: `uniswap-v4-${args.chainId}`,
2058
+ nativeCurrency: { name: "ETH", symbol: "ETH", decimals: 18 },
2059
+ rpcUrls: { default: { http: [args.rpcUrl] } }
2060
+ });
2061
+ const client = createPublicClient({ chain, transport: http(args.rpcUrl) });
2062
+ const latest = await client.getBlockNumber();
2063
+ const maxScan = args.maxBlocksToScan ?? 500000n;
2064
+ const chunkSize = args.chunkSize ?? UNISWAP_V4_LP_LOG_CHUNK_SIZE_DEFAULT;
2065
+ const scanFrom = defaultScanFromBlock({
2066
+ chainId: args.chainId,
2067
+ latest,
2068
+ fromBlock: args.fromBlock,
2069
+ maxBlocksToScan: maxScan
2070
+ });
2071
+ const balance = await client.readContract({
2072
+ address: pm,
2073
+ abi: erc721BalanceAbi,
2074
+ functionName: "balanceOf",
2075
+ args: [wallet]
2076
+ });
2077
+ const targetCount = Number(balance);
2078
+ const emitProgress = (scanningFromBlock, scanningToBlock, foundCount) => {
2079
+ args.onProgress?.({
2080
+ latestBlock: latest.toString(),
2081
+ scanFromBlock: scanFrom.toString(),
2082
+ scanningFromBlock: scanningFromBlock.toString(),
2083
+ scanningToBlock: scanningToBlock.toString(),
2084
+ foundCount,
2085
+ targetCount
2086
+ });
2087
+ };
2088
+ if (balance === 0n) {
2089
+ emitProgress(latest, latest, 0);
2090
+ return [];
2091
+ }
2092
+ const candidates = /* @__PURE__ */ new Set();
2093
+ const verified = /* @__PURE__ */ new Map();
2094
+ let toBlock = latest;
2095
+ while (toBlock >= scanFrom && verified.size < targetCount) {
2096
+ throwIfScanAborted(args.signal);
2097
+ let fromBlock = toBlock >= chunkSize - 1n ? toBlock - chunkSize + 1n : 0n;
2098
+ if (fromBlock < scanFrom) fromBlock = scanFrom;
2099
+ emitProgress(fromBlock, toBlock, verified.size);
2100
+ const logs = await getTransferLogsForWalletInRange({
2101
+ client,
2102
+ positionManager: pm,
2103
+ wallet,
2104
+ fromBlock,
2105
+ toBlock,
2106
+ chunkSize
2107
+ });
2108
+ for (const log of logs) {
2109
+ const tokenId = log.args.tokenId?.toString();
2110
+ if (!tokenId) continue;
2111
+ const to = log.args.to != null ? getAddress(log.args.to) : null;
2112
+ const from = log.args.from != null ? getAddress(log.args.from) : null;
2113
+ if (to === wallet) candidates.add(tokenId);
2114
+ if (from === wallet) candidates.delete(tokenId);
2115
+ }
2116
+ for (const tokenId of candidates) {
2117
+ if (verified.has(tokenId)) continue;
2118
+ try {
2119
+ const owner = await client.readContract({
2120
+ address: pm,
2121
+ abi: erc721BalanceAbi,
2122
+ functionName: "ownerOf",
2123
+ args: [BigInt(tokenId)]
2124
+ });
2125
+ if (getAddress(owner) !== wallet) continue;
2126
+ verified.set(tokenId, { tokenId, positionManager: pm, owner: wallet });
2127
+ if (verified.size >= targetCount) break;
2128
+ } catch {
2129
+ }
2130
+ }
2131
+ if (verified.size >= targetCount) break;
2132
+ if (fromBlock <= scanFrom) break;
2133
+ toBlock = fromBlock - 1n;
2134
+ }
2135
+ const out = [...verified.values()];
2136
+ out.sort((a, b) => BigInt(a.tokenId) < BigInt(b.tokenId) ? -1 : 1);
2137
+ return out;
2138
+ }
2139
+ async function readUniswapV4PositionInfoRaw(args) {
2140
+ const pm = getAddress(
2141
+ args.positionManagerAddress ? String(args.positionManagerAddress) : getUniswapV4PositionManagerOrThrow(args.chainId)
2142
+ );
2143
+ const chain = defineChain({
2144
+ id: args.chainId,
2145
+ name: `uniswap-v4-${args.chainId}`,
2146
+ nativeCurrency: { name: "ETH", symbol: "ETH", decimals: 18 },
2147
+ rpcUrls: { default: { http: [args.rpcUrl] } }
2148
+ });
2149
+ const client = createPublicClient({ chain, transport: http(args.rpcUrl) });
2150
+ const info = await client.readContract({
2151
+ address: pm,
2152
+ abi: positionInfoAbi,
2153
+ functionName: "positionInfo",
2154
+ args: [BigInt(args.tokenId)]
2155
+ });
2156
+ return { info, positionManager: pm };
2157
+ }
2158
+ async function uniswapV4ListPositionsForMcp(args) {
2159
+ const chainId = typeof args.chainId === "number" ? args.chainId : Number.parseInt(String(args.chainId), 10);
2160
+ if (!Number.isFinite(chainId) || chainId <= 0) {
2161
+ throw new Error("chainId must be a positive integer");
2162
+ }
2163
+ const fromBlock = args.fromBlock != null && String(args.fromBlock).trim() !== "" ? BigInt(String(args.fromBlock).trim()) : void 0;
2164
+ const positions = await listUniswapV4PositionsForWallet({
2165
+ chainId,
2166
+ rpcUrl: args.rpcUrl,
2167
+ walletAddress: args.walletAddress,
2168
+ positionManagerAddress: args.positionManagerAddress,
2169
+ fromBlock,
2170
+ onProgress: args.onProgress,
2171
+ signal: args.signal
2172
+ });
2173
+ return { positions };
2174
+ }
2175
+ function uniswapV4ListPositionsRegistryMcpPlaceholder() {
2176
+ throw new Error(
2177
+ "ctm_uniswap_v4_lp_list_positions must run via continuum-node-sdk MCP (token registry, no RPC scan)."
2178
+ );
2179
+ }
2180
+ function uniswapV4RegisterPositionNftPlaceholder() {
2181
+ throw new Error(
2182
+ "ctm_uniswap_v4_register_position_nft must run via continuum-node-sdk MCP (management-signed addToken)."
2183
+ );
2184
+ }
2185
+ function uniswapV4RegisterPositionFromMintTxPlaceholder() {
2186
+ throw new Error(
2187
+ "ctm_uniswap_v4_register_position_from_mint_tx must run via continuum-node-sdk MCP (management-signed addToken)."
2188
+ );
2189
+ }
2190
+ function isNativeUniswapLpTokenAddress(token) {
2191
+ try {
2192
+ return getAddress(token) === zeroAddress;
2193
+ } catch {
2194
+ return token.toLowerCase() === zeroAddress.toLowerCase();
2195
+ }
2196
+ }
2197
+
2198
+ // src/protocols/evm/uniswap-v4/liquidityMultisign.ts
2199
+ var wethDepositAbi = parseAbi(["function deposit() payable"]);
2200
+ var erc20AllowanceAbi = parseAbi([
2201
+ "function allowance(address owner, address spender) view returns (uint256)",
2202
+ "function decimals() view returns (uint8)"
2203
+ ]);
2204
+ function parseOptionalGasLimitString2(raw) {
2205
+ if (raw == null) return null;
2206
+ const s = String(raw).trim();
2207
+ if (!s) return null;
2208
+ try {
2209
+ if (/^0x[0-9a-fA-F]+$/.test(s)) return BigInt(s);
2210
+ return BigInt(s);
2211
+ } catch {
2212
+ return null;
2213
+ }
2214
+ }
2215
+ function parseTxValueWei(tx) {
2216
+ const raw = tx.value ?? "0";
2217
+ try {
2218
+ if (typeof raw === "string" && /^0x[0-9a-fA-F]+$/.test(raw.trim())) return BigInt(raw.trim());
2219
+ return BigInt(String(raw).trim() || "0");
2220
+ } catch {
2221
+ return 0n;
2222
+ }
2223
+ }
2224
+ function dataHexFromTx(tx) {
2225
+ const d = (tx.data ?? "0x").toString().trim();
2226
+ return d.startsWith("0x") ? d : `0x${d}`;
2227
+ }
2228
+ function parseExtraJsonObject2(detail) {
2229
+ if (!detail) return null;
2230
+ const raw = detail.ExtraJSON ?? detail.extraJSON;
2231
+ if (raw == null) return null;
2232
+ if (typeof raw === "object" && !Array.isArray(raw)) return raw;
2233
+ if (typeof raw === "string" && raw.trim()) {
2234
+ try {
2235
+ const p = JSON.parse(raw);
2236
+ if (p && typeof p === "object" && !Array.isArray(p)) return p;
2237
+ } catch {
2238
+ return null;
2239
+ }
2240
+ }
2241
+ return null;
2242
+ }
2243
+ function uniswapV4LiquidityEvmTypeFromBatchMeta(ex, batchIndex) {
2244
+ if (!ex) return false;
2245
+ const bm = ex.batchMeta;
2246
+ if (!Array.isArray(bm) || !bm[batchIndex] || typeof bm[batchIndex] !== "object" || Array.isArray(bm[batchIndex])) {
2247
+ return false;
2248
+ }
2249
+ const evm0 = bm[batchIndex].evm;
2250
+ if (!evm0 || typeof evm0 !== "object" || Array.isArray(evm0)) return false;
2251
+ return String(evm0.type ?? "") === "uniswap_v4_liquidity_tx";
2252
+ }
2253
+ function isUniswapV4LiquidityEvmSignRequest(detail, batchIndex) {
2254
+ const ex = parseExtraJsonObject2(detail);
2255
+ if (batchIndex != null && batchIndex >= 0) {
2256
+ if (uniswapV4LiquidityEvmTypeFromBatchMeta(ex, batchIndex)) return true;
2257
+ } else if (uniswapV4LiquidityEvmTypeFromBatchMeta(ex, 0)) {
2258
+ return true;
2259
+ }
2260
+ const evm = ex?.evm;
2261
+ if (!evm || typeof evm !== "object" || Array.isArray(evm)) return false;
2262
+ return String(evm.type ?? "") === "uniswap_v4_liquidity_tx";
2263
+ }
2264
+ function defaultGasForAction(action) {
2265
+ switch (action) {
2266
+ case "mint":
2267
+ return UNISWAP_V4_LP_MINT_DEFAULT_GAS_UNITS;
2268
+ case "increase":
2269
+ return UNISWAP_V4_LP_INCREASE_DEFAULT_GAS_UNITS;
2270
+ case "decrease":
2271
+ return UNISWAP_V4_LP_DECREASE_DEFAULT_GAS_UNITS;
2272
+ case "collect":
2273
+ return UNISWAP_V4_LP_COLLECT_DEFAULT_GAS_UNITS;
2274
+ default:
2275
+ return UNISWAP_V4_LP_MINT_DEFAULT_GAS_UNITS;
2276
+ }
2277
+ }
2278
+ async function resolveApproveTargets(args) {
2279
+ const out = [];
2280
+ const pairs = [args.token0, args.token1].filter(Boolean);
2281
+ for (const row of pairs) {
2282
+ const amt = BigInt(row.amount);
2283
+ if (amt <= 0n) continue;
2284
+ if (isNativeUniswapLpTokenAddress(row.tokenAddress)) {
2285
+ if (!args.nativeWrapped) {
2286
+ throw new Error("nativeWrapped is required when LP uses native ETH (0x0) token.");
2287
+ }
2288
+ out.push({ token: getAddress(args.nativeWrapped), amount: amt, kind: "weth_deposit" });
2289
+ continue;
2290
+ }
2291
+ out.push({ token: getAddress(row.tokenAddress), amount: amt, kind: "approve" });
2292
+ }
2293
+ const deduped = [];
2294
+ for (const row of out) {
2295
+ const existing = deduped.find((d) => d.token === row.token && d.kind === row.kind);
2296
+ if (existing) {
2297
+ if (row.amount > existing.amount) existing.amount = row.amount;
2298
+ } else {
2299
+ deduped.push({ ...row });
2300
+ }
2301
+ }
2302
+ const steps = [];
2303
+ for (const row of deduped) {
2304
+ if (row.kind === "weth_deposit") {
2305
+ steps.push(row);
2306
+ continue;
2307
+ }
2308
+ const allowance = await args.publicClient.readContract({
2309
+ address: row.token,
2310
+ abi: erc20AllowanceAbi,
2311
+ functionName: "allowance",
2312
+ args: [args.executor, args.spender]
2313
+ });
2314
+ if (allowance < row.amount) {
2315
+ steps.push(row);
2316
+ }
2317
+ }
2318
+ return steps;
2319
+ }
2320
+ async function buildEvmMultisignBodyUniswapV4LiquidityBatchInternal(args) {
2321
+ const parsed = parseUniswapLpApiSnapshot({ action: args.action, lpResponse: args.lpResponse });
2322
+ const tx = parsed.transaction;
2323
+ const to = getAddress(tx.to);
2324
+ const dataHex = dataHexFromTx(tx);
2325
+ const valueWei = parseTxValueWei(tx);
2326
+ const executor = getAddress(args.executorAddress);
2327
+ const spender = to;
2328
+ const chain = defineChain({
2329
+ id: args.chainId,
2330
+ name: `uniswap-v4-lp-${args.chainId}`,
2331
+ nativeCurrency: { name: "ETH", symbol: "ETH", decimals: 18 },
2332
+ rpcUrls: { default: { http: [args.rpcUrl] } }
2333
+ });
2334
+ const publicClient = createPublicClient({ chain, transport: http(args.rpcUrl) });
2335
+ const approveTargets = await resolveApproveTargets({
2336
+ publicClient,
2337
+ executor,
2338
+ spender,
2339
+ token0: parsed.token0,
2340
+ token1: parsed.token1,
2341
+ nativeWrapped: args.nativeWrapped
2342
+ });
2343
+ const steps = [];
2344
+ for (const target of approveTargets) {
2345
+ if (target.kind === "weth_deposit") {
2346
+ steps.push({
2347
+ to: target.token,
2348
+ data: encodeFunctionData({ abi: wethDepositAbi, functionName: "deposit" }),
2349
+ value: target.amount,
2350
+ fallbackGas: UNISWAP_V4_LP_WETH_DEPOSIT_FALLBACK
2351
+ });
2352
+ steps.push({
2353
+ to: target.token,
2354
+ data: encodeFunctionData({
2355
+ abi: erc20Abi,
2356
+ functionName: "approve",
2357
+ args: [spender, target.amount]
2358
+ }),
2359
+ value: 0n,
2360
+ fallbackGas: UNISWAP_V4_LP_ERC20_APPROVE_FALLBACK
2361
+ });
2362
+ } else {
2363
+ steps.push({
2364
+ to: target.token,
2365
+ data: encodeFunctionData({
2366
+ abi: erc20Abi,
2367
+ functionName: "approve",
2368
+ args: [spender, target.amount]
2369
+ }),
2370
+ value: 0n,
2371
+ fallbackGas: UNISWAP_V4_LP_ERC20_APPROVE_FALLBACK
2372
+ });
2373
+ }
2374
+ }
2375
+ const lpFallbackGas = defaultGasForAction(args.action);
2376
+ const fromTradeApi = parseOptionalGasLimitString2(tx.gasLimit) ?? parseOptionalGasLimitString2(tx.gas);
2377
+ steps.push({
2378
+ to,
2379
+ data: dataHex,
2380
+ value: valueWei,
2381
+ fallbackGas: fromTradeApi != null && fromTradeApi > 0n ? fromTradeApi : lpFallbackGas
2382
+ });
2383
+ const actionLabel = args.action === "mint" ? "mint liquidity" : args.action === "increase" ? "increase liquidity" : args.action === "decrease" ? "decrease liquidity" : "collect fees";
2384
+ const dataNo0x = dataHex.startsWith("0x") ? dataHex.slice(2) : dataHex;
2385
+ const lpIndex = steps.length - 1;
2386
+ return buildEvmMultisignBatch({
2387
+ context: {
2388
+ chainCategory: "evm",
2389
+ keyGen: args.keyGen,
2390
+ purposeText: args.purposeText,
2391
+ chainId: args.chainId,
2392
+ rpcUrl: args.rpcUrl,
2393
+ executorAddress: args.executorAddress,
2394
+ chainDetail: args.chainDetail,
2395
+ useCustomGas: args.useCustomGas,
2396
+ customGasChainDetails: args.customGasChainDetails
2397
+ },
2398
+ steps,
2399
+ purposeSuffix: `Uniswap V4: ${steps.length}-tx batch \u2014 ${actionLabel} (classic ERC-20 approve + Position Manager).`,
2400
+ firstMsgRawNo0x: dataNo0x,
2401
+ destinationAddress: to,
2402
+ buildBatchMeta: ({ index }) => {
2403
+ const isLpStep = index === lpIndex;
2404
+ return {
2405
+ signatureText: JSON.stringify({
2406
+ kind: "UniswapV4Liquidity",
2407
+ action: args.action,
2408
+ step: index,
2409
+ lpTx: isLpStep
2410
+ }),
2411
+ ...isLpStep ? {
2412
+ evm: { type: "uniswap_v4_liquidity_tx", version: 1, chainId: String(args.chainId) },
2413
+ uniswapV4Liquidity: {
2414
+ action: args.action,
2415
+ skipPermit2Batch: true,
2416
+ nftTokenId: args.nftTokenId != null ? String(args.nftTokenId) : void 0,
2417
+ poolReference: args.poolReference,
2418
+ lpResponseSnapshot: args.lpResponse,
2419
+ token0: parsed.token0,
2420
+ token1: parsed.token1,
2421
+ tickLower: parsed.tickLower,
2422
+ tickUpper: parsed.tickUpper,
2423
+ transaction: {
2424
+ to: tx.to,
2425
+ value: tx.value,
2426
+ dataNibbles: dataNo0x.length,
2427
+ gasLimit: tx.gasLimit
2428
+ },
2429
+ originalPurpose: args.purposeText
2430
+ }
2431
+ } : {}
2432
+ };
2433
+ }
2434
+ });
2435
+ }
2436
+ async function buildEvmMultisignBodyUniswapV4MintLiquidityBatch(args) {
2437
+ return buildEvmMultisignBodyUniswapV4LiquidityBatchInternal({ ...args, action: "mint" });
2438
+ }
2439
+ async function buildEvmMultisignBodyUniswapV4IncreaseLiquidityBatch(args) {
2440
+ return buildEvmMultisignBodyUniswapV4LiquidityBatchInternal({ ...args, action: "increase" });
2441
+ }
2442
+ async function buildEvmMultisignBodyUniswapV4DecreaseLiquidityBatch(args) {
2443
+ return buildEvmMultisignBodyUniswapV4LiquidityBatchInternal({ ...args, action: "decrease" });
2444
+ }
2445
+ async function buildEvmMultisignBodyUniswapV4CollectFeesBatch(args) {
2446
+ return buildEvmMultisignBodyUniswapV4LiquidityBatchInternal({ ...args, action: "collect" });
2447
+ }
1324
2448
 
1325
2449
  // src/protocols/evm/uniswap-v4/support.ts
1326
2450
  function computeUniswapV4Session(args) {
@@ -1425,6 +2549,52 @@ var uniswapV4ProtocolModule = {
1425
2549
  amount: { type: "string", required: true, description: "Amount for quote" },
1426
2550
  type: { type: "EXACT_INPUT | EXACT_OUTPUT", required: true, description: "Trade type" }
1427
2551
  }
2552
+ },
2553
+ {
2554
+ id: "uniswap-v4.mint-liquidity",
2555
+ protocolId: UNISWAP_V4_PROTOCOL_ID,
2556
+ chainCategory: "evm",
2557
+ description: "Mint a new Uniswap V4 concentrated liquidity position (Position Manager NFT)",
2558
+ commonParams: ["keyGen", "purposeText", "useCustomGas"],
2559
+ params: {
2560
+ lpResponse: { type: "object", required: true, description: "Full LP API create response" },
2561
+ nativeWrapped: { type: "address", required: false, description: "WETH when pool uses native ETH" },
2562
+ poolReference: { type: "string", required: false, description: "V4 pool id" },
2563
+ uniswapApiKey: { type: "string", required: true, description: "Uniswap API key" }
2564
+ }
2565
+ },
2566
+ {
2567
+ id: "uniswap-v4.increase-liquidity",
2568
+ protocolId: UNISWAP_V4_PROTOCOL_ID,
2569
+ chainCategory: "evm",
2570
+ description: "Increase liquidity on an existing Uniswap V4 position NFT",
2571
+ commonParams: ["keyGen", "purposeText", "useCustomGas"],
2572
+ params: {
2573
+ nftTokenId: { type: "string", required: true, description: "Position NFT token id" },
2574
+ lpResponse: { type: "object", required: true, description: "Full LP API increase response" }
2575
+ }
2576
+ },
2577
+ {
2578
+ id: "uniswap-v4.decrease-liquidity",
2579
+ protocolId: UNISWAP_V4_PROTOCOL_ID,
2580
+ chainCategory: "evm",
2581
+ description: "Decrease liquidity on an existing Uniswap V4 position NFT",
2582
+ commonParams: ["keyGen", "purposeText", "useCustomGas"],
2583
+ params: {
2584
+ nftTokenId: { type: "string", required: true, description: "Position NFT token id" },
2585
+ lpResponse: { type: "object", required: true, description: "Full LP API decrease response" }
2586
+ }
2587
+ },
2588
+ {
2589
+ id: "uniswap-v4.collect-fees",
2590
+ protocolId: UNISWAP_V4_PROTOCOL_ID,
2591
+ chainCategory: "evm",
2592
+ description: "Collect accrued fees from a Uniswap V4 position NFT",
2593
+ commonParams: ["keyGen", "purposeText", "useCustomGas"],
2594
+ params: {
2595
+ nftTokenId: { type: "string", required: true, description: "Position NFT token id" },
2596
+ lpResponse: { type: "object", required: true, description: "Full LP API claim response" }
2597
+ }
1428
2598
  }
1429
2599
  ]
1430
2600
  };
@@ -1436,9 +2606,18 @@ var uniswapV4 = {
1436
2606
  swapFromQuote,
1437
2607
  buildSwapMultisignBody: buildEvmMultisignBodyUniswapV4SkipPermit2Batch,
1438
2608
  quote: uniswapTradeQuote,
2609
+ createLiquidityPosition: uniswapLpCreatePosition,
2610
+ increaseLiquidityPosition: uniswapLpIncreasePosition,
2611
+ decreaseLiquidityPosition: uniswapLpDecreasePosition,
2612
+ claimLiquidityFees: uniswapLpClaimFees,
2613
+ buildMintLiquidityMultisignBody: buildEvmMultisignBodyUniswapV4MintLiquidityBatch,
2614
+ buildIncreaseLiquidityMultisignBody: buildEvmMultisignBodyUniswapV4IncreaseLiquidityBatch,
2615
+ buildDecreaseLiquidityMultisignBody: buildEvmMultisignBodyUniswapV4DecreaseLiquidityBatch,
2616
+ buildCollectFeesMultisignBody: buildEvmMultisignBodyUniswapV4CollectFeesBatch,
2617
+ listPositions: listUniswapV4PositionsForWallet,
1439
2618
  isChainSupported: isUniswapV4ChainSupported
1440
2619
  };
1441
2620
 
1442
- export { MAX_UINT160, MAX_UINT48, PERMIT2_ADDRESS, UNISWAP_SWAP_DEFAULT_DEADLINE_SEC_OFFSET, UNISWAP_SWAP_DEFAULT_EXPIRY_MINUTES, UNISWAP_TRADE_BASE_DEFAULT, UNISWAP_UNIVERSAL_ROUTER_DEFAULT_GAS_UNITS, UNISWAP_UNIVERSAL_ROUTER_VERSION_DEFAULT, UNISWAP_V4_PROTOCOL_ID, applySlippagePercentToApproveWei, buildEvmMultisignBodyUniswapV4SkipPermit2Batch, buildUniswapQuoteRequestBody, buildUniswapV4PurposePrefill, computeUniswapV4Session, createSwap, errorMessageFromUniswapJsonBody, fetchEthereumAddressForKeyGen, formatUniswapAmountFieldFromWei, formatUniswapPercentForUi, formatUniswapQuoteForDisplay, getClassicQuoteFromStoredUniswapResponse, getUniswapUniversalRouterSpenderOrThrow, isUniswapFullQuoteResponseNativeIn, isUniswapTokenInAddressNative, isUniswapV4ChainSupported, isUniswapV4SwapEvmSignRequest, messageFromUniswapHttpResponseBody, parseUniswapChainId, parseUniswapQuoteClassicInOut, parseUniswapQuoteSlippageInfo, quoteSwap, resolveRouterSwapGasUnitsFromSignRequest, swapExactInput, swapFromQuote, swapTransactionDeadlineUnixFromExpiryMinutes, uniswapCreateSwap, uniswapQuoteToJsonQuoteOneLine, uniswapTradeQuote, uniswapV4, uniswapV4ProtocolModule };
2621
+ export { MAX_UINT160, MAX_UINT48, PERMIT2_ADDRESS, UNISWAP_LP_API_BASE_DEFAULT, UNISWAP_LP_DEFAULT_DEADLINE_SEC_OFFSET, UNISWAP_LP_DEFAULT_EXPIRY_MINUTES, UNISWAP_LP_DEFAULT_SLIPPAGE_PERCENT, UNISWAP_SWAP_DEFAULT_DEADLINE_SEC_OFFSET, UNISWAP_SWAP_DEFAULT_EXPIRY_MINUTES, UNISWAP_TRADE_BASE_DEFAULT, UNISWAP_UNIVERSAL_ROUTER_DEFAULT_GAS_UNITS, UNISWAP_UNIVERSAL_ROUTER_VERSION_DEFAULT, UNISWAP_V4_LP_COLLECT_DEFAULT_GAS_UNITS, UNISWAP_V4_LP_DECREASE_DEFAULT_GAS_UNITS, UNISWAP_V4_LP_ERC20_APPROVE_FALLBACK, UNISWAP_V4_LP_INCREASE_DEFAULT_GAS_UNITS, UNISWAP_V4_LP_LOG_CHUNK_SIZE_DEFAULT, UNISWAP_V4_LP_LOG_CHUNK_SIZE_MIN, UNISWAP_V4_LP_MINT_DEFAULT_GAS_UNITS, UNISWAP_V4_LP_POOL_LOOKUP_HINT, UNISWAP_V4_LP_POSITION_REGISTRY_HINT, UNISWAP_V4_LP_WETH_DEPOSIT_FALLBACK, UNISWAP_V4_PROTOCOL_ID, applySlippagePercentToApproveWei, buildEvmMultisignBodyUniswapV4CollectFeesBatch, buildEvmMultisignBodyUniswapV4DecreaseLiquidityBatch, buildEvmMultisignBodyUniswapV4IncreaseLiquidityBatch, buildEvmMultisignBodyUniswapV4MintLiquidityBatch, buildEvmMultisignBodyUniswapV4SkipPermit2Batch, buildUniswapQuoteRequestBody, buildUniswapV4PurposePrefill, computeUniswapV4PoolReference, computeUniswapV4Session, createSwap, errorMessageFromUniswapJsonBody, extractUniswapLpTokenAmounts, extractUniswapLpTransaction, fetchEthereumAddressForKeyGen, formatUniswapAmountFieldFromWei, formatUniswapLpAmountHuman, formatUniswapPercentForUi, formatUniswapQuoteForDisplay, formatUniswapV4PositionNotFoundError, getClassicQuoteFromStoredUniswapResponse, getUniswapUniversalRouterSpenderOrThrow, getUniswapV4PositionManagerDeployBlock, getUniswapV4PositionManagerOrThrow, isEthGetLogsBlockRangeTooLargeError, isNativeUniswapLpTokenAddress, isUniswapFullQuoteResponseNativeIn, isUniswapTokenInAddressNative, isUniswapV4ChainSupported, isUniswapV4LiquidityEvmSignRequest, isUniswapV4SwapEvmSignRequest, listUniswapV4PositionsForWallet, listUniswapV4StandardLpPools, messageFromUniswapHttpResponseBody, parseUniswapChainId, parseUniswapLpApiSnapshot, parseUniswapQuoteClassicInOut, parseUniswapQuoteSlippageInfo, parseUniswapV4ScanFromDateYmd, quoteSwap, readUniswapV4PositionInfoRaw, resolveBlockAtOrAfterUnixTime, resolveRouterSwapGasUnitsFromSignRequest, resolveUniswapV4LpExistingPoolFromKey, resolveUniswapV4LpPoolPreset, resolveUniswapV4PositionScanFromDate, sortUniswapV4PoolCurrencies, swapExactInput, swapFromQuote, swapTransactionDeadlineUnixFromExpiryMinutes, tryGetUniswapV4PositionManager, uniswapCreateSwap, uniswapLpClaimFees, uniswapLpCreatePosition, uniswapLpDecreasePosition, uniswapLpIncreasePosition, uniswapLpTxFieldForAction, uniswapQuoteToJsonQuoteOneLine, uniswapTradeQuote, uniswapV4, uniswapV4ListPositionsForMcp, uniswapV4ListPositionsFromRegistryForMcp, uniswapV4ListPositionsRegistryMcpPlaceholder, uniswapV4ListStandardLpPools, uniswapV4PositionMintedTokenIdsFromReceipt, uniswapV4ProtocolModule, uniswapV4RegisterPositionFromMintTxPlaceholder, uniswapV4RegisterPositionNftPlaceholder };
1443
2622
  //# sourceMappingURL=index.js.map
1444
2623
  //# sourceMappingURL=index.js.map