@continuumdao/ctm-mpc-defi 0.2.2 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -473,6 +473,44 @@ var UNISWAP_UNIVERSAL_ROUTER_DEFAULT_GAS_UNITS = 1500000n;
473
473
  var UNISWAP_TRADE_BASE_DEFAULT = "https://trade-api.gateway.uniswap.org/v1";
474
474
  var UNISWAP_UNIVERSAL_ROUTER_VERSION_DEFAULT = "2.0";
475
475
  var UNISWAP_SWAP_DEFAULT_EXPIRY_MINUTES = 30;
476
+ var UNISWAP_LP_DEFAULT_EXPIRY_MINUTES = 30;
477
+ var UNISWAP_LP_DEFAULT_DEADLINE_SEC_OFFSET = UNISWAP_LP_DEFAULT_EXPIRY_MINUTES * 60;
478
+ var UNISWAP_LP_DEFAULT_SLIPPAGE_PERCENT = 0.5;
479
+ var POSITION_MANAGER_BY_CHAIN = {
480
+ 1: "0xbd216513d74c8cf14cf4747e6aaa6420ff64ee9e",
481
+ 10: "0x3c3ea4b57a46241e54610e5f022e5c45859a1017",
482
+ 137: "0x1ec2ebf4f37e7363fdfe3551602425af0b3ceef9",
483
+ 42161: "0xd88f38f930b7952f2db2432cb002e7abbf3dd869",
484
+ 8453: "0x7C5f5A4bBd8fD63184577525326123B519429bDc",
485
+ 11155111: "0x4B2C77d209D3405F41a037Ec6c77F7F5b8e2ca80",
486
+ 130: "0x0d97dc33264bfc1c226207428a79b26757fb9dc3",
487
+ 1868: "0x0e2850543f69f678257266e0907ff9a58b3f13de",
488
+ 59144: "0x661e93cca42afacb172121ef892830ca3b70f08d"
489
+ };
490
+ function getUniswapV4PositionManagerOrThrow(chainId) {
491
+ const raw = POSITION_MANAGER_BY_CHAIN[chainId];
492
+ if (!raw || !raw.startsWith("0x") || raw.length !== 42) {
493
+ throw new Error(
494
+ `No Uniswap V4 PositionManager is configured for chainId ${chainId}. Add this chain to uniswap-v4/constants or pass position manager from LP API response.`
495
+ );
496
+ }
497
+ return viem.getAddress(raw);
498
+ }
499
+ var POSITION_MANAGER_DEPLOY_BLOCK_BY_CHAIN = {
500
+ /** Ethereum mainnet — Uniswap v4 launch (Jan 2025). */
501
+ 1: 22938741n
502
+ };
503
+ var UNISWAP_V4_LP_LOG_CHUNK_SIZE_DEFAULT = 200n;
504
+ var UNISWAP_V4_LP_LOG_CHUNK_SIZE_MIN = 10n;
505
+ function getUniswapV4PositionManagerDeployBlock(chainId) {
506
+ return POSITION_MANAGER_DEPLOY_BLOCK_BY_CHAIN[chainId];
507
+ }
508
+ var UNISWAP_V4_LP_MINT_DEFAULT_GAS_UNITS = 1800000n;
509
+ var UNISWAP_V4_LP_INCREASE_DEFAULT_GAS_UNITS = 1500000n;
510
+ var UNISWAP_V4_LP_DECREASE_DEFAULT_GAS_UNITS = 1200000n;
511
+ var UNISWAP_V4_LP_COLLECT_DEFAULT_GAS_UNITS = 900000n;
512
+ var UNISWAP_V4_LP_ERC20_APPROVE_FALLBACK = 100000n;
513
+ var UNISWAP_V4_LP_WETH_DEPOSIT_FALLBACK = 120000n;
476
514
  var DEFAULT_TRADE_BASE = "https://trade-api.gateway.uniswap.org/v1";
