@peridot-agent/agent-kit 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -414,6 +414,121 @@ async function listMarkets(input, config2) {
414
414
 
415
415
  // src/features/lending/read/get-portfolio.ts
416
416
  import { z as z3 } from "zod";
417
+ init_constants();
418
+
419
+ // src/shared/on-chain-position.ts
420
+ import Decimal from "decimal.js";
421
+ import { createPublicClient, http } from "viem";
422
+
423
+ // src/shared/abis.ts
424
+ import { parseAbi } from "viem";
425
+ var PTOKEN_ABI = parseAbi([
426
+ "function mint(uint256 mintAmount) returns (uint256)",
427
+ "function redeem(uint256 redeemTokens) returns (uint256)",
428
+ "function redeemUnderlying(uint256 redeemAmount) returns (uint256)",
429
+ "function borrow(uint256 borrowAmount) returns (uint256)",
430
+ "function repayBorrow(uint256 repayAmount) returns (uint256)",
431
+ "function repayBorrowBehalf(address borrower, uint256 repayAmount) returns (uint256)",
432
+ "function liquidateBorrow(address borrower, uint256 repayAmount, address pTokenCollateral) returns (uint256)",
433
+ "function balanceOf(address owner) view returns (uint256)",
434
+ "function borrowBalanceStored(address account) view returns (uint256)",
435
+ "function supplyRatePerBlock() view returns (uint256)",
436
+ "function borrowRatePerBlock() view returns (uint256)",
437
+ "function exchangeRateStored() view returns (uint256)",
438
+ "function underlying() view returns (address)"
439
+ ]);
440
+ var COMPTROLLER_ABI = parseAbi([
441
+ "function enterMarkets(address[] calldata pTokens) returns (uint256[] memory)",
442
+ "function exitMarket(address pTokenAddress) returns (uint256)",
443
+ "function getAccountLiquidity(address account) view returns (uint256 errorCode, uint256 liquidity, uint256 shortfall)",
444
+ "function getAllMarkets() view returns (address[] memory)",
445
+ "function markets(address pToken) view returns (bool isListed, uint256 collateralFactorMantissa, bool isComped)",
446
+ "function checkMembership(address account, address pToken) view returns (bool)"
447
+ ]);
448
+ var ERC20_ABI = parseAbi([
449
+ "function approve(address spender, uint256 amount) returns (bool)",
450
+ "function allowance(address owner, address spender) view returns (uint256)",
451
+ "function balanceOf(address owner) view returns (uint256)",
452
+ "function transfer(address to, uint256 amount) returns (bool)"
453
+ ]);
454
+
455
+ // src/shared/on-chain-position.ts
456
+ init_constants();
457
+ async function readOnChainPosition(address, chainId, config2) {
458
+ const markets = PERIDOT_MARKETS[chainId];
459
+ if (!markets) {
460
+ throw new Error(`No markets configured for chain ${chainId}`);
461
+ }
462
+ const marketEntries = Object.entries(markets).filter(
463
+ (entry) => entry[1] !== void 0
464
+ );
465
+ if (marketEntries.length === 0) {
466
+ return { totalSuppliedUsd: 0, totalBorrowedUsd: 0, assets: [] };
467
+ }
468
+ const rpcUrl = config2.rpcUrls?.[chainId] ?? DEFAULT_RPC_URLS[chainId];
469
+ if (!rpcUrl) {
470
+ throw new Error(
471
+ `No RPC URL available for chain ${chainId}. Provide one via config.rpcUrls[${chainId}].`
472
+ );
473
+ }
474
+ const viemClient = createPublicClient({ transport: http(rpcUrl) });
475
+ const apiClient = new PeridotApiClient(config2);
476
+ const [metricsData, multicallResults] = await Promise.all([
477
+ apiClient.getMarketMetrics(),
478
+ viemClient.multicall({
479
+ contracts: marketEntries.flatMap(([, pTokenAddress]) => [
480
+ {
481
+ address: pTokenAddress,
482
+ abi: PTOKEN_ABI,
483
+ functionName: "balanceOf",
484
+ args: [address]
485
+ },
486
+ {
487
+ address: pTokenAddress,
488
+ abi: PTOKEN_ABI,
489
+ functionName: "exchangeRateStored"
490
+ },
491
+ {
492
+ address: pTokenAddress,
493
+ abi: PTOKEN_ABI,
494
+ functionName: "borrowBalanceStored",
495
+ args: [address]
496
+ }
497
+ ]),
498
+ allowFailure: true
499
+ })
500
+ ]);
501
+ const assets = [];
502
+ let totalSuppliedUsd = 0;
503
+ let totalBorrowedUsd = 0;
504
+ for (let i = 0; i < marketEntries.length; i++) {
505
+ const entry = marketEntries[i];
506
+ if (!entry) continue;
507
+ const [symbol] = entry;
508
+ const base = i * 3;
509
+ const balanceResult = multicallResults[base];
510
+ const exchangeRateResult = multicallResults[base + 1];
511
+ const borrowResult = multicallResults[base + 2];
512
+ if (!balanceResult || !exchangeRateResult || !borrowResult || balanceResult.status === "failure" || exchangeRateResult.status === "failure" || borrowResult.status === "failure") {
513
+ continue;
514
+ }
515
+ const cTokenBalance = balanceResult.result;
516
+ const exchangeRate = exchangeRateResult.result;
517
+ const borrowBalance = borrowResult.result;
518
+ const underlyingDecimals = ASSET_DECIMALS[symbol] ?? 18;
519
+ const priceUsd = metricsData[`${symbol}:${chainId}`]?.priceUsd ?? 0;
520
+ const suppliedTokens = new Decimal(cTokenBalance.toString()).mul(exchangeRate.toString()).div("1e18").div(new Decimal(10).pow(underlyingDecimals)).toNumber();
521
+ const borrowedTokens = new Decimal(borrowBalance.toString()).div(new Decimal(10).pow(underlyingDecimals)).toNumber();
522
+ const suppliedUsd = suppliedTokens * priceUsd;
523
+ const borrowedUsd = borrowedTokens * priceUsd;
524
+ if (suppliedUsd > 1e-3 || borrowedUsd > 1e-3) {
525
+ assets.push({ assetId: symbol, suppliedUsd, borrowedUsd, suppliedTokens, borrowedTokens, priceUsd });
526
+ totalSuppliedUsd += suppliedUsd;
527
+ totalBorrowedUsd += borrowedUsd;
528
+ }
529
+ }
530
+ return { totalSuppliedUsd, totalBorrowedUsd, assets };
531
+ }
417
532
 
418
533
  // src/shared/zod-utils.ts
419
534
  import { z as z2 } from "zod";
@@ -469,26 +584,47 @@ var Cache = class {
469
584
  // src/features/lending/read/get-portfolio.ts
470
585
  var portfolioCache = new Cache(3e4);
471
586
  var getPortfolioSchema = z3.object({
472
- address: evmAddress.describe("The wallet address (0x...) to look up")
587
+ address: evmAddress.describe("The wallet address (0x...) to look up"),
588
+ chainId: z3.number().int().default(BSC_MAINNET_CHAIN_ID).refine(isHubChain, { message: "chainId must be a hub chain (56=BSC, 143=Monad, 1868=Somnia)." }).describe("Hub chain ID to query. Defaults to BSC (56).")
473
589
  });
474
590
  async function getPortfolio(input, config2) {
475
- const key = input.address.toLowerCase();
591
+ const key = `${input.address.toLowerCase()}:${input.chainId}`;
476
592
  return portfolioCache.getOrFetch(key, async () => {
477
- const client = new PeridotApiClient(config2);
478
- const data = await client.getUserPortfolio(input.address);
593
+ const apiClient = new PeridotApiClient(config2);
594
+ const [position, apyData] = await Promise.all([
595
+ readOnChainPosition(input.address, input.chainId, config2),
596
+ apiClient.getMarketApy(input.chainId)
597
+ ]);
598
+ const { totalSuppliedUsd, totalBorrowedUsd, assets } = position;
599
+ let netApy = 0;
600
+ if (totalSuppliedUsd > 0) {
601
+ let weighted = 0;
602
+ for (const asset of assets) {
603
+ const apyEntry = apyData[asset.assetId.toLowerCase()]?.[input.chainId];
604
+ if (apyEntry) {
605
+ weighted += asset.suppliedUsd * (apyEntry.totalSupplyApy ?? 0);
606
+ weighted -= asset.borrowedUsd * (apyEntry.netBorrowApy ?? 0);
607
+ }
608
+ }
609
+ netApy = weighted / totalSuppliedUsd;
610
+ }
479
611
  return {
480
612
  address: input.address,
481
613
  fetchedAt: (/* @__PURE__ */ new Date()).toISOString(),
482
614
  portfolio: {
483
- currentValue: data.portfolio.currentValue,
484
- totalSupplied: data.portfolio.totalSupplied,
485
- totalBorrowed: data.portfolio.totalBorrowed,
486
- netApy: data.portfolio.netApy,
487
- healthFactor: data.portfolio.totalBorrowed > 0 ? data.portfolio.totalSupplied / data.portfolio.totalBorrowed : null
615
+ currentValue: totalSuppliedUsd - totalBorrowedUsd,
616
+ totalSupplied: totalSuppliedUsd,
617
+ totalBorrowed: totalBorrowedUsd,
618
+ netApy,
619
+ healthFactor: totalBorrowedUsd > 0 ? totalSuppliedUsd / totalBorrowedUsd : null
488
620
  },
489
- assets: data.assets,
490
- transactions: data.transactions,
491
- earnings: data.earnings
621
+ assets: assets.map((a) => ({
622
+ assetId: a.assetId,
623
+ supplied: a.suppliedUsd,
624
+ borrowed: a.borrowedUsd,
625
+ net: a.suppliedUsd - a.borrowedUsd,
626
+ percentage: totalSuppliedUsd > 0 ? (a.suppliedUsd - a.borrowedUsd) / totalSuppliedUsd * 100 : 0
627
+ }))
492
628
  };
493
629
  });
494
630
  }
@@ -570,39 +706,50 @@ async function getMarketRates(input, config2) {
570
706
 
571
707
  // src/features/lending/read/get-user-position.ts
572
708
  import { z as z6 } from "zod";
709
+ init_constants();
573
710
  var getUserPositionSchema = z6.object({
574
- address: evmAddress.describe("The wallet address (0x...) to look up")
711
+ address: evmAddress.describe("The wallet address (0x...) to look up"),
712
+ chainId: z6.number().int().default(BSC_MAINNET_CHAIN_ID).refine(isHubChain, { message: "chainId must be a hub chain (56=BSC, 143=Monad, 1868=Somnia)." }).describe("Hub chain ID to query. Defaults to BSC (56).")
575
713
  });
576
714
  async function getUserPosition(input, config2) {
577
- const client = new PeridotApiClient(config2);
578
- const data = await client.getUserPortfolio(input.address);
579
- const { portfolio, assets, transactions } = data;
580
- const healthFactor = portfolio.totalBorrowed > 0 ? portfolio.totalSupplied / portfolio.totalBorrowed : null;
715
+ const apiClient = new PeridotApiClient(config2);
716
+ const [position, apyData] = await Promise.all([
717
+ readOnChainPosition(input.address, input.chainId, config2),
718
+ apiClient.getMarketApy(input.chainId)
719
+ ]);
720
+ const { totalSuppliedUsd, totalBorrowedUsd, assets } = position;
721
+ const healthFactor = totalBorrowedUsd > 0 ? totalSuppliedUsd / totalBorrowedUsd : null;
722
+ let netApyPct = 0;
723
+ if (totalSuppliedUsd > 0) {
724
+ let weightedApy = 0;
725
+ for (const asset of assets) {
726
+ const apyEntry = apyData[asset.assetId.toLowerCase()]?.[input.chainId];
727
+ if (apyEntry) {
728
+ weightedApy += asset.suppliedUsd * (apyEntry.totalSupplyApy ?? 0);
729
+ weightedApy -= asset.borrowedUsd * (apyEntry.netBorrowApy ?? 0);
730
+ }
731
+ }
732
+ netApyPct = weightedApy / totalSuppliedUsd;
733
+ }
581
734
  return {
582
735
  address: input.address,
583
- totalSuppliedUsd: portfolio.totalSupplied,
584
- totalBorrowedUsd: portfolio.totalBorrowed,
585
- netWorthUsd: portfolio.currentValue,
586
- netApyPct: portfolio.netApy,
736
+ totalSuppliedUsd,
737
+ totalBorrowedUsd,
738
+ netWorthUsd: totalSuppliedUsd - totalBorrowedUsd,
739
+ netApyPct,
587
740
  healthFactor,
588
741
  assets: assets.map((a) => ({
589
742
  assetId: a.assetId,
590
- suppliedUsd: a.supplied,
591
- borrowedUsd: a.borrowed,
592
- netUsd: a.net
743
+ suppliedUsd: a.suppliedUsd,
744
+ borrowedUsd: a.borrowedUsd,
745
+ netUsd: a.suppliedUsd - a.borrowedUsd
593
746
  })),
594
- transactions: {
595
- supplyCount: transactions.supplyCount,
596
- borrowCount: transactions.borrowCount,
597
- repayCount: transactions.repayCount,
598
- redeemCount: transactions.redeemCount
599
- },
600
747
  fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
601
748
  };
602
749
  }
603
750
 
604
751
  // src/features/lending/read/simulate-borrow.ts
605
- import Decimal from "decimal.js";
752
+ import Decimal2 from "decimal.js";
606
753
  import { z as z7 } from "zod";
607
754
  init_constants();
608
755
  var simulateBorrowSchema = z7.object({
@@ -625,10 +772,10 @@ function classifyRisk(hf) {
625
772
  return "liquidatable";
626
773
  }
627
774
  async function simulateBorrow(input, config2) {
628
- const client = new PeridotApiClient(config2);
629
- const [portfolioData, metricsData] = await Promise.all([
630
- client.getUserPortfolio(input.address),
631
- client.getMarketMetrics()
775
+ const apiClient = new PeridotApiClient(config2);
776
+ const [position, metricsData] = await Promise.all([
777
+ readOnChainPosition(input.address, input.chainId, config2),
778
+ apiClient.getMarketMetrics()
632
779
  ]);
633
780
  const assetUpper = input.asset.toUpperCase();
634
781
  const metricKey = `${assetUpper}:${input.chainId}`;
@@ -640,12 +787,11 @@ async function simulateBorrow(input, config2) {
640
787
  if (isNaN(borrowAmountRaw) || borrowAmountRaw <= 0) {
641
788
  throw new Error(`Invalid borrow amount: "${input.amount}"`);
642
789
  }
643
- const borrowAmount = new Decimal(input.amount);
790
+ const borrowAmount = new Decimal2(input.amount);
644
791
  const borrowAmountUsd = borrowAmount.mul(metric.priceUsd).toNumber();
645
- const { totalSupplied, totalBorrowed } = portfolioData.portfolio;
646
- const currentHF = totalBorrowed > 0 ? new Decimal(totalSupplied).div(totalBorrowed).toNumber() : null;
647
- const projectedBorrowedUsd = new Decimal(totalBorrowed).add(borrowAmountUsd);
648
- if (totalSupplied === 0) {
792
+ const { totalSuppliedUsd, totalBorrowedUsd } = position;
793
+ const currentHF = totalBorrowedUsd > 0 ? new Decimal2(totalSuppliedUsd).div(totalBorrowedUsd).toNumber() : null;
794
+ if (totalSuppliedUsd === 0) {
649
795
  return {
650
796
  currentHealthFactor: null,
651
797
  projectedHealthFactor: null,
@@ -653,13 +799,14 @@ async function simulateBorrow(input, config2) {
653
799
  isSafe: false,
654
800
  riskLevel: "liquidatable",
655
801
  maxSafeBorrowUsd: 0,
656
- warning: "Portfolio shows no supplied collateral (data is sourced from indexed DB snapshots and may not reflect activity from the last few minutes). If you recently supplied assets, wait for the next snapshot update. Otherwise, supply assets and enable them as collateral before borrowing."
802
+ warning: "No supplied collateral found on-chain for this address. Supply assets and enable them as collateral before borrowing."
657
803
  };
658
804
  }
659
- const projectedHF = new Decimal(totalSupplied).div(projectedBorrowedUsd).toNumber();
660
- const maxSafeBorrowUsd = Decimal.max(
805
+ const projectedBorrowedUsd = new Decimal2(totalBorrowedUsd).add(borrowAmountUsd);
806
+ const projectedHF = new Decimal2(totalSuppliedUsd).div(projectedBorrowedUsd).toNumber();
807
+ const maxSafeBorrowUsd = Decimal2.max(
661
808
  0,
662
- new Decimal(totalSupplied).div(RISK_THRESHOLDS.safe).sub(totalBorrowed)
809
+ new Decimal2(totalSuppliedUsd).div(RISK_THRESHOLDS.safe).sub(totalBorrowedUsd)
663
810
  ).toNumber();
664
811
  const riskLevel = classifyRisk(projectedHF);
665
812
  const isSafe = projectedHF >= RISK_THRESHOLDS.high;
@@ -683,43 +830,9 @@ async function simulateBorrow(input, config2) {
683
830
  }
684
831
 
685
832
  // src/features/lending/read/get-account-liquidity.ts
686
- import Decimal2 from "decimal.js";
833
+ import Decimal3 from "decimal.js";
687
834
  import { z as z8 } from "zod";
688
- import { createPublicClient, http } from "viem";
689
-
690
- // src/shared/abis.ts
691
- import { parseAbi } from "viem";
692
- var PTOKEN_ABI = parseAbi([
693
- "function mint(uint256 mintAmount) returns (uint256)",
694
- "function redeem(uint256 redeemTokens) returns (uint256)",
695
- "function redeemUnderlying(uint256 redeemAmount) returns (uint256)",
696
- "function borrow(uint256 borrowAmount) returns (uint256)",
697
- "function repayBorrow(uint256 repayAmount) returns (uint256)",
698
- "function repayBorrowBehalf(address borrower, uint256 repayAmount) returns (uint256)",
699
- "function liquidateBorrow(address borrower, uint256 repayAmount, address pTokenCollateral) returns (uint256)",
700
- "function balanceOf(address owner) view returns (uint256)",
701
- "function borrowBalanceStored(address account) view returns (uint256)",
702
- "function supplyRatePerBlock() view returns (uint256)",
703
- "function borrowRatePerBlock() view returns (uint256)",
704
- "function exchangeRateStored() view returns (uint256)",
705
- "function underlying() view returns (address)"
706
- ]);
707
- var COMPTROLLER_ABI = parseAbi([
708
- "function enterMarkets(address[] calldata pTokens) returns (uint256[] memory)",
709
- "function exitMarket(address pTokenAddress) returns (uint256)",
710
- "function getAccountLiquidity(address account) view returns (uint256 errorCode, uint256 liquidity, uint256 shortfall)",
711
- "function getAllMarkets() view returns (address[] memory)",
712
- "function markets(address pToken) view returns (bool isListed, uint256 collateralFactorMantissa, bool isComped)",
713
- "function checkMembership(address account, address pToken) view returns (bool)"
714
- ]);
715
- var ERC20_ABI = parseAbi([
716
- "function approve(address spender, uint256 amount) returns (bool)",
717
- "function allowance(address owner, address spender) view returns (uint256)",
718
- "function balanceOf(address owner) view returns (uint256)",
719
- "function transfer(address to, uint256 amount) returns (bool)"
720
- ]);
721
-
722
- // src/features/lending/read/get-account-liquidity.ts
835
+ import { createPublicClient as createPublicClient2, http as http2 } from "viem";
723
836
  init_constants();
724
837
  var getAccountLiquiditySchema = z8.object({
725
838
  address: evmAddress.describe("The wallet address to check"),
@@ -733,7 +846,7 @@ async function getAccountLiquidity(input, config2) {
733
846
  );
734
847
  }
735
848
  const controllerAddress = getControllerAddress(input.chainId);
736
- const client = createPublicClient({ transport: http(rpcUrl) });
849
+ const client = createPublicClient2({ transport: http2(rpcUrl) });
737
850
  const [error, liquidity, shortfall] = await client.readContract({
738
851
  address: controllerAddress,
739
852
  abi: COMPTROLLER_ABI,
@@ -743,8 +856,8 @@ async function getAccountLiquidity(input, config2) {
743
856
  if (error !== 0n) {
744
857
  throw new Error(`Comptroller getAccountLiquidity returned error code ${error.toString()}`);
745
858
  }
746
- const liquidityUsd = new Decimal2(liquidity.toString()).div("1e18").toNumber();
747
- const shortfallUsd = new Decimal2(shortfall.toString()).div("1e18").toNumber();
859
+ const liquidityUsd = new Decimal3(liquidity.toString()).div("1e18").toNumber();
860
+ const shortfallUsd = new Decimal3(shortfall.toString()).div("1e18").toNumber();
748
861
  return {
749
862
  address: input.address,
750
863
  chainId: input.chainId,