477
515
  var UNISWAP_QUOTE_HEADERS_BASE = {
478
516
  "Content-Type": "application/json",
@@ -722,7 +760,16 @@ function parseUniswapQuoteClassicInOut(res) {
722
760
  const input = q.input;
723
761
  const output = q.output;
724
762
  const inAm = input?.amount;
725
- const outAm = output?.amount;
763
+ let outAm = output?.amount;
764
+ if (typeof outAm !== "string" || !outAm) {
765
+ const agg = q.aggregatedOutputs;
766
+ if (Array.isArray(agg) && agg.length > 0) {
767
+ const first = agg[0];
768
+ if (typeof first?.amount === "string" && first.amount) {
769
+ outAm = first.amount;
770
+ }
771
+ }
772
+ }
726
773
  if (typeof inAm !== "string" || !inAm || typeof outAm !== "string" || !outAm) return null;
727
774
  try {
728
775
  return { inputWei: BigInt(inAm), outputWei: BigInt(outAm) };
@@ -1290,6 +1337,656 @@ async function buildEvmMultisignBodyUniswapV4SkipPermit2Batch(args) {
1290
1337
  });
1291
1338
  }
1292
1339
 
1340
+ // src/protocols/evm/uniswap-v4/liquidityApi.ts
1341
+ var LP_HEADERS_BASE = {
1342
+ "Content-Type": "application/json",
1343
+ Accept: "application/json",
1344
+ "User-Agent": "ctm-mpc-defi uniswapLpApi/1.0 (TS)"
1345
+ };
1346
+ function trimAddr2(a) {
1347
+ return a.trim();
1348
+ }
1349
+ function lpDeadlineUnix(nowSec = Math.floor(Date.now() / 1e3)) {
1350
+ return nowSec + UNISWAP_LP_DEFAULT_DEADLINE_SEC_OFFSET;
1351
+ }
1352
+ function resolveLpBaseUrl(baseUrl) {
1353
+ const raw = (baseUrl ?? UNISWAP_TRADE_BASE_DEFAULT).replace(/\/$/, "");
1354
+ return raw;
1355
+ }
1356
+ function resolveLpPath(baseUrl, action) {
1357
+ const normalized = baseUrl.replace(/\/$/, "");
1358
+ if (normalized.includes("api.uniswap.org")) {
1359
+ return `${normalized}/lp/${action}`;
1360
+ }
1361
+ return `${normalized}/lp/${action}`;
1362
+ }
1363
+ async function postUniswapLpApi(args) {
1364
+ const useProxy = args.useServerProxy !== false && typeof globalThis !== "undefined" && typeof globalThis.window !== "undefined";
1365
+ if (useProxy && args.proxyPath) {
1366
+ const fn2 = args.fetchImpl ?? globalThis.fetch;
1367
+ const res2 = await fn2(args.proxyPath, {
1368
+ method: "POST",
1369
+ headers: { "Content-Type": "application/json" },
1370
+ body: JSON.stringify({
1371
+ uniswapApiKey: args.uniswapApiKey,
1372
+ baseUrl: args.baseUrl,
1373
+ body: args.body
1374
+ }),
1375
+ credentials: "same-origin"
1376
+ });
1377
+ const text2 = await res2.text();
1378
+ if (!res2.ok) {
1379
+ let errMsg = res2.statusText;
1380
+ try {
1381
+ const j = JSON.parse(text2);
1382
+ if (j?.error?.trim()) errMsg = j.error.trim();
1383
+ } catch {
1384
+ if (text2.trim()) errMsg = text2.slice(0, 500);
1385
+ }
1386
+ throw new Error(`Uniswap LP proxy failed: ${errMsg}`);
1387
+ }
1388
+ return JSON.parse(text2);
1389
+ }
1390
+ const base = resolveLpBaseUrl(args.baseUrl);
1391
+ const url = resolveLpPath(base, args.path);
1392
+ const fn = args.fetchImpl ?? globalThis.fetch;
1393
+ const res = await fn(url, {
1394
+ method: "POST",
1395
+ headers: {
1396
+ ...LP_HEADERS_BASE,
1397
+ "x-api-key": args.uniswapApiKey.trim()
1398
+ },
1399
+ body: JSON.stringify(args.body)
1400
+ });
1401
+ const text = await res.text();
1402
+ if (!res.ok) {
1403
+ throw new Error(
1404
+ `Uniswap LP POST /${args.path} failed: ${messageFromUniswapHttpResponseBody(text, res.status, res.statusText)}`
1405
+ );
1406
+ }
1407
+ return JSON.parse(text);
1408
+ }
1409
+ function extractUniswapLpTransaction(response, field) {
1410
+ const tx = response[field];
1411
+ if (!tx || typeof tx !== "object" || Array.isArray(tx)) {
1412
+ throw new Error(`Uniswap LP response missing \`${field}\` transaction object.`);
1413
+ }
1414
+ const o = tx;
1415
+ const to = String(o.to ?? "").trim();
1416
+ const data = String(o.data ?? "").trim();
1417
+ if (!to.startsWith("0x") || !data.startsWith("0x") || data === "0x") {
1418
+ throw new Error(`Uniswap LP \`${field}\` transaction has invalid to/data.`);
1419
+ }
1420
+ return {
1421
+ to,
1422
+ from: o.from != null ? String(o.from) : void 0,
1423
+ data,
1424
+ value: String(o.value ?? "0"),
1425
+ chainId: typeof o.chainId === "number" ? o.chainId : void 0,
1426
+ gasLimit: o.gasLimit != null ? String(o.gasLimit) : void 0,
1427
+ gasPrice: o.gasPrice != null ? String(o.gasPrice) : void 0,
1428
+ maxFeePerGas: o.maxFeePerGas != null ? String(o.maxFeePerGas) : void 0,
1429
+ maxPriorityFeePerGas: o.maxPriorityFeePerGas != null ? String(o.maxPriorityFeePerGas) : void 0
1430
+ };
1431
+ }
1432
+ function extractUniswapLpTokenAmounts(response) {
1433
+ const read = (key) => {
1434
+ const raw = response[key];
1435
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
1436
+ const o = raw;
1437
+ const tokenAddress = String(o.tokenAddress ?? o.token ?? "").trim();
1438
+ const amount = String(o.amount ?? "").trim();
1439
+ if (!tokenAddress.startsWith("0x") || !amount) return void 0;
1440
+ return { tokenAddress, amount };
1441
+ };
1442
+ return { token0: read("token0"), token1: read("token1") };
1443
+ }
1444
+ async function uniswapLpCreatePosition(args) {
1445
+ const body = {
1446
+ protocol: "V4",
1447
+ walletAddress: trimAddr2(args.walletAddress),
1448
+ chainId: args.chainId,
1449
+ independentToken: {
1450
+ tokenAddress: trimAddr2(args.independentToken.tokenAddress),
1451
+ amount: String(args.independentToken.amount).trim()
1452
+ },
1453
+ slippageTolerance: args.slippageTolerance ?? UNISWAP_LP_DEFAULT_SLIPPAGE_PERCENT,
1454
+ deadline: args.deadline ?? lpDeadlineUnix(),
1455
+ simulateTransaction: args.simulateTransaction ?? false
1456
+ };
1457
+ if (args.existingPool) {
1458
+ body.existingPool = {
1459
+ token0Address: trimAddr2(args.existingPool.token0Address),
1460
+ token1Address: trimAddr2(args.existingPool.token1Address),
1461
+ poolReference: trimAddr2(args.existingPool.poolReference)
1462
+ };
1463
+ }
1464
+ if (args.newPool) {
1465
+ body.newPool = {
1466
+ token0Address: trimAddr2(args.newPool.token0Address),
1467
+ token1Address: trimAddr2(args.newPool.token1Address),
1468
+ fee: args.newPool.fee,
1469
+ tickSpacing: args.newPool.tickSpacing,
1470
+ initialPrice: String(args.newPool.initialPrice).trim(),
1471
+ ...args.newPool.hooks ? { hooks: trimAddr2(args.newPool.hooks) } : {}
1472
+ };
1473
+ }
1474
+ if (!args.existingPool && !args.newPool) {
1475
+ throw new Error("Provide existingPool or newPool for LP create.");
1476
+ }
1477
+ if (args.priceBounds) {
1478
+ body.priceBounds = {
1479
+ minPrice: String(args.priceBounds.minPrice).trim(),
1480
+ maxPrice: String(args.priceBounds.maxPrice).trim()
1481
+ };
1482
+ }
1483
+ if (args.tickBounds) {
1484
+ body.tickBounds = {
1485
+ tickLower: args.tickBounds.tickLower,
1486
+ tickUpper: args.tickBounds.tickUpper
1487
+ };
1488
+ }
1489
+ if (!args.priceBounds && !args.tickBounds) {
1490
+ throw new Error("Provide priceBounds or tickBounds for LP create.");
1491
+ }
1492
+ if (args.batchPermitData) body.batchPermitData = args.batchPermitData;
1493
+ if (args.signature) body.signature = args.signature;
1494
+ return postUniswapLpApi({
1495
+ uniswapApiKey: args.uniswapApiKey,
1496
+ path: "create",
1497
+ body,
1498
+ baseUrl: args.baseUrl,
1499
+ fetchImpl: args.fetchImpl,
1500
+ useServerProxy: args.useServerProxy,
1501
+ proxyPath: "/api/uniswap/liquidity/create"
1502
+ });
1503
+ }
1504
+ async function uniswapLpIncreasePosition(args) {
1505
+ const body = {
1506
+ protocol: "V4",
1507
+ walletAddress: trimAddr2(args.walletAddress),
1508
+ chainId: args.chainId,
1509
+ token0Address: trimAddr2(args.token0Address),
1510
+ token1Address: trimAddr2(args.token1Address),
1511
+ nftTokenId: String(args.nftTokenId),
1512
+ independentToken: {
1513
+ tokenAddress: trimAddr2(args.independentToken.tokenAddress),
1514
+ amount: String(args.independentToken.amount).trim()
1515
+ },
1516
+ slippageTolerance: args.slippageTolerance ?? UNISWAP_LP_DEFAULT_SLIPPAGE_PERCENT,
1517
+ deadline: args.deadline ?? lpDeadlineUnix(),
1518
+ simulateTransaction: args.simulateTransaction ?? false
1519
+ };
1520
+ if (args.v4BatchPermitData) body.v4BatchPermitData = args.v4BatchPermitData;
1521
+ if (args.signature) body.signature = args.signature;
1522
+ return postUniswapLpApi({
1523
+ uniswapApiKey: args.uniswapApiKey,
1524
+ path: "increase",
1525
+ body,
1526
+ baseUrl: args.baseUrl,
1527
+ fetchImpl: args.fetchImpl,
1528
+ useServerProxy: args.useServerProxy,
1529
+ proxyPath: "/api/uniswap/liquidity/increase"
1530
+ });
1531
+ }
1532
+ async function uniswapLpDecreasePosition(args) {
1533
+ const pct = Math.trunc(args.liquidityPercentageToDecrease);
1534
+ if (!Number.isFinite(pct) || pct < 1 || pct > 100) {
1535
+ throw new Error("liquidityPercentageToDecrease must be an integer from 1 to 100.");
1536
+ }
1537
+ const body = {
1538
+ protocol: "V4",
1539
+ walletAddress: trimAddr2(args.walletAddress),
1540
+ chainId: args.chainId,
1541
+ token0Address: trimAddr2(args.token0Address),
1542
+ token1Address: trimAddr2(args.token1Address),
1543
+ nftTokenId: String(args.nftTokenId),
1544
+ liquidityPercentageToDecrease: pct,
1545
+ slippageTolerance: args.slippageTolerance ?? UNISWAP_LP_DEFAULT_SLIPPAGE_PERCENT,
1546
+ deadline: args.deadline ?? lpDeadlineUnix(),
1547
+ simulateTransaction: args.simulateTransaction ?? false
1548
+ };
1549
+ return postUniswapLpApi({
1550
+ uniswapApiKey: args.uniswapApiKey,
1551
+ path: "decrease",
1552
+ body,
1553
+ baseUrl: args.baseUrl,
1554
+ fetchImpl: args.fetchImpl,
1555
+ useServerProxy: args.useServerProxy,
1556
+ proxyPath: "/api/uniswap/liquidity/decrease"
1557
+ });
1558
+ }
1559
+ async function uniswapLpClaimFees(args) {
1560
+ const body = {
1561
+ protocol: "V4",
1562
+ walletAddress: trimAddr2(args.walletAddress),
1563
+ chainId: args.chainId,
1564
+ tokenId: String(args.tokenId),
1565
+ simulateTransaction: args.simulateTransaction ?? false
1566
+ };
1567
+ return postUniswapLpApi({
1568
+ uniswapApiKey: args.uniswapApiKey,
1569
+ path: "claim",
1570
+ body,
1571
+ baseUrl: args.baseUrl,
1572
+ fetchImpl: args.fetchImpl,
1573
+ useServerProxy: args.useServerProxy,
1574
+ proxyPath: "/api/uniswap/liquidity/claim"
1575
+ });
1576
+ }
1577
+ var TX_FIELD_BY_ACTION = {
1578
+ mint: "create",
1579
+ increase: "increase",
1580
+ decrease: "decrease",
1581
+ collect: "claim"
1582
+ };
1583
+ function parseUniswapLpApiSnapshot(args) {
1584
+ const field = TX_FIELD_BY_ACTION[args.action];
1585
+ const transaction = extractUniswapLpTransaction(args.lpResponse, field);
1586
+ const amounts = extractUniswapLpTokenAmounts(args.lpResponse);
1587
+ const tickLower = typeof args.lpResponse.tickLower === "number" ? args.lpResponse.tickLower : void 0;
1588
+ const tickUpper = typeof args.lpResponse.tickUpper === "number" ? args.lpResponse.tickUpper : void 0;
1589
+ const minPrice = typeof args.lpResponse.minPrice === "string" ? args.lpResponse.minPrice : void 0;
1590
+ const maxPrice = typeof args.lpResponse.maxPrice === "string" ? args.lpResponse.maxPrice : void 0;
1591
+ return {
1592
+ transaction,
1593
+ token0: amounts.token0,
1594
+ token1: amounts.token1,
1595
+ tickLower,
1596
+ tickUpper,
1597
+ minPrice,
1598
+ maxPrice
1599
+ };
1600
+ }
1601
+ var erc721BalanceAbi = viem.parseAbi([
1602
+ "function balanceOf(address owner) view returns (uint256)",
1603
+ "function ownerOf(uint256 tokenId) view returns (address)"
1604
+ ]);
1605
+ viem.parseAbi([
1606
+ "function positionInfo(uint256 tokenId) view returns (uint256 info)"
1607
+ ]);
1608
+ viem.parseAbiItem(
1609
+ "event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)"
1610
+ );
1611
+ function throwIfScanAborted(signal) {
1612
+ if (signal?.aborted) {
1613
+ throw new DOMException("Position scan aborted.", "AbortError");
1614
+ }
1615
+ }
1616
+ var TRANSFER_EVENT = {
1617
+ type: "event",
1618
+ name: "Transfer",
1619
+ inputs: [
1620
+ { indexed: true, name: "from", type: "address" },
1621
+ { indexed: true, name: "to", type: "address" },
1622
+ { indexed: true, name: "tokenId", type: "uint256" }
1623
+ ]
1624
+ };
1625
+ function isEthGetLogsBlockRangeTooLargeError(err) {
1626
+ const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();
1627
+ 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");
1628
+ }
1629
+ async function getTransferLogsForWalletInRange(args) {
1630
+ const { client, positionManager, wallet, fromBlock, toBlock } = args;
1631
+ let chunkSize = args.chunkSize < UNISWAP_V4_LP_LOG_CHUNK_SIZE_MIN ? UNISWAP_V4_LP_LOG_CHUNK_SIZE_MIN : args.chunkSize;
1632
+ const out = [];
1633
+ let from = fromBlock;
1634
+ while (from <= toBlock) {
1635
+ let to = from + chunkSize - 1n > toBlock ? toBlock : from + chunkSize - 1n;
1636
+ for (; ; ) {
1637
+ try {
1638
+ const [toLogs, fromLogs] = await Promise.all([
1639
+ client.getLogs({
1640
+ address: positionManager,
1641
+ event: TRANSFER_EVENT,
1642
+ args: { to: wallet },
1643
+ fromBlock: from,
1644
+ toBlock: to
1645
+ }),
1646
+ client.getLogs({
1647
+ address: positionManager,
1648
+ event: TRANSFER_EVENT,
1649
+ args: { from: wallet },
1650
+ fromBlock: from,
1651
+ toBlock: to
1652
+ })
1653
+ ]);
1654
+ out.push(...toLogs, ...fromLogs);
1655
+ from = to + 1n;
1656
+ break;
1657
+ } catch (err) {
1658
+ if (!isEthGetLogsBlockRangeTooLargeError(err) || chunkSize <= UNISWAP_V4_LP_LOG_CHUNK_SIZE_MIN) {
1659
+ throw err;
1660
+ }
1661
+ chunkSize = chunkSize / 2n;
1662
+ if (chunkSize < UNISWAP_V4_LP_LOG_CHUNK_SIZE_MIN) {
1663
+ chunkSize = UNISWAP_V4_LP_LOG_CHUNK_SIZE_MIN;
1664
+ }
1665
+ to = from + chunkSize - 1n > toBlock ? toBlock : from + chunkSize - 1n;
1666
+ }
1667
+ }
1668
+ }
1669
+ return out;
1670
+ }
1671
+ function defaultScanFromBlock(args) {
1672
+ if (args.fromBlock != null) return args.fromBlock;
1673
+ const deploy = getUniswapV4PositionManagerDeployBlock(args.chainId);
1674
+ if (deploy != null) return deploy;
1675
+ return args.latest > args.maxBlocksToScan ? args.latest - args.maxBlocksToScan : 0n;
1676
+ }
1677
+ async function listUniswapV4PositionsForWallet(args) {
1678
+ throwIfScanAborted(args.signal);
1679
+ const wallet = viem.getAddress(args.walletAddress);
1680
+ const pm = viem.getAddress(
1681
+ args.positionManagerAddress ? String(args.positionManagerAddress) : getUniswapV4PositionManagerOrThrow(args.chainId)
1682
+ );
1683
+ const chain = viem.defineChain({
1684
+ id: args.chainId,
1685
+ name: `uniswap-v4-${args.chainId}`,
1686
+ nativeCurrency: { name: "ETH", symbol: "ETH", decimals: 18 },
1687
+ rpcUrls: { default: { http: [args.rpcUrl] } }
1688
+ });
1689
+ const client = viem.createPublicClient({ chain, transport: viem.http(args.rpcUrl) });
1690
+ const latest = await client.getBlockNumber();
1691
+ const maxScan = args.maxBlocksToScan ?? 500000n;
1692
+ const chunkSize = args.chunkSize ?? UNISWAP_V4_LP_LOG_CHUNK_SIZE_DEFAULT;
1693
+ const scanFrom = defaultScanFromBlock({
1694
+ chainId: args.chainId,
1695
+ latest,
1696
+ fromBlock: args.fromBlock,
1697
+ maxBlocksToScan: maxScan
1698
+ });
1699
+ const balance = await client.readContract({
1700
+ address: pm,
1701
+ abi: erc721BalanceAbi,
1702
+ functionName: "balanceOf",
1703
+ args: [wallet]
1704
+ });
1705
+ const targetCount = Number(balance);
1706
+ const emitProgress = (scanningFromBlock, scanningToBlock, foundCount) => {
1707
+ args.onProgress?.({
1708
+ latestBlock: latest.toString(),
1709
+ scanFromBlock: scanFrom.toString(),
1710
+ scanningFromBlock: scanningFromBlock.toString(),
1711
+ scanningToBlock: scanningToBlock.toString(),
1712
+ foundCount,
1713
+ targetCount
1714
+ });
1715
+ };
1716
+ if (balance === 0n) {
1717
+ emitProgress(latest, latest, 0);
1718
+ return [];
1719
+ }
1720
+ const candidates = /* @__PURE__ */ new Set();
1721
+ const verified = /* @__PURE__ */ new Map();
1722
+ let toBlock = latest;
1723
+ while (toBlock >= scanFrom && verified.size < targetCount) {
1724
+ throwIfScanAborted(args.signal);
1725
+ let fromBlock = toBlock >= chunkSize - 1n ? toBlock - chunkSize + 1n : 0n;
1726
+ if (fromBlock < scanFrom) fromBlock = scanFrom;
1727
+ emitProgress(fromBlock, toBlock, verified.size);
1728
+ const logs = await getTransferLogsForWalletInRange({
1729
+ client,
1730
+ positionManager: pm,
1731
+ wallet,
1732
+ fromBlock,
1733
+ toBlock,
1734
+ chunkSize
1735
+ });
1736
+ for (const log of logs) {
1737
+ const tokenId = log.args.tokenId?.toString();
1738
+ if (!tokenId) continue;
1739
+ const to = log.args.to != null ? viem.getAddress(log.args.to) : null;
1740
+ const from = log.args.from != null ? viem.getAddress(log.args.from) : null;
1741
+ if (to === wallet) candidates.add(tokenId);
1742
+ if (from === wallet) candidates.delete(tokenId);
1743
+ }
1744
+ for (const tokenId of candidates) {
1745
+ if (verified.has(tokenId)) continue;
1746
+ try {
1747
+ const owner = await client.readContract({
1748
+ address: pm,
1749
+ abi: erc721BalanceAbi,
1750
+ functionName: "ownerOf",
1751
+ args: [BigInt(tokenId)]
1752
+ });
1753
+ if (viem.getAddress(owner) !== wallet) continue;
1754
+ verified.set(tokenId, { tokenId, positionManager: pm, owner: wallet });
1755
+ if (verified.size >= targetCount) break;
1756
+ } catch {
1757
+ }
1758
+ }
1759
+ if (verified.size >= targetCount) break;
1760
+ if (fromBlock <= scanFrom) break;
1761
+ toBlock = fromBlock - 1n;
1762
+ }
1763
+ const out = [...verified.values()];
1764
+ out.sort((a, b) => BigInt(a.tokenId) < BigInt(b.tokenId) ? -1 : 1);
1765
+ return out;
1766
+ }
1767
+ function isNativeUniswapLpTokenAddress(token) {
1768
+ try {
1769
+ return viem.getAddress(token) === viem.zeroAddress;
1770
+ } catch {
1771
+ return token.toLowerCase() === viem.zeroAddress.toLowerCase();
1772
+ }
1773
+ }
1774
+
1775
+ // src/protocols/evm/uniswap-v4/liquidityMultisign.ts
1776
+ var wethDepositAbi = viem.parseAbi(["function deposit() payable"]);
1777
+ var erc20AllowanceAbi = viem.parseAbi([
1778
+ "function allowance(address owner, address spender) view returns (uint256)",
1779
+ "function decimals() view returns (uint8)"
1780
+ ]);
1781
+ function parseOptionalGasLimitString2(raw) {
1782
+ if (raw == null) return null;
1783
+ const s = String(raw).trim();
1784
+ if (!s) return null;
1785
+ try {
1786
+ if (/^0x[0-9a-fA-F]+$/.test(s)) return BigInt(s);
1787
+ return BigInt(s);
1788
+ } catch {
1789
+ return null;
1790
+ }
1791
+ }
1792
+ function parseTxValueWei(tx) {
1793
+ const raw = tx.value ?? "0";
1794
+ try {
1795
+ if (typeof raw === "string" && /^0x[0-9a-fA-F]+$/.test(raw.trim())) return BigInt(raw.trim());
1796
+ return BigInt(String(raw).trim() || "0");
1797
+ } catch {
1798
+ return 0n;
1799
+ }
1800
+ }
1801
+ function dataHexFromTx(tx) {
1802
+ const d = (tx.data ?? "0x").toString().trim();
1803
+ return d.startsWith("0x") ? d : `0x${d}`;
1804
+ }
1805
+ function defaultGasForAction(action) {
1806
+ switch (action) {
1807
+ case "mint":
1808
+ return UNISWAP_V4_LP_MINT_DEFAULT_GAS_UNITS;
1809
+ case "increase":
1810
+ return UNISWAP_V4_LP_INCREASE_DEFAULT_GAS_UNITS;
1811
+ case "decrease":
1812
+ return UNISWAP_V4_LP_DECREASE_DEFAULT_GAS_UNITS;
1813
+ case "collect":
1814
+ return UNISWAP_V4_LP_COLLECT_DEFAULT_GAS_UNITS;
1815
+ default:
1816
+ return UNISWAP_V4_LP_MINT_DEFAULT_GAS_UNITS;
1817
+ }
1818
+ }
1819
+ async function resolveApproveTargets(args) {
1820
+ const out = [];
1821
+ const pairs = [args.token0, args.token1].filter(Boolean);
1822
+ for (const row of pairs) {
1823
+ const amt = BigInt(row.amount);
1824
+ if (amt <= 0n) continue;
1825
+ if (isNativeUniswapLpTokenAddress(row.tokenAddress)) {
1826
+ if (!args.nativeWrapped) {
1827
+ throw new Error("nativeWrapped is required when LP uses native ETH (0x0) token.");
1828
+ }
1829
+ out.push({ token: viem.getAddress(args.nativeWrapped), amount: amt, kind: "weth_deposit" });
1830
+ continue;
1831
+ }
1832
+ out.push({ token: viem.getAddress(row.tokenAddress), amount: amt, kind: "approve" });
1833
+ }
1834
+ const deduped = [];
1835
+ for (const row of out) {
1836
+ const existing = deduped.find((d) => d.token === row.token && d.kind === row.kind);
1837
+ if (existing) {
1838
+ if (row.amount > existing.amount) existing.amount = row.amount;
1839
+ } else {
1840
+ deduped.push({ ...row });
1841
+ }
1842
+ }
1843
+ const steps = [];
1844
+ for (const row of deduped) {
1845
+ if (row.kind === "weth_deposit") {
1846
+ steps.push(row);
1847
+ continue;
1848
+ }
1849
+ const allowance = await args.publicClient.readContract({
1850
+ address: row.token,
1851
+ abi: erc20AllowanceAbi,
1852
+ functionName: "allowance",
1853
+ args: [args.executor, args.spender]
1854
+ });
1855
+ if (allowance < row.amount) {
1856
+ steps.push(row);
1857
+ }
1858
+ }
1859
+ return steps;
1860
+ }
1861
+ async function buildEvmMultisignBodyUniswapV4LiquidityBatchInternal(args) {
1862
+ const parsed = parseUniswapLpApiSnapshot({ action: args.action, lpResponse: args.lpResponse });
1863
+ const tx = parsed.transaction;
1864
+ const to = viem.getAddress(tx.to);
1865
+ const dataHex = dataHexFromTx(tx);
1866
+ const valueWei = parseTxValueWei(tx);
1867
+ const executor = viem.getAddress(args.executorAddress);
1868
+ const spender = to;
1869
+ const chain = viem.defineChain({
1870
+ id: args.chainId,
1871
+ name: `uniswap-v4-lp-${args.chainId}`,
1872
+ nativeCurrency: { name: "ETH", symbol: "ETH", decimals: 18 },
1873
+ rpcUrls: { default: { http: [args.rpcUrl] } }
1874
+ });
1875
+ const publicClient = viem.createPublicClient({ chain, transport: viem.http(args.rpcUrl) });
1876
+ const approveTargets = await resolveApproveTargets({
1877
+ publicClient,
1878
+ executor,
1879
+ spender,
1880
+ token0: parsed.token0,
1881
+ token1: parsed.token1,
1882
+ nativeWrapped: args.nativeWrapped
1883
+ });
1884
+ const steps = [];
1885
+ for (const target of approveTargets) {
1886
+ if (target.kind === "weth_deposit") {
1887
+ steps.push({
1888
+ to: target.token,
1889
+ data: viem.encodeFunctionData({ abi: wethDepositAbi, functionName: "deposit" }),
1890
+ value: target.amount,
1891
+ fallbackGas: UNISWAP_V4_LP_WETH_DEPOSIT_FALLBACK
1892
+ });
1893
+ steps.push({
1894
+ to: target.token,
1895
+ data: viem.encodeFunctionData({
1896
+ abi: viem.erc20Abi,
1897
+ functionName: "approve",
1898
+ args: [spender, target.amount]
1899
+ }),
1900
+ value: 0n,
1901
+ fallbackGas: UNISWAP_V4_LP_ERC20_APPROVE_FALLBACK
1902
+ });
1903
+ } else {
1904
+ steps.push({
1905
+ to: target.token,
1906
+ data: viem.encodeFunctionData({
1907
+ abi: viem.erc20Abi,
1908
+ functionName: "approve",
1909
+ args: [spender, target.amount]
1910
+ }),
1911
+ value: 0n,
1912
+ fallbackGas: UNISWAP_V4_LP_ERC20_APPROVE_FALLBACK
1913
+ });
1914
+ }
1915
+ }
1916
+ const lpFallbackGas = defaultGasForAction(args.action);
1917
+ const fromTradeApi = parseOptionalGasLimitString2(tx.gasLimit) ?? parseOptionalGasLimitString2(tx.gas);
1918
+ steps.push({
1919
+ to,
1920
+ data: dataHex,
1921
+ value: valueWei,
1922
+ fallbackGas: fromTradeApi != null && fromTradeApi > 0n ? fromTradeApi : lpFallbackGas
1923
+ });
1924
+ const actionLabel = args.action === "mint" ? "mint liquidity" : args.action === "increase" ? "increase liquidity" : args.action === "decrease" ? "decrease liquidity" : "collect fees";
1925
+ const dataNo0x = dataHex.startsWith("0x") ? dataHex.slice(2) : dataHex;
1926
+ const lpIndex = steps.length - 1;
1927
+ return buildEvmMultisignBatch({
1928
+ context: {
1929
+ chainCategory: "evm",
1930
+ keyGen: args.keyGen,
1931
+ purposeText: args.purposeText,
1932
+ chainId: args.chainId,
1933
+ rpcUrl: args.rpcUrl,
1934
+ executorAddress: args.executorAddress,
1935
+ chainDetail: args.chainDetail,
1936
+ useCustomGas: args.useCustomGas,
1937
+ customGasChainDetails: args.customGasChainDetails
1938
+ },
1939
+ steps,
1940
+ purposeSuffix: `Uniswap V4: ${steps.length}-tx batch \u2014 ${actionLabel} (classic ERC-20 approve + Position Manager).`,
1941
+ firstMsgRawNo0x: dataNo0x,
1942
+ destinationAddress: to,
1943
+ buildBatchMeta: ({ index }) => {
1944
+ const isLpStep = index === lpIndex;
1945
+ return {
1946
+ signatureText: JSON.stringify({
1947
+ kind: "UniswapV4Liquidity",
1948
+ action: args.action,
1949
+ step: index,
1950
+ lpTx: isLpStep
1951
+ }),
1952
+ ...isLpStep ? {
1953
+ evm: { type: "uniswap_v4_liquidity_tx", version: 1, chainId: String(args.chainId) },
1954
+ uniswapV4Liquidity: {
1955
+ action: args.action,
1956
+ skipPermit2Batch: true,
1957
+ nftTokenId: args.nftTokenId != null ? String(args.nftTokenId) : void 0,
1958
+ poolReference: args.poolReference,
1959
+ lpResponseSnapshot: args.lpResponse,
1960
+ token0: parsed.token0,
1961
+ token1: parsed.token1,
1962
+ tickLower: parsed.tickLower,
1963
+ tickUpper: parsed.tickUpper,
1964
+ transaction: {
1965
+ to: tx.to,
1966
+ value: tx.value,
1967
+ dataNibbles: dataNo0x.length,
1968
+ gasLimit: tx.gasLimit
1969
+ },
1970
+ originalPurpose: args.purposeText
1971
+ }
1972
+ } : {}
1973
+ };
1974
+ }
1975
+ });
1976
+ }
1977
+ async function buildEvmMultisignBodyUniswapV4MintLiquidityBatch(args) {
1978
+ return buildEvmMultisignBodyUniswapV4LiquidityBatchInternal({ ...args, action: "mint" });
1979
+ }
1980
+ async function buildEvmMultisignBodyUniswapV4IncreaseLiquidityBatch(args) {
1981
+ return buildEvmMultisignBodyUniswapV4LiquidityBatchInternal({ ...args, action: "increase" });
1982
+ }
1983
+ async function buildEvmMultisignBodyUniswapV4DecreaseLiquidityBatch(args) {
1984
+ return buildEvmMultisignBodyUniswapV4LiquidityBatchInternal({ ...args, action: "decrease" });
1985
+ }
1986
+ async function buildEvmMultisignBodyUniswapV4CollectFeesBatch(args) {
1987
+ return buildEvmMultisignBodyUniswapV4LiquidityBatchInternal({ ...args, action: "collect" });
1988
+ }
1989
+
1293
1990
  // src/protocols/evm/uniswap-v4/swap.ts
1294
1991
  async function swapFromQuote(args) {
1295
1992
  const deadline = args.swapTransactionDeadlineUnix ?? swapTransactionDeadlineUnixFromExpiryMinutes(30);
@@ -1372,6 +2069,52 @@ var uniswapV4ProtocolModule = {
1372
2069
  amount: { type: "string", required: true, description: "Amount for quote" },
1373
2070
  type: { type: "EXACT_INPUT | EXACT_OUTPUT", required: true, description: "Trade type" }
1374
2071
  }
2072
+ },
2073
+ {
2074
+ id: "uniswap-v4.mint-liquidity",
2075
+ protocolId: UNISWAP_V4_PROTOCOL_ID,
2076
+ chainCategory: "evm",
2077
+ description: "Mint a new Uniswap V4 concentrated liquidity position (Position Manager NFT)",
2078
+ commonParams: ["keyGen", "purposeText", "useCustomGas"],
2079
+ params: {
2080
+ lpResponse: { type: "object", required: true, description: "Full LP API create response" },
2081
+ nativeWrapped: { type: "address", required: false, description: "WETH when pool uses native ETH" },
2082
+ poolReference: { type: "string", required: false, description: "V4 pool id" },
2083
+ uniswapApiKey: { type: "string", required: true, description: "Uniswap API key" }
2084
+ }
2085
+ },
2086
+ {
2087
+ id: "uniswap-v4.increase-liquidity",
2088
+ protocolId: UNISWAP_V4_PROTOCOL_ID,
2089
+ chainCategory: "evm",
2090
+ description: "Increase liquidity on an existing Uniswap V4 position NFT",
2091
+ commonParams: ["keyGen", "purposeText", "useCustomGas"],
2092
+ params: {
2093
+ nftTokenId: { type: "string", required: true, description: "Position NFT token id" },
2094
+ lpResponse: { type: "object", required: true, description: "Full LP API increase response" }
2095
+ }
2096
+ },
2097
+ {
2098
+ id: "uniswap-v4.decrease-liquidity",
2099
+ protocolId: UNISWAP_V4_PROTOCOL_ID,
2100
+ chainCategory: "evm",
2101
+ description: "Decrease liquidity on an existing Uniswap V4 position NFT",
2102
+ commonParams: ["keyGen", "purposeText", "useCustomGas"],
2103
+ params: {
2104
+ nftTokenId: { type: "string", required: true, description: "Position NFT token id" },
2105
+ lpResponse: { type: "object", required: true, description: "Full LP API decrease response" }
2106
+ }
2107
+ },
2108
+ {
2109
+ id: "uniswap-v4.collect-fees",
2110
+ protocolId: UNISWAP_V4_PROTOCOL_ID,
2111
+ chainCategory: "evm",
2112
+ description: "Collect accrued fees from a Uniswap V4 position NFT",
2113
+ commonParams: ["keyGen", "purposeText", "useCustomGas"],
2114
+ params: {
2115
+ nftTokenId: { type: "string", required: true, description: "Position NFT token id" },
2116
+ lpResponse: { type: "object", required: true, description: "Full LP API claim response" }
2117
+ }
1375
2118
  }
1376
2119
  ]
1377
2120
  };
@@ -1383,6 +2126,15 @@ var uniswapV4 = {
1383
2126
  swapFromQuote,
1384
2127
  buildSwapMultisignBody: buildEvmMultisignBodyUniswapV4SkipPermit2Batch,
1385
2128
  quote: uniswapTradeQuote,
2129
+ createLiquidityPosition: uniswapLpCreatePosition,
2130
+ increaseLiquidityPosition: uniswapLpIncreasePosition,
2131
+ decreaseLiquidityPosition: uniswapLpDecreasePosition,
2132
+ claimLiquidityFees: uniswapLpClaimFees,
2133
+ buildMintLiquidityMultisignBody: buildEvmMultisignBodyUniswapV4MintLiquidityBatch,
2134
+ buildIncreaseLiquidityMultisignBody: buildEvmMultisignBodyUniswapV4IncreaseLiquidityBatch,
2135
+ buildDecreaseLiquidityMultisignBody: buildEvmMultisignBodyUniswapV4DecreaseLiquidityBatch,
2136
+ buildCollectFeesMultisignBody: buildEvmMultisignBodyUniswapV4CollectFeesBatch,
2137
+ listPositions: listUniswapV4PositionsForWallet,
1386
2138
  isChainSupported: isUniswapV4ChainSupported
1387
2139
  };
1388
2140
 
@@ -1477,44 +2229,64 @@ function swappableCurveGraphNodeKeys(adj) {
1477
2229
  }
1478
2230
 
1479
2231
  // src/protocols/evm/curve-dao/apiSession.ts
2232
+ var CURVE_SESSION_CACHE_TTL_MS = 5 * 60 * 1e3;
2233
+ var curveSessionCache = /* @__PURE__ */ new Map();
1480
2234
  async function fetchAllCurvePools(curve) {
1481
2235
  const run = (p) => p.catch(() => void 0);
1482
- await Promise.all([
1483
- run(curve.factory.fetchPools()),
1484
- run(curve.crvUSDFactory.fetchPools()),
1485
- run(curve.EYWAFactory.fetchPools()),
1486
- run(curve.cryptoFactory.fetchPools()),
1487
- run(curve.twocryptoFactory.fetchPools()),
1488
- run(curve.tricryptoFactory.fetchPools()),
1489
- run(curve.stableNgFactory.fetchPools())
1490
- ]);
2236
+ const tasks = [];
2237
+ for (const key of [
2238
+ "factory",
2239
+ "crvUSDFactory",
2240
+ "EYWAFactory",
2241
+ "cryptoFactory",
2242
+ "twocryptoFactory",
2243
+ "tricryptoFactory",
2244
+ "stableNgFactory"
2245
+ ]) {
2246
+ const f = curve[key];
2247
+ if (f?.fetchPools) {
2248
+ tasks.push(run(f.fetchPools()));
2249
+ }
2250
+ }
2251
+ await Promise.all(tasks);
1491
2252
  }
1492
2253
  async function loadFullCurveSessionForRpc(rpcUrl) {
1493
2254
  const url = (rpcUrl ?? "").trim();
1494
- if (!url) return null;
2255
+ if (!url) {
2256
+ throw new Error("rpcUrl is required.");
2257
+ }
2258
+ const cached = curveSessionCache.get(url);
2259
+ if (cached && cached.expiresAt > Date.now()) {
2260
+ return cached.session;
2261
+ }
1495
2262
  try {
1496
2263
  const { default: curve } = await import('@curvefi/api');
1497
2264
  await curve.init("JsonRpc", { url }, {});
1498
2265
  const wrapped = curve.getNetworkConstants().NATIVE_COIN?.wrappedAddress;
1499
2266
  if (!curve.hasRouter || !curve.hasRouter()) {
1500
- return {
2267
+ const session2 = {
1501
2268
  curve,
1502
2269
  adj: /* @__PURE__ */ new Map(),
1503
2270
  swappableNodeKeys: /* @__PURE__ */ new Set(),
1504
2271
  wrappedNative: wrapped
1505
2272
  };
2273
+ curveSessionCache.set(url, { session: session2, expiresAt: Date.now() + CURVE_SESSION_CACHE_TTL_MS });
2274
+ return session2;
1506
2275
  }
1507
2276
  await fetchAllCurvePools(curve);
1508
2277
  const adj = buildCurveLiquidityGraphFromApi(curve);
1509
2278
  addNativeWethBridge(adj, wrapped);
1510
- return {
2279
+ const session = {
1511
2280
  curve,
1512
2281
  adj,
1513
2282
  swappableNodeKeys: swappableCurveGraphNodeKeys(adj),
1514
2283
  wrappedNative: wrapped
1515
2284
  };
1516
- } catch {
1517
- return null;
2285
+ curveSessionCache.set(url, { session, expiresAt: Date.now() + CURVE_SESSION_CACHE_TTL_MS });
2286
+ return session;
2287
+ } catch (e) {
2288
+ const msg = e instanceof Error ? e.message : String(e);
2289
+ throw new Error(`Curve session init failed for RPC: ${msg}`);
1518
2290
  }
1519
2291
  }
1520
2292
 
@@ -1567,7 +2339,7 @@ async function buildEvmMultisignBodyCurveDaoBatch(args) {
1567
2339
  rpcUrls: { default: { http: [args.rpcUrl] } }
1568
2340
  });
1569
2341
  const publicClient = viem.createPublicClient({ chain: ch, transport: viem.http(args.rpcUrl) });
1570
- const erc20AllowanceAbi = viem.parseAbi([
2342
+ const erc20AllowanceAbi2 = viem.parseAbi([
1571
2343
  "function allowance(address owner, address spender) view returns (uint256)",
1572
2344
  "function decimals() view returns (uint8)"
1573
2345
  ]);
@@ -1576,13 +2348,13 @@ async function buildEvmMultisignBodyCurveDaoBatch(args) {
1576
2348
  if (!isNativeIn) {
1577
2349
  const decimalsN = await publicClient.readContract({
1578
2350
  address: tokenIn,
1579
- abi: erc20AllowanceAbi,
2351
+ abi: erc20AllowanceAbi2,
1580
2352
  functionName: "decimals"
1581
2353
  });
1582
2354
  const amountWei = viem.parseUnits(args.amountHuman, Number(decimalsN));
1583
2355
  const currentAllowance = await publicClient.readContract({
1584
2356
  address: tokenIn,
1585
- abi: erc20AllowanceAbi,
2357
+ abi: erc20AllowanceAbi2,
1586
2358
  functionName: "allowance",
1587
2359
  args: [executor, routerAddr]
1588
2360
  });