@1delta/margin-fetcher 0.0.158 → 0.0.160

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.
Files changed (109) hide show
  1. package/dist/abis/compound-v2/SumerLens.d.ts +331 -0
  2. package/dist/abis/compound-v2/SumerLens.d.ts.map +1 -0
  3. package/dist/index.d.ts +7 -1
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +2112 -418
  6. package/dist/index.js.map +1 -1
  7. package/dist/lending/index.d.ts +2 -0
  8. package/dist/lending/index.d.ts.map +1 -1
  9. package/dist/lending/margin/base/borrow.d.ts +10 -0
  10. package/dist/lending/margin/base/borrow.d.ts.map +1 -0
  11. package/dist/lending/margin/base/deposit.d.ts +10 -0
  12. package/dist/lending/margin/base/deposit.d.ts.map +1 -0
  13. package/dist/lending/margin/base/index.d.ts +7 -0
  14. package/dist/lending/margin/base/index.d.ts.map +1 -0
  15. package/dist/lending/margin/base/repay.d.ts +10 -0
  16. package/dist/lending/margin/base/repay.d.ts.map +1 -0
  17. package/dist/lending/margin/base/utils.d.ts +17 -0
  18. package/dist/lending/margin/base/utils.d.ts.map +1 -0
  19. package/dist/lending/margin/base/withdraw.d.ts +10 -0
  20. package/dist/lending/margin/base/withdraw.d.ts.map +1 -0
  21. package/dist/lending/margin/base/yield/getIntrinsicYieldChange.d.ts +22 -0
  22. package/dist/lending/margin/base/yield/getIntrinsicYieldChange.d.ts.map +1 -0
  23. package/dist/lending/margin/base/yield/getOrganicYieldChange.d.ts +22 -0
  24. package/dist/lending/margin/base/yield/getOrganicYieldChange.d.ts.map +1 -0
  25. package/dist/lending/margin/base/yield/getRewardYieldChange.d.ts +28 -0
  26. package/dist/lending/margin/base/yield/getRewardYieldChange.d.ts.map +1 -0
  27. package/dist/lending/margin/base/yield/index.d.ts +4 -0
  28. package/dist/lending/margin/base/yield/index.d.ts.map +1 -0
  29. package/dist/lending/margin/loop/compute/computeCloseDeltas.d.ts +8 -0
  30. package/dist/lending/margin/loop/compute/computeCloseDeltas.d.ts.map +1 -0
  31. package/dist/lending/margin/loop/compute/computeCollateralSwapDeltas.d.ts +8 -0
  32. package/dist/lending/margin/loop/compute/computeCollateralSwapDeltas.d.ts.map +1 -0
  33. package/dist/lending/margin/loop/compute/computeDebtSwapDeltas.d.ts +8 -0
  34. package/dist/lending/margin/loop/compute/computeDebtSwapDeltas.d.ts.map +1 -0
  35. package/dist/lending/margin/loop/compute/computeOpenDeltas.d.ts +8 -0
  36. package/dist/lending/margin/loop/compute/computeOpenDeltas.d.ts.map +1 -0
  37. package/dist/lending/margin/loop/compute/computeZapDeltas.d.ts +8 -0
  38. package/dist/lending/margin/loop/compute/computeZapDeltas.d.ts.map +1 -0
  39. package/dist/lending/margin/loop/compute/index.d.ts +6 -0
  40. package/dist/lending/margin/loop/compute/index.d.ts.map +1 -0
  41. package/dist/lending/margin/loop/index.d.ts +5 -0
  42. package/dist/lending/margin/loop/index.d.ts.map +1 -0
  43. package/dist/lending/margin/loop/types.d.ts +28 -0
  44. package/dist/lending/margin/loop/types.d.ts.map +1 -0
  45. package/dist/lending/margin/loop/utils.d.ts +11 -0
  46. package/dist/lending/margin/loop/utils.d.ts.map +1 -0
  47. package/dist/lending/margin/loop/yield/getIntrinsicYieldChange.d.ts +6 -0
  48. package/dist/lending/margin/loop/yield/getIntrinsicYieldChange.d.ts.map +1 -0
  49. package/dist/lending/margin/loop/yield/getOraganicYieldChange.d.ts +6 -0
  50. package/dist/lending/margin/loop/yield/getOraganicYieldChange.d.ts.map +1 -0
  51. package/dist/lending/margin/loop/yield/getRewardYieldChange.d.ts +22 -0
  52. package/dist/lending/margin/loop/yield/getRewardYieldChange.d.ts.map +1 -0
  53. package/dist/lending/margin/loop/yield/index.d.ts +4 -0
  54. package/dist/lending/margin/loop/yield/index.d.ts.map +1 -0
  55. package/dist/lending/margin/sumer/borrow.d.ts +12 -0
  56. package/dist/lending/margin/sumer/borrow.d.ts.map +1 -0
  57. package/dist/lending/margin/sumer/deposit.d.ts +11 -0
  58. package/dist/lending/margin/sumer/deposit.d.ts.map +1 -0
  59. package/dist/lending/margin/sumer/index.d.ts +7 -0
  60. package/dist/lending/margin/sumer/index.d.ts.map +1 -0
  61. package/dist/lending/margin/sumer/repay.d.ts +12 -0
  62. package/dist/lending/margin/sumer/repay.d.ts.map +1 -0
  63. package/dist/lending/margin/sumer/types.d.ts +27 -0
  64. package/dist/lending/margin/sumer/types.d.ts.map +1 -0
  65. package/dist/lending/margin/sumer/waterfall.d.ts +31 -0
  66. package/dist/lending/margin/sumer/waterfall.d.ts.map +1 -0
  67. package/dist/lending/margin/sumer/withdraw.d.ts +10 -0
  68. package/dist/lending/margin/sumer/withdraw.d.ts.map +1 -0
  69. package/dist/lending/public-data/addresses/compoundV2.d.ts.map +1 -1
  70. package/dist/lending/public-data/compound-v2/getters/sumer.d.ts +103 -0
  71. package/dist/lending/public-data/compound-v2/getters/sumer.d.ts.map +1 -0
  72. package/dist/lending/public-data/compound-v2/publicCallBuild.d.ts.map +1 -1
  73. package/dist/lending/public-data/compound-v2/publicCallParse.d.ts.map +1 -1
  74. package/dist/lending/public-data/fetchLender.d.ts.map +1 -1
  75. package/dist/lending/public-data/morpho/getMarketsFromChain.d.ts.map +1 -1
  76. package/dist/lending/user-data/abis.d.ts +1163 -46
  77. package/dist/lending/user-data/abis.d.ts.map +1 -1
  78. package/dist/lending/user-data/compound-v2/userCallParse.d.ts.map +1 -1
  79. package/dist/lending/user-data/fetchUserData.d.ts +3 -3
  80. package/dist/lending/user-data/fetchUserData.d.ts.map +1 -1
  81. package/dist/lending/user-data/init/userCallBuild.d.ts +0 -4
  82. package/dist/lending/user-data/init/userCallBuild.d.ts.map +1 -1
  83. package/dist/lending/user-data/init/userCallParse.d.ts.map +1 -1
  84. package/dist/lending/user-data/utils/createSumerUserState.d.ts +6 -0
  85. package/dist/lending/user-data/utils/createSumerUserState.d.ts.map +1 -0
  86. package/dist/lending/user-data/utils/index.d.ts +1 -0
  87. package/dist/lending/user-data/utils/index.d.ts.map +1 -1
  88. package/dist/lending/user-data/utils/types.d.ts +10 -0
  89. package/dist/lending/user-data/utils/types.d.ts.map +1 -1
  90. package/dist/lending-pairs/computeLendingPairs.d.ts.map +1 -1
  91. package/dist/token/fetchTokenBalance.d.ts +5 -2
  92. package/dist/token/fetchTokenBalance.d.ts.map +1 -1
  93. package/dist/types/apiReturnType.d.ts +1 -1
  94. package/dist/types/apiReturnType.d.ts.map +1 -1
  95. package/dist/types/lender/aave-v2-types.d.ts +1 -1
  96. package/dist/types/lender/aave-v2-types.d.ts.map +1 -1
  97. package/dist/types/lender/compound-v2-types.d.ts +5 -2
  98. package/dist/types/lender/compound-v2-types.d.ts.map +1 -1
  99. package/dist/types/lender/morpho-types.d.ts +1 -1
  100. package/dist/types/lender/morpho-types.d.ts.map +1 -1
  101. package/dist/types/lenderTypes.d.ts +1 -1
  102. package/dist/types/lenderTypes.d.ts.map +1 -1
  103. package/dist/utils/index.d.ts +1 -0
  104. package/dist/utils/index.d.ts.map +1 -1
  105. package/package.json +6 -4
  106. package/dist/abis/morpho/blue.d.ts +0 -76
  107. package/dist/abis/morpho/blue.d.ts.map +0 -1
  108. package/dist/abis/morpho/lens.d.ts +0 -128
  109. package/dist/abis/morpho/lens.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -4,6 +4,9 @@ import './chunk-PR4QN5HX.js';
4
4
  import { Lender, AAVE_V3_LENDERS, AAVE_V2_LENDERS, AAVE_V32_LENDERS, COMPOUND_V2_LENDERS, VENUS_LENDERS } from '@1delta/lender-registry';
5
5
  import lodash from 'lodash';
6
6
  import { getEvmChain, multicallRetry, getEvmClient, getEvmClientUniversal } from '@1delta/providers';
7
+ import { MorphoLensAbi, MorphoBlueAbi } from '@1delta/abis';
8
+ export { MorphoLensAbi } from '@1delta/abis';
9
+ import { InitMarginAddresses } from '@1delta/calldata-sdk';
7
10
  import { BALANCER_V2_FORKS, BALANCER_V3_FORKS, UNISWAP_V4_FORKS, FLASH_LOAN_IDS } from '@1delta/dex-registry';
8
11
 
9
12
  // src/abis/aave-v2/ProtocolDataProvider.ts
@@ -6263,7 +6266,8 @@ globalThis[GLOBAL_LENDER_DATA_KEY] = {
6263
6266
  compoundV3Oracles: {},
6264
6267
  morphoOracles: {},
6265
6268
  morphoTypeOracles: {},
6266
- morphoTypeMarkets: {}
6269
+ morphoTypeMarkets: {},
6270
+ aaveWethGateway: {}
6267
6271
  };
6268
6272
  function getGlobalData2() {
6269
6273
  return globalThis[GLOBAL_LENDER_DATA_KEY];
@@ -6282,7 +6286,6 @@ var compoundV3Pools = () => getGlobalData2()?.compoundV3Pools;
6282
6286
  var morphoPools = () => getGlobalData2()?.morphoPools;
6283
6287
  var compoundV3BaseData = () => getGlobalData2()?.compoundV3BaseData;
6284
6288
  var compoundV2Pools = () => getGlobalData2()?.compoundV2Pools;
6285
- var compoundV2Tokens = () => getGlobalData2()?.compoundV2Tokens;
6286
6289
  var compoundV2TokenArray = () => getGlobalData2()?.compoundV2TokenArray;
6287
6290
  var initConfig = () => getGlobalData2()?.initConfig;
6288
6291
  var getListUrl = (chainId) => `https://raw.githubusercontent.com/1delta-DAO/token-lists/main/${chainId}.json`;
@@ -6349,12 +6352,16 @@ function isCompoundV2Type(lender) {
6349
6352
  function isVenusType(lender) {
6350
6353
  return VENUS_LENDERS.includes(lender);
6351
6354
  }
6355
+ function isSumerType(lender) {
6356
+ return lender === Lender.SUMER;
6357
+ }
6352
6358
  var ENABLED_COMPOUNDS = [
6353
6359
  Lender.VENUS,
6354
6360
  Lender.VENUS_ETH,
6355
6361
  Lender.MOONWELL,
6356
6362
  Lender.ENCLABS,
6357
- Lender.ENCLABS_LST
6363
+ Lender.ENCLABS_LST,
6364
+ Lender.SUMER
6358
6365
  ];
6359
6366
  var getLendersForChain = (c) => {
6360
6367
  let lenders = [];
@@ -8115,7 +8122,7 @@ var getAaveV2ReservesDataConverter = (lender, chainId, prices, additionalYields,
8115
8122
  stableBorrowRate: formatAaveRawApyToApr(
8116
8123
  reserveData?.[5 /* stableBorrowRate */]?.toString()
8117
8124
  ),
8118
- stakingYield: additionalYields?.intrinsicYields[oracleKey] ?? 0,
8125
+ intrinsicYield: additionalYields?.intrinsicYields[oracleKey] ?? 0,
8119
8126
  // rewards
8120
8127
  rewards: lender === Lender.MERIDIAN && chainId === Chain.TAIKO_ALETHIA && additionalYields?.lenderRewards ? {
8121
8128
  TAIKO: {
@@ -8275,7 +8282,7 @@ var getAaveV3ReservesDataConverter = (lender, chainId, prices, additionalYields,
8275
8282
  stableBorrowRate: formatAaveRawApyToApr(
8276
8283
  reserveData?.[7 /* stableBorrowRate */]?.toString()
8277
8284
  ),
8278
- stakingYield: additionalYields.intrinsicYields[toOracleKey(assetMeta?.assetGroup)] ?? 0,
8285
+ intrinsicYield: additionalYields.intrinsicYields[toOracleKey(assetMeta?.assetGroup)] ?? 0,
8279
8286
  // rewards
8280
8287
  rewards: {}
8281
8288
  };
@@ -8475,7 +8482,7 @@ function parseYLDRCall(chainId, lender, additionalYields, prices, tokenList) {
8475
8482
  reserveData?.[4 /* variableBorrowRate */]?.toString()
8476
8483
  ),
8477
8484
  stableBorrowRate: 0,
8478
- stakingYield: additionalYields.intrinsicYields[oracleKey] ?? 0,
8485
+ intrinsicYield: additionalYields.intrinsicYields[oracleKey] ?? 0,
8479
8486
  // rewards
8480
8487
  rewards: {},
8481
8488
  decimals: Number(
@@ -8612,7 +8619,7 @@ function parseAave32(chainId, lender, prices, additionalYields, tokenList) {
8612
8619
  stableBorrowRate: formatAaveRawApyToApr(
8613
8620
  reserveData?.[7 /* stableBorrowRate */]?.toString()
8614
8621
  ),
8615
- stakingYield: additionalYields.intrinsicYields[toOracleKey(assetMeta?.assetGroup)] ?? 0,
8622
+ intrinsicYield: additionalYields.intrinsicYields[toOracleKey(assetMeta?.assetGroup)] ?? 0,
8616
8623
  // rewards
8617
8624
  rewards: {}
8618
8625
  };
@@ -8742,7 +8749,7 @@ var getInitReservesDataConverter = (lender, chainId, prices, additionalYields, t
8742
8749
  ),
8743
8750
  stableBorrowRate: 0,
8744
8751
  collateralActive: true,
8745
- stakingYield: additionalYields.intrinsicYields[oracleKey] ?? 0,
8752
+ intrinsicYield: additionalYields.intrinsicYields[oracleKey] ?? 0,
8746
8753
  rewards: {},
8747
8754
  config: {},
8748
8755
  borrowingEnabled: totalDebt !== "0",
@@ -8854,7 +8861,7 @@ var getCompoundV3ReservesDataConverter = (lender, chainId, prices, additionalYie
8854
8861
  variableBorrowRate: 0,
8855
8862
  stableBorrowRate: 0,
8856
8863
  depositRate: 0,
8857
- stakingYield: additionalYields.intrinsicYields[oracleKey] ?? 0,
8864
+ intrinsicYield: additionalYields.intrinsicYields[oracleKey] ?? 0,
8858
8865
  utilization: 0,
8859
8866
  // debt and liquidity are zero
8860
8867
  totalDebt: 0,
@@ -8941,7 +8948,7 @@ var getCompoundV3ReservesDataConverter = (lender, chainId, prices, additionalYie
8941
8948
  collateralActive: false,
8942
8949
  isActive: true,
8943
8950
  isFrozen: false,
8944
- stakingYield: additionalYields.intrinsicYields[oracleKeyBase] ?? 0
8951
+ intrinsicYield: additionalYields.intrinsicYields[oracleKeyBase] ?? 0
8945
8952
  }
8946
8953
  };
8947
8954
  return { data: { ...result, ...baseData }, chainId };
@@ -10921,9 +10928,9 @@ function createBaseTypeUserState(payload, lenderData, totalDeposits24h = 0, tota
10921
10928
  rewardApr: safeDivide(rewardDepositAccrual + rewardBorrowAccrual, nav),
10922
10929
  rewardDepositApr: safeDivide(rewardDepositAccrual, deposits),
10923
10930
  rewardBorrowApr: safeDivide(rewardBorrowAccrual, debt),
10924
- stakingApr: safeDivide(stakingDepositAccrual - stakingBorrowAccrual, nav),
10925
- stakingDepositApr: safeDivide(stakingDepositAccrual, deposits),
10926
- stakingBorrowApr: safeDivide(stakingBorrowAccrual, debt)
10931
+ intrinsicApr: safeDivide(stakingDepositAccrual - stakingBorrowAccrual, nav),
10932
+ intrinsicDepositApr: safeDivide(stakingDepositAccrual, deposits),
10933
+ intrinsicBorrowApr: safeDivide(stakingBorrowAccrual, debt)
10927
10934
  };
10928
10935
  const userConfig = { selectedMode: mode, id: account, isWhitelisted };
10929
10936
  const creditLine = Math.max(
@@ -10978,6 +10985,250 @@ function createBaseTypeUserState(payload, lenderData, totalDeposits24h = 0, tota
10978
10985
  };
10979
10986
  }
10980
10987
 
10988
+ // src/lending/margin/sumer/waterfall.ts
10989
+ function computeSumerWaterfall(groups, accum) {
10990
+ let total = 0;
10991
+ for (const g of groups) {
10992
+ const a = accum[g.groupId];
10993
+ if (!a) continue;
10994
+ let cDep = a.cDep;
10995
+ let sDep = a.sDep;
10996
+ let sDebt = a.sDebt;
10997
+ let cDebt = a.cDebt;
10998
+ if (cDep > 0 && sDebt > 0 && g.intraMintRate > 0) {
10999
+ const absorbed = Math.min(cDep * g.intraMintRate, sDebt);
11000
+ total += absorbed;
11001
+ sDebt -= absorbed;
11002
+ cDep -= absorbed / g.intraMintRate;
11003
+ }
11004
+ if (cDep > 0 && cDebt > 0 && g.intraCRate > 0) {
11005
+ const absorbed = Math.min(cDep * g.intraCRate, cDebt);
11006
+ total += absorbed;
11007
+ cDebt -= absorbed;
11008
+ cDep -= absorbed / g.intraCRate;
11009
+ }
11010
+ if (sDep > 0 && sDebt > 0 && g.intraSuRate > 0) {
11011
+ const absorbed = Math.min(sDep * g.intraSuRate, sDebt);
11012
+ total += absorbed;
11013
+ sDebt -= absorbed;
11014
+ sDep -= absorbed / g.intraSuRate;
11015
+ }
11016
+ if (sDep > 0 && cDebt > 0 && g.intraSuRate > 0) {
11017
+ const absorbed = Math.min(sDep * g.intraSuRate, cDebt);
11018
+ total += absorbed;
11019
+ cDebt -= absorbed;
11020
+ sDep -= absorbed / g.intraSuRate;
11021
+ }
11022
+ total += cDep * g.interCRate + sDep * g.interSuRate;
11023
+ }
11024
+ return total;
11025
+ }
11026
+ function buildSumerAccumulators(positions) {
11027
+ const groupRatesMap = {};
11028
+ const gAccum = {};
11029
+ const gAccumAll = {};
11030
+ for (const pos of positions) {
11031
+ const sm = pos.sumerMeta;
11032
+ const gId = sm.groupId;
11033
+ if (!groupRatesMap[gId]) groupRatesMap[gId] = sm;
11034
+ if (!gAccum[gId]) gAccum[gId] = { cDep: 0, sDep: 0, cDebt: 0, sDebt: 0 };
11035
+ if (!gAccumAll[gId])
11036
+ gAccumAll[gId] = { cDep: 0, sDep: 0, cDebt: 0, sDebt: 0 };
11037
+ const totalDebt = pos.debtUSD + pos.debtStableUSD;
11038
+ if (sm.isCToken) {
11039
+ if (pos.collateralActive && pos.collateralEnabled)
11040
+ gAccum[gId].cDep += pos.depositsUSD;
11041
+ if (pos.collateralActive) gAccumAll[gId].cDep += pos.depositsUSD;
11042
+ gAccum[gId].cDebt += totalDebt;
11043
+ gAccumAll[gId].cDebt += totalDebt;
11044
+ } else {
11045
+ if (pos.collateralActive && pos.collateralEnabled)
11046
+ gAccum[gId].sDep += pos.depositsUSD;
11047
+ if (pos.collateralActive) gAccumAll[gId].sDep += pos.depositsUSD;
11048
+ gAccum[gId].sDebt += totalDebt;
11049
+ gAccumAll[gId].sDebt += totalDebt;
11050
+ }
11051
+ }
11052
+ return { groupRatesMap, gAccum, gAccumAll };
11053
+ }
11054
+ function applyPositionDelta(positions, targetMarketUid, depositsDeltaUSD, debtDeltaUSD, debtStableDeltaUSD) {
11055
+ return positions.map((p) => {
11056
+ if (p.marketUid !== targetMarketUid) return p;
11057
+ return {
11058
+ ...p,
11059
+ depositsUSD: p.depositsUSD + depositsDeltaUSD,
11060
+ debtUSD: p.debtUSD + debtDeltaUSD,
11061
+ debtStableUSD: p.debtStableUSD + debtStableDeltaUSD
11062
+ };
11063
+ });
11064
+ }
11065
+
11066
+ // src/lending/user-data/utils/createSumerUserState.ts
11067
+ function createSumerUserState(payload, lenderData, totalDeposits24h = 0, totalDebt24h = 0) {
11068
+ const assetKeys = getMarketUidsFromMeta(lenderData);
11069
+ const { chainId, account } = payload;
11070
+ const isWhitelisted = !Boolean(payload?.notWhitelisted ?? false);
11071
+ const groupRatesMap = {};
11072
+ const gAccum = {};
11073
+ const gAccumAll = {};
11074
+ let depositInterest = 0;
11075
+ let borrowInterest = 0;
11076
+ let rewardDepositAccrual = 0;
11077
+ let rewardBorrowAccrual = 0;
11078
+ let stakingDepositAccrual = 0;
11079
+ let stakingBorrowAccrual = 0;
11080
+ let deposits = 0;
11081
+ let debt = 0;
11082
+ let rewardsPerAsset = {};
11083
+ for (let i = 0; i < assetKeys.length; i++) {
11084
+ const marketUid = assetKeys[i];
11085
+ if (!lenderData?.[marketUid] || !payload.lendingPositions["0"][marketUid])
11086
+ continue;
11087
+ const { depositsUSD, debtStableUSD, debtUSD, collateralEnabled } = payload.lendingPositions["0"][marketUid];
11088
+ const {
11089
+ depositRate,
11090
+ intrinsicYield,
11091
+ variableBorrowRate,
11092
+ stableBorrowRate,
11093
+ rewards,
11094
+ flags,
11095
+ sumerMeta
11096
+ } = lenderData[marketUid];
11097
+ deposits += depositsUSD;
11098
+ debt += debtStableUSD;
11099
+ debt += debtUSD;
11100
+ Object.entries(rewards ?? {}).forEach(
11101
+ ([key, rewardData]) => {
11102
+ rewardDepositAccrual += rewardData.depositRate * depositsUSD;
11103
+ rewardBorrowAccrual += rewardData.variableBorrowRate * debtUSD + (rewardData.stableBorrowRate ?? 0) * debtStableUSD;
11104
+ const rewDepo = rewardData.depositRate * depositsUSD;
11105
+ const rewDebt = rewardData.variableBorrowRate * debtUSD + (rewardData.stableBorrowRate ?? 0) * (debtStableUSD ?? 0);
11106
+ if (!rewardsPerAsset[key])
11107
+ rewardsPerAsset[key] = { depositApr: 0, borrowApr: 0 };
11108
+ if (rewDepo > 0) rewardsPerAsset[key].depositApr += rewDepo;
11109
+ if (rewDebt > 0) rewardsPerAsset[key].borrowApr += rewDebt;
11110
+ }
11111
+ );
11112
+ stakingDepositAccrual += (intrinsicYield ?? 0) * depositsUSD;
11113
+ stakingBorrowAccrual += (intrinsicYield ?? 0) * (debtStableUSD + debtUSD);
11114
+ if (sumerMeta) {
11115
+ const gId = sumerMeta.groupId;
11116
+ if (!groupRatesMap[gId]) groupRatesMap[gId] = sumerMeta;
11117
+ if (!gAccum[gId])
11118
+ gAccum[gId] = { cDep: 0, sDep: 0, cDebt: 0, sDebt: 0 };
11119
+ if (!gAccumAll[gId])
11120
+ gAccumAll[gId] = { cDep: 0, sDep: 0, cDebt: 0, sDebt: 0 };
11121
+ const totalDebtForPos = debtUSD + debtStableUSD;
11122
+ if (sumerMeta.isCToken) {
11123
+ if (flags?.collateralActive && collateralEnabled)
11124
+ gAccum[gId].cDep += depositsUSD;
11125
+ if (flags?.collateralActive) gAccumAll[gId].cDep += depositsUSD;
11126
+ gAccum[gId].cDebt += totalDebtForPos;
11127
+ gAccumAll[gId].cDebt += totalDebtForPos;
11128
+ } else {
11129
+ if (flags?.collateralActive && collateralEnabled)
11130
+ gAccum[gId].sDep += depositsUSD;
11131
+ if (flags?.collateralActive) gAccumAll[gId].sDep += depositsUSD;
11132
+ gAccum[gId].sDebt += totalDebtForPos;
11133
+ gAccumAll[gId].sDebt += totalDebtForPos;
11134
+ }
11135
+ }
11136
+ depositInterest += depositRate * depositsUSD;
11137
+ borrowInterest += debtStableUSD * stableBorrowRate + debtUSD * variableBorrowRate;
11138
+ }
11139
+ const borrowDiscountedCollateral = computeSumerWaterfall(
11140
+ Object.values(groupRatesMap),
11141
+ gAccum
11142
+ );
11143
+ const borrowDiscountedCollateralAllActive = computeSumerWaterfall(
11144
+ Object.values(groupRatesMap),
11145
+ gAccumAll
11146
+ );
11147
+ const nav = deposits - debt;
11148
+ const balanceData2 = {
11149
+ borrowDiscountedCollateral,
11150
+ borrowDiscountedCollateralAllActive,
11151
+ collateral: borrowDiscountedCollateral,
11152
+ collateralAllActive: borrowDiscountedCollateralAllActive,
11153
+ deposits,
11154
+ debt,
11155
+ adjustedDebt: debt,
11156
+ nav,
11157
+ deposits24h: totalDeposits24h,
11158
+ debt24h: totalDebt24h,
11159
+ nav24h: totalDeposits24h - totalDebt24h,
11160
+ ...payload.rewards ? { rewards: payload.rewards } : {}
11161
+ };
11162
+ const aprData2 = {
11163
+ apr: safeDivide(depositInterest - borrowInterest, nav),
11164
+ borrowApr: safeDivide(borrowInterest, debt),
11165
+ depositApr: safeDivide(depositInterest, deposits),
11166
+ rewards: divideAccrualsToAprs(rewardsPerAsset, nav, deposits, debt),
11167
+ rewardApr: safeDivide(rewardDepositAccrual + rewardBorrowAccrual, nav),
11168
+ rewardDepositApr: safeDivide(rewardDepositAccrual, deposits),
11169
+ rewardBorrowApr: safeDivide(rewardBorrowAccrual, debt),
11170
+ intrinsicApr: safeDivide(stakingDepositAccrual - stakingBorrowAccrual, nav),
11171
+ intrinsicDepositApr: safeDivide(stakingDepositAccrual, deposits),
11172
+ intrinsicBorrowApr: safeDivide(stakingBorrowAccrual, debt)
11173
+ };
11174
+ const userConfig = { selectedMode: 0, id: account, isWhitelisted };
11175
+ const creditLine = Math.max(
11176
+ 0,
11177
+ borrowDiscountedCollateral - balanceData2.adjustedDebt
11178
+ );
11179
+ for (let i = 0; i < assetKeys.length; i++) {
11180
+ const marketUid = assetKeys[i];
11181
+ const pos = payload.lendingPositions["0"][marketUid];
11182
+ if (!pos || !lenderData?.[marketUid]) continue;
11183
+ const {
11184
+ configs,
11185
+ flags,
11186
+ price: priceInfo,
11187
+ sumerMeta: sm
11188
+ } = lenderData[marketUid];
11189
+ const config = configs?.[sm?.groupId ?? 0];
11190
+ const price = priceInfo?.priceUsd ?? 1;
11191
+ const bcf = config?.borrowCollateralFactor ?? 1;
11192
+ const bf = config?.borrowFactor ?? 1;
11193
+ let withdrawable;
11194
+ if (!pos.collateralEnabled || config?.collateralDisabled) {
11195
+ withdrawable = String(pos.deposits);
11196
+ } else if (balanceData2.debt === 0) {
11197
+ withdrawable = String(pos.deposits);
11198
+ } else {
11199
+ const withdrawableUSD = Math.max(creditLine / bcf, 0);
11200
+ withdrawable = String(
11201
+ Math.min(withdrawableUSD / price, Number(pos.deposits))
11202
+ );
11203
+ }
11204
+ let borrowable;
11205
+ if (!flags?.borrowingEnabled || flags?.isFrozen || config?.debtDisabled) {
11206
+ borrowable = "0";
11207
+ } else {
11208
+ const borrowableUSD = Math.max(creditLine / bf, 0);
11209
+ borrowable = String(borrowableUSD / price);
11210
+ }
11211
+ pos.withdrawable = withdrawable;
11212
+ pos.borrowable = borrowable;
11213
+ }
11214
+ return {
11215
+ lender: "",
11216
+ account,
11217
+ chainId,
11218
+ data: [
11219
+ {
11220
+ health: balanceData2.debt === 0 ? null : balanceData2.adjustedDebt > 0 ? balanceData2.borrowDiscountedCollateral / balanceData2.adjustedDebt : balanceData2.collateral / balanceData2.debt,
11221
+ borrowCapacityUSD: creditLine,
11222
+ accountId: "0",
11223
+ balanceData: balanceData2,
11224
+ aprData: aprData2,
11225
+ userConfig,
11226
+ positions: Object.values(payload.lendingPositions["0"])
11227
+ }
11228
+ ]
11229
+ };
11230
+ }
11231
+
10981
11232
  // src/lending/user-data/utils/createMultiAccountStyleUserState.ts
10982
11233
  function createMultiAccountTypeUserState(payload, lenderData, histData) {
10983
11234
  const positionKeys = Object.keys(payload.lendingPositions ?? {});
@@ -11052,9 +11303,9 @@ function createMultiAccountTypeUserState(payload, lenderData, histData) {
11052
11303
  rewardApr: safeDivide(rewardDepositAccrual + rewardBorrowAccrual, nav),
11053
11304
  rewardDepositApr: safeDivide(rewardDepositAccrual, deposits),
11054
11305
  rewardBorrowApr: safeDivide(rewardBorrowAccrual, debt),
11055
- stakingApr: safeDivide(stakingDepositAccrual - stakingBorrowAccrual, nav),
11056
- stakingDepositApr: safeDivide(stakingDepositAccrual, deposits),
11057
- stakingBorrowApr: safeDivide(stakingBorrowAccrual, debt),
11306
+ intrinsicApr: safeDivide(stakingDepositAccrual - stakingBorrowAccrual, nav),
11307
+ intrinsicDepositApr: safeDivide(stakingDepositAccrual, deposits),
11308
+ intrinsicBorrowApr: safeDivide(stakingBorrowAccrual, debt),
11058
11309
  rewards: {}
11059
11310
  };
11060
11311
  const creditLine = Math.max(0, borrowDiscountedCollateral - adjustedDebt);
@@ -11197,7 +11448,7 @@ function convertMarketsToMorphoResponse(response, chainId, additionalYields = {
11197
11448
  depositRate: apyToApr2(Number(state.supplyApy)) * 100,
11198
11449
  variableBorrowRate: apyToApr2(Number(state.borrowApy)) * 100,
11199
11450
  stableBorrowRate: 0,
11200
- stakingYield: additionalYields.intrinsicYields[meta?.assetGroup] ?? 0,
11451
+ intrinsicYield: additionalYields.intrinsicYields[meta?.assetGroup] ?? 0,
11201
11452
  rewards: Object.keys(loanRewards).length > 0 ? loanRewards : void 0,
11202
11453
  decimals: loanAsset.decimals,
11203
11454
  config: {
@@ -11241,7 +11492,7 @@ function convertMarketsToMorphoResponse(response, chainId, additionalYields = {
11241
11492
  depositRate: 0,
11242
11493
  variableBorrowRate: 0,
11243
11494
  stableBorrowRate: 0,
11244
- stakingYield: additionalYields.intrinsicYields[metaCollateral?.assetGroup] ?? 0,
11495
+ intrinsicYield: additionalYields.intrinsicYields[metaCollateral?.assetGroup] ?? 0,
11245
11496
  rewards: void 0,
11246
11497
  decimals: collateralAsset.decimals,
11247
11498
  config: {
@@ -11877,7 +12128,7 @@ function getListaMarketDataConverter(lender, chainId, prices, additionalYields =
11877
12128
  depositRate: depositApr,
11878
12129
  variableBorrowRate: borrowApr,
11879
12130
  stableBorrowRate: 0,
11880
- stakingYield: additionalYields.intrinsicYields[meta?.assetGroup] ?? 0,
12131
+ intrinsicYield: additionalYields.intrinsicYields[meta?.assetGroup] ?? 0,
11881
12132
  rewards: Object.keys(loanRewards).length > 0 ? loanRewards : void 0,
11882
12133
  decimals: loanDecimals,
11883
12134
  config: {
@@ -11915,7 +12166,7 @@ function getListaMarketDataConverter(lender, chainId, prices, additionalYields =
11915
12166
  depositRate: 0,
11916
12167
  variableBorrowRate: 0,
11917
12168
  stableBorrowRate: 0,
11918
- stakingYield: additionalYields.intrinsicYields[metaCollateral?.assetGroup] ?? 0,
12169
+ intrinsicYield: additionalYields.intrinsicYields[metaCollateral?.assetGroup] ?? 0,
11919
12170
  rewards: void 0,
11920
12171
  decimals: collateralDecimals,
11921
12172
  config: {
@@ -12013,7 +12264,7 @@ function getMorphoMarketDataConverter(lender, chainId, prices, additionalYields
12013
12264
  decoded.forEach((market, i) => {
12014
12265
  const uniqueKey = markets[i];
12015
12266
  const { lltv, irm, oracle, loanToken, collateralToken, ...state } = market;
12016
- if (collateralToken && loanToken && oracle) {
12267
+ if (collateralToken && loanToken && oracle && collateralToken !== zeroAddress && loanToken !== zeroAddress) {
12017
12268
  const m = "MORPHO_BLUE_" + uniqueKey.slice(2).toUpperCase();
12018
12269
  if (!data[m]) data[m] = { data: {} };
12019
12270
  const loanRewards = {};
@@ -12076,7 +12327,7 @@ function getMorphoMarketDataConverter(lender, chainId, prices, additionalYields
12076
12327
  depositRate: depositApr,
12077
12328
  variableBorrowRate: borrowApr,
12078
12329
  stableBorrowRate: 0,
12079
- stakingYield: additionalYields.intrinsicYields[meta?.assetGroup] ?? 0,
12330
+ intrinsicYield: additionalYields.intrinsicYields[meta?.assetGroup] ?? 0,
12080
12331
  rewards: Object.keys(loanRewards).length > 0 ? loanRewards : void 0,
12081
12332
  decimals: loanDecimals,
12082
12333
  config: {
@@ -12115,7 +12366,7 @@ function getMorphoMarketDataConverter(lender, chainId, prices, additionalYields
12115
12366
  depositRate: 0,
12116
12367
  variableBorrowRate: 0,
12117
12368
  stableBorrowRate: 0,
12118
- stakingYield: additionalYields.intrinsicYields[metaCollateral?.assetGroup] ?? 0,
12369
+ intrinsicYield: additionalYields.intrinsicYields[metaCollateral?.assetGroup] ?? 0,
12119
12370
  rewards: void 0,
12120
12371
  decimals: collateralDecimals,
12121
12372
  config: {
@@ -12155,137 +12406,6 @@ function getMorphoMarketDataConverter(lender, chainId, prices, additionalYields
12155
12406
  markets.length > 0 ? Math.ceil(markets.length / MARKET_CHUNK_SIZE) : 0
12156
12407
  ];
12157
12408
  }
12158
-
12159
- // src/abis/morpho/lens.ts
12160
- var MorphoLensAbi = [
12161
- {
12162
- inputs: [
12163
- {
12164
- internalType: "bytes32[]",
12165
- name: "marketsIds",
12166
- type: "bytes32[]"
12167
- },
12168
- {
12169
- internalType: "address",
12170
- name: "user",
12171
- type: "address"
12172
- },
12173
- {
12174
- internalType: "address",
12175
- name: "morpho",
12176
- type: "address"
12177
- }
12178
- ],
12179
- name: "getUserDataCompact",
12180
- outputs: [
12181
- {
12182
- internalType: "bytes",
12183
- name: "data",
12184
- type: "bytes"
12185
- }
12186
- ],
12187
- stateMutability: "view",
12188
- type: "function"
12189
- },
12190
- {
12191
- name: "getMarketDataCompact",
12192
- type: "function",
12193
- stateMutability: "view",
12194
- inputs: [
12195
- { type: "address", name: "morpho" },
12196
- { type: "bytes32[]", name: "marketsIds" }
12197
- ],
12198
- outputs: [{ type: "bytes", name: "data" }]
12199
- },
12200
- {
12201
- inputs: [
12202
- {
12203
- internalType: "bytes32[]",
12204
- name: "marketsIds",
12205
- type: "bytes32[]"
12206
- },
12207
- {
12208
- internalType: "address",
12209
- name: "user",
12210
- type: "address"
12211
- },
12212
- {
12213
- internalType: "address",
12214
- name: "morpho",
12215
- type: "address"
12216
- }
12217
- ],
12218
- name: "getUserDataCompact",
12219
- outputs: [
12220
- {
12221
- internalType: "bytes",
12222
- name: "data",
12223
- type: "bytes"
12224
- }
12225
- ],
12226
- stateMutability: "view",
12227
- type: "function"
12228
- },
12229
- {
12230
- name: "getMoolahMarketDataCompact",
12231
- type: "function",
12232
- stateMutability: "view",
12233
- inputs: [
12234
- { type: "address", name: "morpho" },
12235
- { type: "bytes32[]", name: "marketsIds" }
12236
- ],
12237
- outputs: [{ type: "bytes", name: "data" }]
12238
- },
12239
- {
12240
- inputs: [
12241
- {
12242
- internalType: "bytes32[]",
12243
- name: "marketsIds",
12244
- type: "bytes32[]"
12245
- },
12246
- {
12247
- internalType: "address",
12248
- name: "user",
12249
- type: "address"
12250
- },
12251
- {
12252
- internalType: "address",
12253
- name: "morpho",
12254
- type: "address"
12255
- }
12256
- ],
12257
- name: "getListaUserDataCompact",
12258
- outputs: [
12259
- {
12260
- internalType: "bytes",
12261
- name: "data",
12262
- type: "bytes"
12263
- }
12264
- ],
12265
- stateMutability: "view",
12266
- type: "function"
12267
- },
12268
- {
12269
- name: "getMoolahMarketDataCompact",
12270
- type: "function",
12271
- stateMutability: "view",
12272
- inputs: [
12273
- { type: "address", name: "morpho" },
12274
- { type: "bytes32[]", name: "marketsIds" }
12275
- ],
12276
- outputs: [{ type: "bytes", name: "data" }]
12277
- },
12278
- {
12279
- name: "getListaMarketDataCompact",
12280
- type: "function",
12281
- stateMutability: "view",
12282
- inputs: [
12283
- { type: "address", name: "morpho" },
12284
- { type: "bytes32[]", name: "marketsIds" }
12285
- ],
12286
- outputs: [{ type: "bytes", name: "data" }]
12287
- }
12288
- ];
12289
12409
  var VENUS_LENS_VBNB = "0xf15A9c5aaDc327B383945D5821C7aC08Cdac7430";
12290
12410
  var VENUS_LENS = {
12291
12411
  [Chain.BNB_SMART_CHAIN_MAINNET]: "0xA179d2f1Fd53D15Bc790bE91d5fF4a0108E29621",
@@ -12296,6 +12416,15 @@ var VENUS_LENS = {
12296
12416
  [Chain.OP_MAINNET]: "0x142160A2E699e33af337741f157D96aAd6bC72aA",
12297
12417
  [Chain.UNICHAIN]: "0xe192aeDBDBd235DBF33Ea1444f2B908Ea3E78419"
12298
12418
  };
12419
+ var SUMER_LENS = {
12420
+ [Chain.BNB_SMART_CHAIN_MAINNET]: "0xB7ea94340e65CC68d1274aE483dfBE593fD6f21e",
12421
+ // [Chain.ETHEREUM_MAINNET]: '',
12422
+ [Chain.ARBITRUM_ONE]: "0xbdBCf25E9187350b9102E316b707B1B2c7E51492",
12423
+ [Chain.BASE]: "0x2B43fBb7D1171bCfA31c9685f24A417dC8757064",
12424
+ [Chain.BERACHAIN]: "0x85D682FA4115f6a1Ed91170E705A50D532e3B6BD",
12425
+ [Chain.CORE_BLOCKCHAIN_MAINNET]: "0x894fc5177d8e670A4EF4C0aDA2FC5C04861b46Ab",
12426
+ [Chain.HEMI_NETWORK]: "0x6f064Eca024f7065b09372FEe1f8a3854843decA"
12427
+ };
12299
12428
  var MOONWELL_LENS = {
12300
12429
  [Chain.OP_MAINNET]: "0xD6C66868f937f00604d0FB860241970D6CC2CBfE",
12301
12430
  [Chain.BASE]: "0x6834770aba6c2028f448e3259ddee4bcb879d459",
@@ -12310,14 +12439,12 @@ var COMPOUND_V2_LENS = {
12310
12439
  [Lender.VENUS_ETH]: VENUS_LENS,
12311
12440
  [Lender.MOONWELL]: MOONWELL_LENS,
12312
12441
  [Lender.ENCLABS]: ENCLABS_LENS,
12313
- [Lender.ENCLABS_LST]: ENCLABS_LENS
12442
+ [Lender.ENCLABS_LST]: ENCLABS_LENS,
12443
+ [Lender.SUMER]: SUMER_LENS
12314
12444
  };
12315
12445
  function getCompoundV2Comptroller(chainId, lender = Lender.VENUS) {
12316
12446
  return compoundV2Pools()?.[lender]?.[chainId];
12317
12447
  }
12318
- function getCompoundV2CollateralTokens(chainId, lender = Lender.VENUS) {
12319
- return compoundV2Tokens()?.[lender]?.[chainId];
12320
- }
12321
12448
  function getCompoundV2Lens(chainId, lender) {
12322
12449
  return COMPOUND_V2_LENS[lender]?.[chainId];
12323
12450
  }
@@ -12465,11 +12592,395 @@ var VenusLensLegacyAbi = [
12465
12592
  }
12466
12593
  ];
12467
12594
 
12595
+ // src/abis/compound-v2/SumerLens.ts
12596
+ var SumerLensAbi = [
12597
+ {
12598
+ inputs: [
12599
+ {
12600
+ internalType: "contract ICToken",
12601
+ name: "cToken",
12602
+ type: "address"
12603
+ }
12604
+ ],
12605
+ name: "cTokenMetadata",
12606
+ outputs: [
12607
+ {
12608
+ components: [
12609
+ { internalType: "address", name: "cToken", type: "address" },
12610
+ {
12611
+ internalType: "uint256",
12612
+ name: "exchangeRateCurrent",
12613
+ type: "uint256"
12614
+ },
12615
+ {
12616
+ internalType: "uint256",
12617
+ name: "supplyRatePerBlock",
12618
+ type: "uint256"
12619
+ },
12620
+ {
12621
+ internalType: "uint256",
12622
+ name: "borrowRatePerBlock",
12623
+ type: "uint256"
12624
+ },
12625
+ {
12626
+ internalType: "uint256",
12627
+ name: "reserveFactorMantissa",
12628
+ type: "uint256"
12629
+ },
12630
+ { internalType: "uint256", name: "totalBorrows", type: "uint256" },
12631
+ { internalType: "uint256", name: "totalReserves", type: "uint256" },
12632
+ { internalType: "uint256", name: "totalSupply", type: "uint256" },
12633
+ { internalType: "uint256", name: "totalCash", type: "uint256" },
12634
+ { internalType: "bool", name: "isListed", type: "bool" },
12635
+ {
12636
+ internalType: "address",
12637
+ name: "underlyingAssetAddress",
12638
+ type: "address"
12639
+ },
12640
+ { internalType: "uint256", name: "cTokenDecimals", type: "uint256" },
12641
+ {
12642
+ internalType: "uint256",
12643
+ name: "underlyingDecimals",
12644
+ type: "uint256"
12645
+ },
12646
+ { internalType: "bool", name: "isCToken", type: "bool" },
12647
+ { internalType: "bool", name: "isCEther", type: "bool" },
12648
+ { internalType: "uint256", name: "borrowCap", type: "uint256" },
12649
+ { internalType: "uint256", name: "depositCap", type: "uint256" },
12650
+ {
12651
+ internalType: "uint256",
12652
+ name: "heteroLiquidationIncentive",
12653
+ type: "uint256"
12654
+ },
12655
+ {
12656
+ internalType: "uint256",
12657
+ name: "homoLiquidationIncentive",
12658
+ type: "uint256"
12659
+ },
12660
+ {
12661
+ internalType: "uint256",
12662
+ name: "sutokenLiquidationIncentive",
12663
+ type: "uint256"
12664
+ },
12665
+ { internalType: "uint8", name: "groupId", type: "uint8" },
12666
+ { internalType: "uint256", name: "intraRate", type: "uint256" },
12667
+ { internalType: "uint256", name: "interRate", type: "uint256" },
12668
+ { internalType: "uint256", name: "mintRate", type: "uint256" },
12669
+ { internalType: "uint256", name: "discountRate", type: "uint256" },
12670
+ { internalType: "bool", name: "interMintAllowed", type: "bool" }
12671
+ ],
12672
+ internalType: "struct SumerLens.CTokenMetadata",
12673
+ name: "",
12674
+ type: "tuple"
12675
+ }
12676
+ ],
12677
+ stateMutability: "nonpayable",
12678
+ type: "function"
12679
+ },
12680
+ {
12681
+ inputs: [
12682
+ {
12683
+ internalType: "contract ICToken[]",
12684
+ name: "cTokens",
12685
+ type: "address[]"
12686
+ }
12687
+ ],
12688
+ name: "cTokenMetadataAll",
12689
+ outputs: [
12690
+ {
12691
+ components: [
12692
+ { internalType: "address", name: "cToken", type: "address" },
12693
+ {
12694
+ internalType: "uint256",
12695
+ name: "exchangeRateCurrent",
12696
+ type: "uint256"
12697
+ },
12698
+ {
12699
+ internalType: "uint256",
12700
+ name: "supplyRatePerBlock",
12701
+ type: "uint256"
12702
+ },
12703
+ {
12704
+ internalType: "uint256",
12705
+ name: "borrowRatePerBlock",
12706
+ type: "uint256"
12707
+ },
12708
+ {
12709
+ internalType: "uint256",
12710
+ name: "reserveFactorMantissa",
12711
+ type: "uint256"
12712
+ },
12713
+ { internalType: "uint256", name: "totalBorrows", type: "uint256" },
12714
+ { internalType: "uint256", name: "totalReserves", type: "uint256" },
12715
+ { internalType: "uint256", name: "totalSupply", type: "uint256" },
12716
+ { internalType: "uint256", name: "totalCash", type: "uint256" },
12717
+ { internalType: "bool", name: "isListed", type: "bool" },
12718
+ {
12719
+ internalType: "address",
12720
+ name: "underlyingAssetAddress",
12721
+ type: "address"
12722
+ },
12723
+ { internalType: "uint256", name: "cTokenDecimals", type: "uint256" },
12724
+ {
12725
+ internalType: "uint256",
12726
+ name: "underlyingDecimals",
12727
+ type: "uint256"
12728
+ },
12729
+ { internalType: "bool", name: "isCToken", type: "bool" },
12730
+ { internalType: "bool", name: "isCEther", type: "bool" },
12731
+ { internalType: "uint256", name: "borrowCap", type: "uint256" },
12732
+ { internalType: "uint256", name: "depositCap", type: "uint256" },
12733
+ {
12734
+ internalType: "uint256",
12735
+ name: "heteroLiquidationIncentive",
12736
+ type: "uint256"
12737
+ },
12738
+ {
12739
+ internalType: "uint256",
12740
+ name: "homoLiquidationIncentive",
12741
+ type: "uint256"
12742
+ },
12743
+ {
12744
+ internalType: "uint256",
12745
+ name: "sutokenLiquidationIncentive",
12746
+ type: "uint256"
12747
+ },
12748
+ { internalType: "uint8", name: "groupId", type: "uint8" },
12749
+ { internalType: "uint256", name: "intraRate", type: "uint256" },
12750
+ { internalType: "uint256", name: "interRate", type: "uint256" },
12751
+ { internalType: "uint256", name: "mintRate", type: "uint256" },
12752
+ { internalType: "uint256", name: "discountRate", type: "uint256" },
12753
+ { internalType: "bool", name: "interMintAllowed", type: "bool" }
12754
+ ],
12755
+ internalType: "struct SumerLens.CTokenMetadata[]",
12756
+ name: "",
12757
+ type: "tuple[]"
12758
+ }
12759
+ ],
12760
+ stateMutability: "nonpayable",
12761
+ type: "function"
12762
+ },
12763
+ {
12764
+ inputs: [
12765
+ {
12766
+ internalType: "contract ICToken",
12767
+ name: "cToken",
12768
+ type: "address"
12769
+ },
12770
+ {
12771
+ internalType: "address payable",
12772
+ name: "account",
12773
+ type: "address"
12774
+ }
12775
+ ],
12776
+ name: "cTokenBalances",
12777
+ outputs: [
12778
+ {
12779
+ components: [
12780
+ { internalType: "address", name: "cToken", type: "address" },
12781
+ { internalType: "bool", name: "isCToken", type: "bool" },
12782
+ { internalType: "bool", name: "isCEther", type: "bool" },
12783
+ { internalType: "uint256", name: "balanceOf", type: "uint256" },
12784
+ {
12785
+ internalType: "uint256",
12786
+ name: "borrowBalanceCurrent",
12787
+ type: "uint256"
12788
+ },
12789
+ {
12790
+ internalType: "uint256",
12791
+ name: "balanceOfUnderlying",
12792
+ type: "uint256"
12793
+ },
12794
+ { internalType: "uint256", name: "tokenBalance", type: "uint256" },
12795
+ {
12796
+ internalType: "uint256",
12797
+ name: "tokenAllowance",
12798
+ type: "uint256"
12799
+ }
12800
+ ],
12801
+ internalType: "struct SumerLens.CTokenBalances",
12802
+ name: "",
12803
+ type: "tuple"
12804
+ }
12805
+ ],
12806
+ stateMutability: "nonpayable",
12807
+ type: "function"
12808
+ }
12809
+ ];
12810
+ var SumerComptrollerAbi = [
12811
+ {
12812
+ inputs: [
12813
+ { internalType: "uint8", name: "groupId", type: "uint8" }
12814
+ ],
12815
+ name: "assetGroup",
12816
+ outputs: [
12817
+ {
12818
+ components: [
12819
+ { internalType: "uint8", name: "groupId", type: "uint8" },
12820
+ {
12821
+ internalType: "uint16",
12822
+ name: "intraCRatePercent",
12823
+ type: "uint16"
12824
+ },
12825
+ {
12826
+ internalType: "uint16",
12827
+ name: "intraMintRatePercent",
12828
+ type: "uint16"
12829
+ },
12830
+ {
12831
+ internalType: "uint16",
12832
+ name: "intraSuRatePercent",
12833
+ type: "uint16"
12834
+ },
12835
+ {
12836
+ internalType: "uint16",
12837
+ name: "interCRatePercent",
12838
+ type: "uint16"
12839
+ },
12840
+ {
12841
+ internalType: "uint16",
12842
+ name: "interSuRatePercent",
12843
+ type: "uint16"
12844
+ }
12845
+ ],
12846
+ internalType: "struct IComptroller.CompactAssetGroup",
12847
+ name: "",
12848
+ type: "tuple"
12849
+ }
12850
+ ],
12851
+ stateMutability: "view",
12852
+ type: "function"
12853
+ }
12854
+ ];
12855
+
12856
+ // src/lending/public-data/compound-v2/getters/types.ts
12857
+ var CAction = /* @__PURE__ */ ((CAction2) => {
12858
+ CAction2[CAction2["MINT"] = 0] = "MINT";
12859
+ CAction2[CAction2["REDEEM"] = 1] = "REDEEM";
12860
+ CAction2[CAction2["BORROW"] = 2] = "BORROW";
12861
+ CAction2[CAction2["REPAY"] = 3] = "REPAY";
12862
+ CAction2[CAction2["SEIZE"] = 4] = "SEIZE";
12863
+ CAction2[CAction2["LIQUIDATE"] = 5] = "LIQUIDATE";
12864
+ CAction2[CAction2["TRANSFER"] = 6] = "TRANSFER";
12865
+ CAction2[CAction2["ENTER_MARKET"] = 7] = "ENTER_MARKET";
12866
+ CAction2[CAction2["EXIT_MARKET"] = 8] = "EXIT_MARKET";
12867
+ return CAction2;
12868
+ })(CAction || {});
12869
+
12870
+ // src/lending/public-data/compound-v2/getters/sumer.ts
12871
+ function readSumerCTokenMetadata(meta, token) {
12872
+ return {
12873
+ cToken: meta.cToken ?? "",
12874
+ exchangeRateCurrent: meta.exchangeRateCurrent ?? 0n,
12875
+ supplyRatePerBlock: meta.supplyRatePerBlock ?? 0n,
12876
+ borrowRatePerBlock: meta.borrowRatePerBlock ?? 0n,
12877
+ reserveFactorMantissa: meta.reserveFactorMantissa ?? 0n,
12878
+ totalBorrows: meta.totalBorrows ?? 0n,
12879
+ totalReserves: meta.totalReserves ?? 0n,
12880
+ totalSupply: meta.totalSupply ?? 0n,
12881
+ totalCash: meta.totalCash ?? 0n,
12882
+ isListed: meta.isListed ?? true,
12883
+ // use intraRate as the default collateralFactorMantissa for backward compat
12884
+ collateralFactorMantissa: meta.intraRate ?? 0n,
12885
+ underlyingAssetAddress: meta.underlyingAssetAddress ?? "",
12886
+ cTokenDecimals: meta.cTokenDecimals ?? 0n,
12887
+ underlyingDecimals: meta.underlyingDecimals ?? 0n,
12888
+ isCToken: meta.isCToken ?? true,
12889
+ isCEther: meta.isCEther ?? false,
12890
+ borrowCap: meta.borrowCap ?? 0n,
12891
+ depositCap: meta.depositCap ?? 0n,
12892
+ // group-based collateral factors
12893
+ groupId: Number(meta.groupId ?? 0),
12894
+ intraRate: meta.intraRate ?? 0n,
12895
+ interRate: meta.interRate ?? 0n,
12896
+ mintRate: meta.mintRate ?? 0n,
12897
+ discountRate: meta.discountRate ?? 0n,
12898
+ interMintAllowed: meta.interMintAllowed ?? false,
12899
+ // liquidation incentives
12900
+ heteroLiquidationIncentive: meta.heteroLiquidationIncentive ?? 0n,
12901
+ homoLiquidationIncentive: meta.homoLiquidationIncentive ?? 0n,
12902
+ sutokenLiquidationIncentive: meta.sutokenLiquidationIncentive ?? 0n,
12903
+ // no pausedActions bitmap in Sumer — default to not paused
12904
+ pausedActions: {
12905
+ [0 /* MINT */]: false,
12906
+ [1 /* REDEEM */]: false,
12907
+ [2 /* BORROW */]: false,
12908
+ [3 /* REPAY */]: false,
12909
+ [4 /* SEIZE */]: false,
12910
+ [5 /* LIQUIDATE */]: false,
12911
+ [6 /* TRANSFER */]: false,
12912
+ [7 /* ENTER_MARKET */]: false,
12913
+ [8 /* EXIT_MARKET */]: false
12914
+ },
12915
+ // borrow is allowed if listed (no explicit pause field)
12916
+ isBorrowAllowed: meta.isListed ?? true,
12917
+ depositRate: apyToApr(
12918
+ calculateRateForCompoundType(
12919
+ (meta.supplyRatePerBlock ?? 0n).toString(),
12920
+ token.chainId,
12921
+ 0 /* BLOCK */
12922
+ ) / 100
12923
+ ) * 100,
12924
+ variableBorrowRate: apyToApr(
12925
+ calculateRateForCompoundType(
12926
+ (meta.borrowRatePerBlock ?? 0n).toString(),
12927
+ token.chainId,
12928
+ 0 /* BLOCK */
12929
+ ) / 100
12930
+ ) * 100
12931
+ };
12932
+ }
12933
+ function parseSumerAssetGroup(raw) {
12934
+ if (!raw || typeof raw === "string") {
12935
+ return {
12936
+ groupId: 0,
12937
+ intraCRatePercent: 0,
12938
+ intraMintRatePercent: 0,
12939
+ intraSuRatePercent: 0,
12940
+ interCRatePercent: 0,
12941
+ interSuRatePercent: 0
12942
+ };
12943
+ }
12944
+ return {
12945
+ groupId: Number(raw.groupId ?? raw[0] ?? 0) || 0,
12946
+ intraCRatePercent: Number(raw.intraCRatePercent ?? raw[1] ?? 0) || 0,
12947
+ intraMintRatePercent: Number(raw.intraMintRatePercent ?? raw[2] ?? 0) || 0,
12948
+ intraSuRatePercent: Number(raw.intraSuRatePercent ?? raw[3] ?? 0) || 0,
12949
+ interCRatePercent: Number(raw.interCRatePercent ?? raw[4] ?? 0) || 0,
12950
+ interSuRatePercent: Number(raw.interSuRatePercent ?? raw[5] ?? 0) || 0
12951
+ };
12952
+ }
12953
+ var SUMER_GROUP_COUNT = 5;
12954
+ var SUMER_PERCENT_DIVISOR = 1e4;
12955
+ function normalizeSumerGroups(parsed) {
12956
+ return parsed.map((g) => ({
12957
+ groupId: g.groupId,
12958
+ intraCRate: g.intraCRatePercent / SUMER_PERCENT_DIVISOR,
12959
+ intraMintRate: g.intraMintRatePercent / SUMER_PERCENT_DIVISOR,
12960
+ intraSuRate: g.intraSuRatePercent / SUMER_PERCENT_DIVISOR,
12961
+ interCRate: g.interCRatePercent / SUMER_PERCENT_DIVISOR,
12962
+ interSuRate: g.interSuRatePercent / SUMER_PERCENT_DIVISOR
12963
+ }));
12964
+ }
12965
+
12468
12966
  // src/lending/public-data/compound-v2/publicCallBuild.ts
12469
12967
  var buildCompoundV2StyleLenderReserveCall = (chainId, lender) => {
12470
- const collateralTokens = getCompoundV2CollateralTokens(chainId, lender);
12968
+ const tokens = getCompoundV2Tokens(chainId, lender);
12471
12969
  const getCTokenCall = getCall(lender, chainId);
12472
- const calls = Object.values(collateralTokens).map(getCTokenCall);
12970
+ const calls = tokens.map((tk) => getCTokenCall(tk.cToken));
12971
+ if (isSumerType(lender)) {
12972
+ const comptroller = getCompoundV2Comptroller(chainId, lender);
12973
+ if (comptroller) {
12974
+ for (let groupId = 0; groupId < SUMER_GROUP_COUNT; groupId++) {
12975
+ calls.push({
12976
+ abi: SumerComptrollerAbi,
12977
+ address: comptroller,
12978
+ name: "assetGroup",
12979
+ params: [groupId]
12980
+ });
12981
+ }
12982
+ }
12983
+ }
12473
12984
  return calls;
12474
12985
  };
12475
12986
  function getCall(lender, chainId) {
@@ -12493,6 +13004,14 @@ function getCall(lender, chainId) {
12493
13004
  params: [tk]
12494
13005
  });
12495
13006
  }
13007
+ if (isSumerType(lender)) {
13008
+ return (tk) => ({
13009
+ abi: SumerLensAbi,
13010
+ address: lens,
13011
+ name: "cTokenMetadata",
13012
+ params: [tk]
13013
+ });
13014
+ }
12496
13015
  return (tk) => ({
12497
13016
  address: lens,
12498
13017
  name: "cTokenMetadata",
@@ -12500,20 +13019,6 @@ function getCall(lender, chainId) {
12500
13019
  });
12501
13020
  }
12502
13021
 
12503
- // src/lending/public-data/compound-v2/getters/types.ts
12504
- var CAction = /* @__PURE__ */ ((CAction2) => {
12505
- CAction2[CAction2["MINT"] = 0] = "MINT";
12506
- CAction2[CAction2["REDEEM"] = 1] = "REDEEM";
12507
- CAction2[CAction2["BORROW"] = 2] = "BORROW";
12508
- CAction2[CAction2["REPAY"] = 3] = "REPAY";
12509
- CAction2[CAction2["SEIZE"] = 4] = "SEIZE";
12510
- CAction2[CAction2["LIQUIDATE"] = 5] = "LIQUIDATE";
12511
- CAction2[CAction2["TRANSFER"] = 6] = "TRANSFER";
12512
- CAction2[CAction2["ENTER_MARKET"] = 7] = "ENTER_MARKET";
12513
- CAction2[CAction2["EXIT_MARKET"] = 8] = "EXIT_MARKET";
12514
- return CAction2;
12515
- })(CAction || {});
12516
-
12517
13022
  // src/lending/public-data/compound-v2/getters/venus.ts
12518
13023
  function readVTokenMetadata(meta, token) {
12519
13024
  const pick = (...values) => values.find((v) => v !== void 0);
@@ -12723,7 +13228,7 @@ function convertSingleEntry(opts) {
12723
13228
  totalDepositsUSD: totalSupplyUnderlying * price,
12724
13229
  totalDebtStable: 0,
12725
13230
  totalDebtStableUSD: 0,
12726
- stakingYield: additionalYields.intrinsicYields[asset.assetGroup] ?? 0,
13231
+ intrinsicYield: additionalYields.intrinsicYields[asset.assetGroup] ?? 0,
12727
13232
  config: {
12728
13233
  [LENDER_MODE_NO_MODE]: {
12729
13234
  category: LENDER_MODE_NO_MODE,
@@ -12756,15 +13261,115 @@ function convertSingleEntry(opts) {
12756
13261
  }
12757
13262
  };
12758
13263
  }
13264
+ function convertSumerEntry(opts) {
13265
+ const { entryRaw, asset, chainId, lender, prices, additionalYields, cToken, groups } = opts;
13266
+ const decs = asset.decimals;
13267
+ const currentEntry = readSumerCTokenMetadata(entryRaw, asset);
13268
+ const exchangeRateRaw = currentEntry.exchangeRateCurrent ?? 0n;
13269
+ const exchangeRateCurrent = parseRawAmount(
13270
+ exchangeRateRaw.toString(),
13271
+ PRICE_DECIMALS
13272
+ );
13273
+ const totalSupplyUnderlying = Number(parseRawAmount(currentEntry.totalSupply?.toString(), decs)) * Number(exchangeRateCurrent);
13274
+ const totalDebt = Number(
13275
+ parseRawAmount(currentEntry.totalBorrows?.toString(), decs)
13276
+ );
13277
+ const liquidity = totalSupplyUnderlying - totalDebt;
13278
+ const price = prices[asset.assetGroup] ?? 0;
13279
+ const poolId = asset.address;
13280
+ const collateralActive = Boolean(currentEntry.isListed);
13281
+ const borrowingEnabled = Boolean(currentEntry.isBorrowAllowed);
13282
+ const marketUid = createMarketUid(chainId, lender, cToken);
13283
+ const groupId = currentEntry.groupId;
13284
+ const intraRate = Number(
13285
+ parseRawAmount(currentEntry.intraRate?.toString(), RESERVE_MANTISSA_DECIMALS)
13286
+ );
13287
+ const interRate = Number(
13288
+ parseRawAmount(currentEntry.interRate?.toString(), RESERVE_MANTISSA_DECIMALS)
13289
+ );
13290
+ const config = {};
13291
+ for (let gId = 0; gId < SUMER_GROUP_COUNT; gId++) {
13292
+ const isOwnGroup = gId === groupId;
13293
+ const cf = isOwnGroup ? intraRate : interRate;
13294
+ config[gId] = {
13295
+ category: gId,
13296
+ borrowCollateralFactor: cf,
13297
+ collateralFactor: cf,
13298
+ borrowFactor: 1,
13299
+ collateralDisabled: !collateralActive,
13300
+ debtDisabled: !borrowingEnabled
13301
+ };
13302
+ }
13303
+ return {
13304
+ marketUid,
13305
+ poolId,
13306
+ asset,
13307
+ depositRate: currentEntry.depositRate,
13308
+ variableBorrowRate: currentEntry.variableBorrowRate,
13309
+ stableBorrowRate: 0,
13310
+ totalLiquidity: liquidity,
13311
+ totalLiquidityUSD: liquidity * price,
13312
+ totalDebt,
13313
+ totalDebtUSD: totalDebt * price,
13314
+ totalDeposits: totalSupplyUnderlying,
13315
+ totalDepositsUSD: totalSupplyUnderlying * price,
13316
+ totalDebtStable: 0,
13317
+ totalDebtStableUSD: 0,
13318
+ stakingYield: additionalYields.intrinsicYields[asset.assetGroup] ?? 0,
13319
+ config,
13320
+ hasStable: false,
13321
+ underlying: asset.address,
13322
+ isActive: Boolean(currentEntry.isListed),
13323
+ isFrozen: false,
13324
+ rewards: {},
13325
+ collateralActive,
13326
+ borrowingEnabled,
13327
+ params: {
13328
+ metadata: {
13329
+ cToken,
13330
+ exchangeRate: exchangeRateRaw.toString(),
13331
+ cTokenDecimals: Number(currentEntry.cTokenDecimals?.toString()),
13332
+ sumer: {
13333
+ isCToken: Boolean(currentEntry.isCToken),
13334
+ ...groups[groupId] ?? groups[0]
13335
+ }
13336
+ }
13337
+ }
13338
+ };
13339
+ }
12759
13340
  var getCompoundV2DataConverter = (lender, chainId, prices, additionalYields, tokenList = {}) => {
12760
13341
  const compoundV2Tokens2 = getCompoundV2Tokens(chainId, lender);
12761
- const expectedNumberOfCalls = compoundV2Tokens2.length;
13342
+ const tokenCount = compoundV2Tokens2.length;
13343
+ const isSumer = isSumerType(lender);
13344
+ const expectedNumberOfCalls = isSumer ? tokenCount + SUMER_GROUP_COUNT : tokenCount;
12762
13345
  const reader = getReader(lender);
12763
13346
  return [
12764
13347
  (data) => {
12765
13348
  if (data.length !== expectedNumberOfCalls) return void 0;
12766
13349
  const out = { data: {}, chainId };
12767
- for (let i = 0; i < compoundV2Tokens2.length; i++) {
13350
+ if (isSumer) {
13351
+ const groupData = data.slice(tokenCount);
13352
+ const groups = normalizeSumerGroups(groupData.map(parseSumerAssetGroup));
13353
+ for (let i = 0; i < tokenCount; i++) {
13354
+ const { underlying, cToken } = compoundV2Tokens2[i];
13355
+ if (!cToken || !underlying) continue;
13356
+ const poolId = underlying;
13357
+ const asset = tokenList[poolId];
13358
+ const entryRaw = data[i];
13359
+ out.data[poolId] = convertSumerEntry({
13360
+ entryRaw,
13361
+ asset,
13362
+ chainId,
13363
+ lender,
13364
+ prices,
13365
+ additionalYields,
13366
+ cToken,
13367
+ groups
13368
+ });
13369
+ }
13370
+ return out;
13371
+ }
13372
+ for (let i = 0; i < tokenCount; i++) {
12768
13373
  const { underlying, cToken } = compoundV2Tokens2[i];
12769
13374
  if (!cToken || !underlying) continue;
12770
13375
  const poolId = underlying;
@@ -12793,6 +13398,9 @@ function getReader(lender) {
12793
13398
  if (lender === Lender.MOONWELL) {
12794
13399
  return (x, t) => parseMoonwellMarket(x, t);
12795
13400
  }
13401
+ if (isSumerType(lender)) {
13402
+ return (x, t) => readSumerCTokenMetadata(x, t);
13403
+ }
12796
13404
  }
12797
13405
 
12798
13406
  // src/abis/compound-v2/VenusLens.ts
@@ -13711,6 +14319,7 @@ var getAbi = (lender) => {
13711
14319
  if (isCompoundV3(lender)) return [...IrgetterAbi, ...CometAbi, ...CometExtAbi];
13712
14320
  if (isInit(lender)) return InitLensAbi;
13713
14321
  if (isMorphoType(lender)) return MorphoLensAbi;
14322
+ if (isSumerType(lender)) return [...SumerLensAbi, ...SumerComptrollerAbi];
13714
14323
  if (isCompoundV2Type(lender)) return VenusLensAbi;
13715
14324
  return [];
13716
14325
  };
@@ -14159,24 +14768,26 @@ var buildAaveV3UserCall = (chainId, lender, account) => {
14159
14768
  }
14160
14769
  return calls;
14161
14770
  };
14162
-
14163
- // src/lending/user-data/init/userCallBuild.ts
14164
- var initBrokerAddresses = {
14165
- [Chain.MANTLE]: "0xc08BFef7E778f3519D79E96780b77066F5d4FCC0"
14166
- };
14167
- function getInitFlashAggregatorAddress(chainId) {
14168
- if (!chainId) return void 0;
14169
- return initBrokerAddresses[chainId];
14170
- }
14171
14771
  var buildInitUserCall = (chainId, lender, account) => {
14172
14772
  const lensContract = getInitLensAddress(chainId);
14173
- const brokerAddress = getInitFlashAggregatorAddress(chainId);
14174
- const call = {
14175
- address: lensContract,
14176
- name: "getUserPositionData",
14177
- params: [account, brokerAddress]
14178
- };
14179
- return [call];
14773
+ const calls = [];
14774
+ const legacyBroker = InitMarginAddresses.getLegacyFlashAggregator(chainId);
14775
+ if (legacyBroker) {
14776
+ calls.push({
14777
+ address: lensContract,
14778
+ name: "getUserPositionData",
14779
+ params: [account, legacyBroker]
14780
+ });
14781
+ }
14782
+ const currentBroker = InitMarginAddresses.getFlashAggregator(chainId);
14783
+ if (currentBroker) {
14784
+ calls.push({
14785
+ address: lensContract,
14786
+ name: "getUserPositionData",
14787
+ params: [account, currentBroker]
14788
+ });
14789
+ }
14790
+ return calls;
14180
14791
  };
14181
14792
 
14182
14793
  // src/lending/user-data/compound-v3/userCallBuild.ts
@@ -18421,107 +19032,6 @@ var YLDRAbi = [
18421
19032
  }
18422
19033
  ];
18423
19034
 
18424
- // src/abis/morpho/blue.ts
18425
- var MorphoBlueAbi = [
18426
- {
18427
- inputs: [
18428
- {
18429
- internalType: "Id",
18430
- name: "",
18431
- type: "bytes32"
18432
- },
18433
- {
18434
- internalType: "address",
18435
- name: "",
18436
- type: "address"
18437
- }
18438
- ],
18439
- name: "position",
18440
- outputs: [
18441
- {
18442
- internalType: "uint256",
18443
- name: "supplyShares",
18444
- type: "uint256"
18445
- },
18446
- {
18447
- internalType: "uint128",
18448
- name: "borrowShares",
18449
- type: "uint128"
18450
- },
18451
- {
18452
- internalType: "uint128",
18453
- name: "collateral",
18454
- type: "uint128"
18455
- }
18456
- ],
18457
- stateMutability: "view",
18458
- type: "function"
18459
- },
18460
- {
18461
- inputs: [
18462
- {
18463
- internalType: "bytes32[]",
18464
- name: "slots",
18465
- type: "bytes32[]"
18466
- }
18467
- ],
18468
- name: "extSloads",
18469
- outputs: [
18470
- {
18471
- internalType: "bytes32[]",
18472
- name: "res",
18473
- type: "bytes32[]"
18474
- }
18475
- ],
18476
- stateMutability: "view",
18477
- type: "function"
18478
- },
18479
- {
18480
- inputs: [
18481
- {
18482
- internalType: "Id",
18483
- name: "",
18484
- type: "bytes32"
18485
- }
18486
- ],
18487
- name: "market",
18488
- outputs: [
18489
- {
18490
- internalType: "uint128",
18491
- name: "totalSupplyAssets",
18492
- type: "uint128"
18493
- },
18494
- {
18495
- internalType: "uint128",
18496
- name: "totalSupplyShares",
18497
- type: "uint128"
18498
- },
18499
- {
18500
- internalType: "uint128",
18501
- name: "totalBorrowAssets",
18502
- type: "uint128"
18503
- },
18504
- {
18505
- internalType: "uint128",
18506
- name: "totalBorrowShares",
18507
- type: "uint128"
18508
- },
18509
- {
18510
- internalType: "uint128",
18511
- name: "lastUpdate",
18512
- type: "uint128"
18513
- },
18514
- {
18515
- internalType: "uint128",
18516
- name: "fee",
18517
- type: "uint128"
18518
- }
18519
- ],
18520
- stateMutability: "view",
18521
- type: "function"
18522
- }
18523
- ];
18524
-
18525
19035
  // src/abis/compound-v2/Comptroller.ts
18526
19036
  var ComptrollerAbi = [
18527
19037
  {
@@ -18780,104 +19290,108 @@ function createAaveV3Entry(i, data, key, meta) {
18780
19290
  addedDebt: (Number(currentVariableDebt) + Number(currentStableDebt)) * priceHist
18781
19291
  };
18782
19292
  }
18783
-
18784
- // src/lending/user-data/init/userCallParse.ts
18785
- var getInitUserDataConverter = (lender, chainId, account, metaMap) => {
18786
- const validOwner = account.toLowerCase();
18787
- const brokerAddress = getInitFlashAggregatorAddress(chainId) ?? "";
18788
- const expectedNumberOfCalls = 1;
18789
- return [
18790
- (_data) => {
18791
- if (_data.length !== expectedNumberOfCalls) {
18792
- return void 0;
18793
- }
18794
- const [data] = _data;
18795
- const indexes = data[0 /* posMeta */].map((e, i) => {
18796
- return { e, i };
18797
- }).filter((a) => a.e.owner.toLowerCase() === validOwner).map((a) => a.i);
18798
- let histData = {};
18799
- const modes = {};
18800
- let allPools = {};
18801
- const result = Object.assign(
19293
+ function parseSingleBrokerData(data, validOwner, brokerAddress, lender, chainId, metaMap) {
19294
+ const indexes = data[0 /* posMeta */].map((e, i) => ({ e, i })).filter((a) => a.e.owner.toLowerCase() === validOwner).map((a) => a.i);
19295
+ const histData = {};
19296
+ const modes = {};
19297
+ let allPools = {};
19298
+ const result = Object.assign(
19299
+ {},
19300
+ ...indexes.map((index) => {
19301
+ const entry = data[0 /* posMeta */][index];
19302
+ const mode = entry.mode;
19303
+ const id = entry.posId.toString();
19304
+ modes[id] = mode;
19305
+ const collatData = Object.assign(
18802
19306
  {},
18803
- ...indexes.map((index) => {
18804
- const entry = data[0 /* posMeta */][index];
18805
- const mode = entry.mode;
18806
- const id = entry.posId.toString();
18807
- modes[id] = mode;
18808
- const collatData = Object.assign(
18809
- {},
18810
- ...data[1 /* collaterals */][index].map(
18811
- (c) => {
18812
- const pool = c.pool.toLowerCase();
18813
- allPools[pool] = c.underlying.toLowerCase();
18814
- const key = createMarketUid(chainId, lender, pool);
18815
- const metaEntity = metaMap?.[key];
18816
- const decimals = metaEntity.asset?.decimals ?? 18;
18817
- const depositsRaw = c.amount.toString();
18818
- return {
18819
- [pool]: {
18820
- deposits: parseRawAmount(depositsRaw, decimals)
18821
- }
18822
- };
19307
+ ...data[1 /* collaterals */][index].map(
19308
+ (c) => {
19309
+ const pool = c.pool.toLowerCase();
19310
+ allPools[pool] = c.underlying.toLowerCase();
19311
+ const key = createMarketUid(chainId, lender, pool);
19312
+ const metaEntity = metaMap?.[key];
19313
+ const decimals = metaEntity.asset?.decimals ?? 18;
19314
+ const depositsRaw = c.amount.toString();
19315
+ return {
19316
+ [pool]: {
19317
+ deposits: parseRawAmount(depositsRaw, decimals)
18823
19318
  }
18824
- )
18825
- );
18826
- const debtData = Object.assign(
18827
- {},
18828
- ...data[2 /* debts */][index].map(
18829
- (c) => {
18830
- const pool = c.pool.toLowerCase();
18831
- allPools[pool] = c.underlying.toLowerCase();
18832
- const key = createMarketUid(chainId, lender, pool);
18833
- const metaEntity = metaMap?.[key];
18834
- const decimals = metaEntity.asset?.decimals ?? 18;
18835
- return {
18836
- [pool]: {
18837
- debt: parseRawAmount(c.amount.toString(), decimals)
18838
- }
18839
- };
19319
+ };
19320
+ }
19321
+ )
19322
+ );
19323
+ const debtData = Object.assign(
19324
+ {},
19325
+ ...data[2 /* debts */][index].map(
19326
+ (c) => {
19327
+ const pool = c.pool.toLowerCase();
19328
+ allPools[pool] = c.underlying.toLowerCase();
19329
+ const key = createMarketUid(chainId, lender, pool);
19330
+ const metaEntity = metaMap?.[key];
19331
+ const decimals = metaEntity.asset?.decimals ?? 18;
19332
+ return {
19333
+ [pool]: {
19334
+ debt: parseRawAmount(c.amount.toString(), decimals)
18840
19335
  }
18841
- )
18842
- );
18843
- return {
18844
- [id]: Object.assign(
18845
- {},
18846
- ...Object.entries(allPools).map(
18847
- ([pool, underlying]) => {
18848
- const key = createMarketUid(chainId, lender, pool);
18849
- const metaEntity = metaMap?.[key];
18850
- const price = metaEntity?.price?.priceUsd ?? 1;
18851
- const priceHist = metaEntity?.price?.priceUsd24h ?? price;
18852
- if (!histData[id])
18853
- histData[id] = {
18854
- totalDebt24h: 0,
18855
- totalDeposits24h: 0
18856
- };
18857
- const debt = debtData[pool]?.debt ?? 0;
18858
- const deposits = collatData[pool]?.deposits ?? 0;
18859
- histData[id].totalDebt24h += Number(debt) * priceHist;
18860
- histData[id].totalDeposits24h += Number(deposits) * priceHist;
18861
- return {
18862
- [key]: {
18863
- marketUid: key,
18864
- underlying,
18865
- deposits,
18866
- debt,
18867
- debtStable: "0",
18868
- debtStableUSD: 0,
18869
- depositsUSD: price * Number(deposits),
18870
- debtUSD: price * Number(debt),
18871
- collateralEnabled: true,
18872
- isAllowed: entry.approved.toLowerCase() === brokerAddress.toLowerCase()
18873
- }
18874
- };
18875
- }
18876
- )
18877
- )
18878
- };
18879
- })
19336
+ };
19337
+ }
19338
+ )
18880
19339
  );
19340
+ return {
19341
+ [id]: Object.assign(
19342
+ {},
19343
+ ...Object.entries(allPools).map(
19344
+ ([pool, underlying]) => {
19345
+ const key = createMarketUid(chainId, lender, pool);
19346
+ const metaEntity = metaMap?.[key];
19347
+ const price = metaEntity?.price?.priceUsd ?? 1;
19348
+ const priceHist = metaEntity?.price?.priceUsd24h ?? price;
19349
+ if (!histData[id])
19350
+ histData[id] = {
19351
+ totalDebt24h: 0,
19352
+ totalDeposits24h: 0
19353
+ };
19354
+ const debt = debtData[pool]?.debt ?? 0;
19355
+ const deposits = collatData[pool]?.deposits ?? 0;
19356
+ histData[id].totalDebt24h += Number(debt) * priceHist;
19357
+ histData[id].totalDeposits24h += Number(deposits) * priceHist;
19358
+ return {
19359
+ [key]: {
19360
+ marketUid: key,
19361
+ underlying,
19362
+ deposits,
19363
+ debt,
19364
+ debtStable: "0",
19365
+ debtStableUSD: 0,
19366
+ depositsUSD: price * Number(deposits),
19367
+ debtUSD: price * Number(debt),
19368
+ collateralEnabled: true,
19369
+ isAllowed: entry.approved.toLowerCase() === brokerAddress.toLowerCase()
19370
+ }
19371
+ };
19372
+ }
19373
+ )
19374
+ )
19375
+ };
19376
+ })
19377
+ );
19378
+ return { result, modes, histData };
19379
+ }
19380
+ var getInitUserDataConverter = (lender, chainId, account, metaMap) => {
19381
+ const validOwner = account.toLowerCase();
19382
+ const legacyBroker = InitMarginAddresses.getLegacyFlashAggregator(chainId) ?? "";
19383
+ const currentBroker = InitMarginAddresses.getFlashAggregator(chainId) ?? "";
19384
+ const expectedNumberOfCalls = 2;
19385
+ return [
19386
+ (_data) => {
19387
+ if (_data.length !== expectedNumberOfCalls) {
19388
+ return void 0;
19389
+ }
19390
+ const legacy = parseSingleBrokerData(_data[0], validOwner, legacyBroker, lender, chainId, metaMap);
19391
+ const current = parseSingleBrokerData(_data[1], validOwner, currentBroker, lender, chainId, metaMap);
19392
+ const result = { ...legacy.result, ...current.result };
19393
+ const modes = { ...legacy.modes, ...current.modes };
19394
+ const histData = { ...legacy.histData, ...current.histData };
18881
19395
  const payload = {
18882
19396
  chainId,
18883
19397
  lendingPositions: result,
@@ -19179,9 +19693,9 @@ var aprData = {
19179
19693
  rewardApr: 0,
19180
19694
  rewardDepositApr: 0,
19181
19695
  rewardBorrowApr: 0,
19182
- stakingApr: 0,
19183
- stakingDepositApr: 0,
19184
- stakingBorrowApr: 0
19696
+ intrinsicApr: 0,
19697
+ intrinsicDepositApr: 0,
19698
+ intrinsicBorrowApr: 0
19185
19699
  };
19186
19700
  var userDataEmpty = (account, chainId, notWhitelisted = false) => {
19187
19701
  return {
@@ -19477,7 +19991,8 @@ var getCompoundV2UserDataConverter = (lender, chainId, account, metaMap) => {
19477
19991
  lendingPositions: { "0": lendingPositions },
19478
19992
  rewards: {}
19479
19993
  };
19480
- const userData = createBaseTypeUserState(
19994
+ const createState = isSumerType(lender) ? createSumerUserState : createBaseTypeUserState;
19995
+ const userData = createState(
19481
19996
  payload,
19482
19997
  metaMap,
19483
19998
  totalDeposits24h,
@@ -19555,7 +20070,7 @@ var generateLendingPools = (lenderData, prices, histPrices) => {
19555
20070
  if (!byMarket.has(key)) byMarket.set(key, []);
19556
20071
  byMarket.get(key).push({
19557
20072
  ...pool,
19558
- apr: pool.depositRate + (pool.stakingYield ?? 0),
20073
+ apr: pool.depositRate + (pool.intrinsicYield ?? 0),
19559
20074
  utilitzation: (Number(pool.totalDebt) + Number(pool.totalDebtStable ?? 0)) / Number(pool.totalDeposits),
19560
20075
  exposure: []
19561
20076
  });
@@ -19899,7 +20414,7 @@ function buildPortfolioTotals(userDataResult) {
19899
20414
  lenderDebtWeight += balanceData2.debt;
19900
20415
  }
19901
20416
  totalNav24h += balanceData2.nav24h ?? 0;
19902
- totalRewardApr += aprData2.rewardApr + aprData2.rewardDepositApr + aprData2.rewardBorrowApr + aprData2.stakingApr;
20417
+ totalRewardApr += aprData2.rewardApr + aprData2.rewardDepositApr + aprData2.rewardBorrowApr + aprData2.intrinsicApr;
19903
20418
  }
19904
20419
  totalDepositsUSD += lenderDeposits;
19905
20420
  totalDebtUSD += lenderDebt;
@@ -19970,7 +20485,7 @@ function aggregateLenderData(lender, userData) {
19970
20485
  weight: balanceData2.deposits
19971
20486
  });
19972
20487
  }
19973
- totalRewardApr += aprData2.rewardApr + aprData2.rewardDepositApr + aprData2.rewardBorrowApr + aprData2.stakingApr;
20488
+ totalRewardApr += aprData2.rewardApr + aprData2.rewardDepositApr + aprData2.rewardBorrowApr + aprData2.intrinsicApr;
19974
20489
  if (health !== null && health > 0) {
19975
20490
  healthSum += health;
19976
20491
  healthCount++;
@@ -20118,6 +20633,872 @@ function fuseLenderData(userDataResult, summary) {
20118
20633
  return entries;
20119
20634
  }
20120
20635
 
20636
+ // src/lending/margin/base/utils.ts
20637
+ var EMPTY_BALANCE = {
20638
+ rewards: void 0,
20639
+ borrowDiscountedCollateral: 0,
20640
+ borrowDiscountedCollateralAllActive: 0,
20641
+ collateral: 0,
20642
+ collateralAllActive: 0,
20643
+ deposits: 0,
20644
+ debt: 0,
20645
+ adjustedDebt: 0,
20646
+ nav: 0,
20647
+ deposits24h: 0,
20648
+ debt24h: 0,
20649
+ nav24h: 0
20650
+ };
20651
+ var positivePart = (x) => x > 0 ? x : 0;
20652
+ function getHealthFactor(collateral, adjustedDebt) {
20653
+ if (adjustedDebt === 0) return Infinity;
20654
+ const raw = collateral / adjustedDebt;
20655
+ return Number.isNaN(raw) ? 0 : Math.round(raw * 1e4) / 1e4;
20656
+ }
20657
+ function getBorrowCapacity(bd) {
20658
+ return bd.borrowDiscountedCollateral - bd.adjustedDebt;
20659
+ }
20660
+ function getAssetConfig(config, modeId) {
20661
+ const entry = config[modeId];
20662
+ if (!entry) {
20663
+ throw new Error(`No config found for modeId ${modeId}`);
20664
+ }
20665
+ return entry;
20666
+ }
20667
+ function computePostTradeMetrics(balanceData2, postTrade) {
20668
+ const healthFactor = getHealthFactor(balanceData2.collateral, balanceData2.adjustedDebt);
20669
+ const healthFactorPost = postTrade.adjustedDebt === 0 ? Infinity : positivePart(getHealthFactor(postTrade.collateral, postTrade.adjustedDebt));
20670
+ return {
20671
+ healthFactor,
20672
+ healthFactorPost,
20673
+ borrowCapacity: getBorrowCapacity(balanceData2),
20674
+ borrowCapacityPost: getBorrowCapacity(postTrade),
20675
+ balanceDataPost: postTrade
20676
+ };
20677
+ }
20678
+
20679
+ // src/lending/margin/base/yield/getOrganicYieldChange.ts
20680
+ function getOrganicYieldDeposit(amountUSD, cashFlowDeposits, cashFlowDebt, deposits, debt, yieldParams) {
20681
+ const totalCashFlowDeposits = cashFlowDeposits + amountUSD * yieldParams.depositRate;
20682
+ const newCollat = deposits + amountUSD;
20683
+ return [
20684
+ Math.abs(debt) < 0.01 ? 0 : cashFlowDebt / debt,
20685
+ totalCashFlowDeposits / newCollat,
20686
+ (totalCashFlowDeposits - cashFlowDebt) / (newCollat - debt)
20687
+ ];
20688
+ }
20689
+ function getOrganicYieldBorrow(amountUSD, irMode, cashFlowDeposits, cashFlowDebt, deposits, debt, yieldParams) {
20690
+ const totalCashFlowDebt = cashFlowDebt + amountUSD * (irMode === 1 ? yieldParams.stableBorrowRate : yieldParams.variableBorrowRate);
20691
+ const newDebt = debt + amountUSD;
20692
+ return [
20693
+ totalCashFlowDebt / newDebt,
20694
+ Math.abs(deposits) < 0.01 ? 0 : cashFlowDeposits / deposits,
20695
+ (cashFlowDeposits - totalCashFlowDebt) / (deposits - newDebt)
20696
+ ];
20697
+ }
20698
+ function getOrganicYieldWithdraw(amountUSD, cashFlowDeposits, cashFlowDebt, deposits, debt, yieldParams) {
20699
+ const totalCashFlowDeposits = cashFlowDeposits - amountUSD * yieldParams.depositRate;
20700
+ const newCollat = deposits - amountUSD;
20701
+ return [
20702
+ Math.abs(debt) < 0.01 ? 0 : cashFlowDebt / debt,
20703
+ totalCashFlowDeposits / newCollat,
20704
+ (totalCashFlowDeposits - cashFlowDebt) / (newCollat - debt)
20705
+ ];
20706
+ }
20707
+ function getOrganicYieldRepay(amountUSD, irMode, cashFlowDeposits, cashFlowDebt, deposits, debt, yieldParams) {
20708
+ const totalCashFlowDebt = cashFlowDebt - amountUSD * (irMode === 1 ? yieldParams.stableBorrowRate : yieldParams.variableBorrowRate);
20709
+ const newDebt = debt - amountUSD;
20710
+ return [
20711
+ Math.abs(newDebt) < 0.01 ? 0 : totalCashFlowDebt / newDebt,
20712
+ Math.abs(deposits) < 0.01 ? 0 : cashFlowDeposits / deposits,
20713
+ (cashFlowDeposits - totalCashFlowDebt) / (deposits - newDebt)
20714
+ ];
20715
+ }
20716
+
20717
+ // src/lending/margin/base/yield/getIntrinsicYieldChange.ts
20718
+ function getIntrinsicYieldDeposit(amountUSD, cashFlowDeposits, cashFlowDebt, deposits, debt, yieldParams) {
20719
+ const totalCashFlowDeposits = cashFlowDeposits + amountUSD * yieldParams.intrinsicYield;
20720
+ const newCollat = deposits + amountUSD;
20721
+ return [
20722
+ Math.abs(debt) < 0.01 ? 0 : cashFlowDebt / debt,
20723
+ totalCashFlowDeposits / newCollat,
20724
+ (totalCashFlowDeposits - cashFlowDebt) / (newCollat - debt)
20725
+ ];
20726
+ }
20727
+ function getIntrinsicYieldBorrow(amountUSD, cashFlowDeposits, cashFlowDebt, deposits, debt, yieldParams) {
20728
+ const totalCashFlowDebt = cashFlowDebt + amountUSD * yieldParams.intrinsicYield;
20729
+ const newDebt = debt + amountUSD;
20730
+ return [
20731
+ totalCashFlowDebt / newDebt,
20732
+ Math.abs(deposits) < 0.01 ? 0 : cashFlowDeposits / deposits,
20733
+ (cashFlowDeposits - totalCashFlowDebt) / (deposits - newDebt)
20734
+ ];
20735
+ }
20736
+ function getIntrinsicYieldWithdraw(amountUSD, cashFlowDeposits, cashFlowDebt, deposits, debt, yieldParams) {
20737
+ const totalCashFlowDeposits = cashFlowDeposits - amountUSD * yieldParams.intrinsicYield;
20738
+ const newCollat = deposits - amountUSD;
20739
+ return [
20740
+ Math.abs(debt) < 0.01 ? 0 : cashFlowDebt / debt,
20741
+ totalCashFlowDeposits / newCollat,
20742
+ (totalCashFlowDeposits - cashFlowDebt) / (newCollat - debt)
20743
+ ];
20744
+ }
20745
+ function getIntrinsicYieldRepay(amountUSD, cashFlowDeposits, cashFlowDebt, deposits, debt, yieldParams) {
20746
+ const totalCashFlowDebt = cashFlowDebt - amountUSD * yieldParams.intrinsicYield;
20747
+ const newDebt = debt - amountUSD;
20748
+ return [
20749
+ Math.abs(newDebt) < 0.01 ? 0 : totalCashFlowDebt / newDebt,
20750
+ Math.abs(deposits) < 0.01 ? 0 : cashFlowDeposits / deposits,
20751
+ (cashFlowDeposits - totalCashFlowDebt) / (deposits - newDebt)
20752
+ ];
20753
+ }
20754
+
20755
+ // src/lending/margin/base/yield/getRewardYieldChange.ts
20756
+ function getRewardYieldDeposit(amountUSD, cashFlowDeposits, cashFlowDebt, deposits, debt, yieldParams) {
20757
+ const rewards = yieldParams?.rewards;
20758
+ if (!rewards) return {};
20759
+ const data = {};
20760
+ for (const key of Object.keys(rewards)) {
20761
+ const _flowOut = amountUSD * (rewards[key]?.depositRate ?? 0);
20762
+ const totalCashFlowDeposits = cashFlowDeposits + _flowOut;
20763
+ const newCollat = deposits + amountUSD;
20764
+ data[key] = {
20765
+ borrowApr: Math.abs(debt) < 0.01 ? 0 : cashFlowDebt / debt,
20766
+ depositApr: totalCashFlowDeposits / newCollat,
20767
+ apr: (cashFlowDeposits + cashFlowDebt + _flowOut) / (newCollat - debt)
20768
+ };
20769
+ }
20770
+ return data;
20771
+ }
20772
+ function getRewardYieldBorrow(amountUSD, irMode, cashFlowDeposits, cashFlowDebt, deposits, debt, yieldParams) {
20773
+ const rewards = yieldParams?.rewards;
20774
+ if (!rewards) return {};
20775
+ const data = {};
20776
+ for (const key of Object.keys(rewards)) {
20777
+ const _flowIn = amountUSD * ((irMode === 1 ? rewards[key]?.stableBorrowRate : rewards[key]?.variableBorrowRate) ?? 0);
20778
+ const totalCashFlowDebt = cashFlowDebt + _flowIn;
20779
+ const newDebt = debt + amountUSD;
20780
+ data[key] = {
20781
+ borrowApr: totalCashFlowDebt / newDebt,
20782
+ depositApr: Math.abs(deposits) < 0.01 ? 0 : cashFlowDeposits / deposits,
20783
+ apr: (cashFlowDeposits + cashFlowDebt + _flowIn) / (deposits - newDebt)
20784
+ };
20785
+ }
20786
+ return data;
20787
+ }
20788
+ function getRewardYieldWithdraw(amountUSD, cashFlowDeposits, cashFlowDebt, deposits, debt, yieldParams) {
20789
+ const rewards = yieldParams?.rewards;
20790
+ if (!rewards) return {};
20791
+ const data = {};
20792
+ for (const key of Object.keys(rewards)) {
20793
+ const _flowIn = amountUSD * (rewards[key]?.depositRate ?? 0);
20794
+ const totalCashFlowDeposits = cashFlowDeposits - _flowIn;
20795
+ const newCollat = deposits - amountUSD;
20796
+ data[key] = {
20797
+ borrowApr: Math.abs(debt) < 0.01 ? 0 : cashFlowDebt / debt,
20798
+ depositApr: totalCashFlowDeposits / newCollat,
20799
+ apr: (cashFlowDeposits + cashFlowDebt - _flowIn) / (newCollat - debt)
20800
+ };
20801
+ }
20802
+ return data;
20803
+ }
20804
+ function getRewardYieldRepay(amountUSD, irMode, cashFlowDeposits, cashFlowDebt, deposits, debt, yieldParams) {
20805
+ const rewards = yieldParams?.rewards;
20806
+ if (!rewards) return {};
20807
+ const data = {};
20808
+ for (const key of Object.keys(rewards)) {
20809
+ const _flowOut = amountUSD * ((irMode === 1 ? rewards[key]?.stableBorrowRate : rewards[key]?.variableBorrowRate) ?? 0);
20810
+ const totalCashFlowDebt = cashFlowDebt - _flowOut;
20811
+ const newDebt = debt - amountUSD;
20812
+ data[key] = {
20813
+ borrowApr: Math.abs(newDebt) < 0.01 ? 0 : totalCashFlowDebt / newDebt,
20814
+ depositApr: Math.abs(deposits) < 0.01 ? 0 : cashFlowDeposits / deposits,
20815
+ apr: (cashFlowDeposits + cashFlowDebt - _flowOut) / (deposits - newDebt)
20816
+ };
20817
+ }
20818
+ return data;
20819
+ }
20820
+
20821
+ // src/lending/margin/base/deposit.ts
20822
+ function computeDepositDelta(amount, price, balanceData2, config, modeId, createNewSubAccount = false, apr, yieldParams) {
20823
+ const { borrowCollateralFactor, collateralFactor } = getAssetConfig(config, modeId);
20824
+ const base = createNewSubAccount ? EMPTY_BALANCE : balanceData2;
20825
+ const dollarAmount = amount * price;
20826
+ const postTrade = {
20827
+ ...base,
20828
+ borrowDiscountedCollateral: base.borrowDiscountedCollateral + borrowCollateralFactor * dollarAmount,
20829
+ collateral: base.collateral + collateralFactor * dollarAmount,
20830
+ deposits: base.deposits + dollarAmount,
20831
+ nav: base.nav + dollarAmount
20832
+ };
20833
+ const result = computePostTradeMetrics(base, postTrade);
20834
+ if (apr && yieldParams) {
20835
+ const cashFlowDeposits = base.deposits * apr.depositApr;
20836
+ const cashFlowDebt = base.debt * apr.borrowApr;
20837
+ const rewardFlowDeposits = base.deposits * (apr.rewardDepositApr ?? 0);
20838
+ const rewardFlowDebt = base.debt * (apr.rewardBorrowApr ?? 0);
20839
+ const intrinsicFlowDeposits = base.deposits * apr.intrinsicDepositApr;
20840
+ const intrinsicFlowDebt = base.debt * apr.intrinsicBorrowApr;
20841
+ const newApr = { ...apr };
20842
+ [newApr.borrowApr, newApr.depositApr, newApr.apr] = getOrganicYieldDeposit(
20843
+ dollarAmount,
20844
+ cashFlowDeposits,
20845
+ cashFlowDebt,
20846
+ base.deposits,
20847
+ base.debt,
20848
+ yieldParams
20849
+ );
20850
+ newApr.rewards = getRewardYieldDeposit(
20851
+ dollarAmount,
20852
+ rewardFlowDeposits,
20853
+ rewardFlowDebt,
20854
+ base.deposits,
20855
+ base.debt,
20856
+ yieldParams
20857
+ );
20858
+ [newApr.intrinsicBorrowApr, newApr.intrinsicDepositApr, newApr.intrinsicApr] = getIntrinsicYieldDeposit(
20859
+ dollarAmount,
20860
+ intrinsicFlowDeposits,
20861
+ intrinsicFlowDebt,
20862
+ base.deposits,
20863
+ base.debt,
20864
+ yieldParams
20865
+ );
20866
+ result.aprDataPost = newApr;
20867
+ }
20868
+ return result;
20869
+ }
20870
+
20871
+ // src/lending/margin/base/withdraw.ts
20872
+ function computeWithdrawDelta(amount, price, balanceData2, config, modeId, apr, yieldParams) {
20873
+ const { borrowCollateralFactor, collateralFactor } = getAssetConfig(config, modeId);
20874
+ const dollarAmount = amount * price;
20875
+ const postTrade = {
20876
+ ...balanceData2,
20877
+ borrowDiscountedCollateral: balanceData2.borrowDiscountedCollateral - borrowCollateralFactor * dollarAmount,
20878
+ collateral: balanceData2.collateral - collateralFactor * dollarAmount,
20879
+ deposits: balanceData2.deposits - dollarAmount,
20880
+ nav: balanceData2.nav - dollarAmount
20881
+ };
20882
+ const result = computePostTradeMetrics(balanceData2, postTrade);
20883
+ if (apr && yieldParams) {
20884
+ const cashFlowDeposits = balanceData2.deposits * apr.depositApr;
20885
+ const cashFlowDebt = balanceData2.debt * apr.borrowApr;
20886
+ const rewardFlowDeposits = balanceData2.deposits * (apr.rewardDepositApr ?? 0);
20887
+ const rewardFlowDebt = balanceData2.debt * (apr.rewardBorrowApr ?? 0);
20888
+ const intrinsicFlowDeposits = balanceData2.deposits * apr.intrinsicDepositApr;
20889
+ const intrinsicFlowDebt = balanceData2.debt * apr.intrinsicBorrowApr;
20890
+ const newApr = { ...apr };
20891
+ [newApr.borrowApr, newApr.depositApr, newApr.apr] = getOrganicYieldWithdraw(
20892
+ dollarAmount,
20893
+ cashFlowDeposits,
20894
+ cashFlowDebt,
20895
+ balanceData2.deposits,
20896
+ balanceData2.debt,
20897
+ yieldParams
20898
+ );
20899
+ newApr.rewards = getRewardYieldWithdraw(
20900
+ dollarAmount,
20901
+ rewardFlowDeposits,
20902
+ rewardFlowDebt,
20903
+ balanceData2.deposits,
20904
+ balanceData2.debt,
20905
+ yieldParams
20906
+ );
20907
+ [newApr.intrinsicBorrowApr, newApr.intrinsicDepositApr, newApr.intrinsicApr] = getIntrinsicYieldWithdraw(
20908
+ dollarAmount,
20909
+ intrinsicFlowDeposits,
20910
+ intrinsicFlowDebt,
20911
+ balanceData2.deposits,
20912
+ balanceData2.debt,
20913
+ yieldParams
20914
+ );
20915
+ result.aprDataPost = newApr;
20916
+ }
20917
+ return result;
20918
+ }
20919
+
20920
+ // src/lending/margin/base/borrow.ts
20921
+ function computeBorrowDelta(amount, price, balanceData2, config, modeId, apr, yieldParams, irMode) {
20922
+ const { borrowFactor } = getAssetConfig(config, modeId);
20923
+ const dollarAmount = amount * price;
20924
+ const postTrade = {
20925
+ ...balanceData2,
20926
+ debt: balanceData2.debt + dollarAmount,
20927
+ adjustedDebt: balanceData2.adjustedDebt + borrowFactor * dollarAmount,
20928
+ nav: balanceData2.nav - dollarAmount
20929
+ };
20930
+ const result = computePostTradeMetrics(balanceData2, postTrade);
20931
+ if (apr && yieldParams) {
20932
+ const mode = irMode ?? 2;
20933
+ const cashFlowDeposits = balanceData2.deposits * apr.depositApr;
20934
+ const cashFlowDebt = balanceData2.debt * apr.borrowApr;
20935
+ const rewardFlowDeposits = balanceData2.deposits * (apr.rewardDepositApr ?? 0);
20936
+ const rewardFlowDebt = balanceData2.debt * (apr.rewardBorrowApr ?? 0);
20937
+ const intrinsicFlowDeposits = balanceData2.deposits * apr.intrinsicDepositApr;
20938
+ const intrinsicFlowDebt = balanceData2.debt * apr.intrinsicBorrowApr;
20939
+ const newApr = { ...apr };
20940
+ [newApr.borrowApr, newApr.depositApr, newApr.apr] = getOrganicYieldBorrow(
20941
+ dollarAmount,
20942
+ mode,
20943
+ cashFlowDeposits,
20944
+ cashFlowDebt,
20945
+ balanceData2.deposits,
20946
+ balanceData2.debt,
20947
+ yieldParams
20948
+ );
20949
+ newApr.rewards = getRewardYieldBorrow(
20950
+ dollarAmount,
20951
+ mode,
20952
+ rewardFlowDeposits,
20953
+ rewardFlowDebt,
20954
+ balanceData2.deposits,
20955
+ balanceData2.debt,
20956
+ yieldParams
20957
+ );
20958
+ [newApr.intrinsicBorrowApr, newApr.intrinsicDepositApr, newApr.intrinsicApr] = getIntrinsicYieldBorrow(
20959
+ dollarAmount,
20960
+ intrinsicFlowDeposits,
20961
+ intrinsicFlowDebt,
20962
+ balanceData2.deposits,
20963
+ balanceData2.debt,
20964
+ yieldParams
20965
+ );
20966
+ result.aprDataPost = newApr;
20967
+ }
20968
+ return result;
20969
+ }
20970
+
20971
+ // src/lending/margin/base/repay.ts
20972
+ function computeRepayDelta(amount, price, balanceData2, config, modeId, apr, yieldParams, irMode) {
20973
+ const { borrowFactor } = getAssetConfig(config, modeId);
20974
+ const dollarAmount = amount * price;
20975
+ const postTrade = {
20976
+ ...balanceData2,
20977
+ debt: balanceData2.debt - dollarAmount,
20978
+ adjustedDebt: Math.max(0, balanceData2.adjustedDebt - borrowFactor * dollarAmount),
20979
+ nav: balanceData2.nav + dollarAmount
20980
+ };
20981
+ const result = computePostTradeMetrics(balanceData2, postTrade);
20982
+ if (apr && yieldParams) {
20983
+ const mode = irMode ?? 2;
20984
+ const cashFlowDeposits = balanceData2.deposits * apr.depositApr;
20985
+ const cashFlowDebt = balanceData2.debt * apr.borrowApr;
20986
+ const rewardFlowDeposits = balanceData2.deposits * (apr.rewardDepositApr ?? 0);
20987
+ const rewardFlowDebt = balanceData2.debt * (apr.rewardBorrowApr ?? 0);
20988
+ const intrinsicFlowDeposits = balanceData2.deposits * apr.intrinsicDepositApr;
20989
+ const intrinsicFlowDebt = balanceData2.debt * apr.intrinsicBorrowApr;
20990
+ const newApr = { ...apr };
20991
+ [newApr.borrowApr, newApr.depositApr, newApr.apr] = getOrganicYieldRepay(
20992
+ dollarAmount,
20993
+ mode,
20994
+ cashFlowDeposits,
20995
+ cashFlowDebt,
20996
+ balanceData2.deposits,
20997
+ balanceData2.debt,
20998
+ yieldParams
20999
+ );
21000
+ newApr.rewards = getRewardYieldRepay(
21001
+ dollarAmount,
21002
+ mode,
21003
+ rewardFlowDeposits,
21004
+ rewardFlowDebt,
21005
+ balanceData2.deposits,
21006
+ balanceData2.debt,
21007
+ yieldParams
21008
+ );
21009
+ [newApr.intrinsicBorrowApr, newApr.intrinsicDepositApr, newApr.intrinsicApr] = getIntrinsicYieldRepay(
21010
+ dollarAmount,
21011
+ intrinsicFlowDeposits,
21012
+ intrinsicFlowDebt,
21013
+ balanceData2.deposits,
21014
+ balanceData2.debt,
21015
+ yieldParams
21016
+ );
21017
+ result.aprDataPost = newApr;
21018
+ }
21019
+ return result;
21020
+ }
21021
+
21022
+ // src/lending/margin/loop/utils.ts
21023
+ var positivePart2 = (n) => n < 0 ? 0 : n;
21024
+ function nanTo(possiblyNaN, replacement = Infinity) {
21025
+ return isNaN(possiblyNaN) ? replacement : possiblyNaN;
21026
+ }
21027
+ function getHealthFactor2(collateral, adjustedDebt) {
21028
+ if (adjustedDebt === 0) return Infinity;
21029
+ const raw = collateral / adjustedDebt;
21030
+ return Math.round((isNaN(raw) ? 0 : raw) * 1e4) / 1e4;
21031
+ }
21032
+ function keysFromMaps(a, b) {
21033
+ const set = /* @__PURE__ */ new Set();
21034
+ if (a) for (const k of Object.keys(a)) set.add(k);
21035
+ if (b) for (const k of Object.keys(b)) set.add(k);
21036
+ return [...set];
21037
+ }
21038
+ function noOpResult(balance, apr) {
21039
+ const hf = getHealthFactor2(balance.collateral, balance.adjustedDebt);
21040
+ return {
21041
+ balanceDataPost: balance,
21042
+ aprDataPost: apr,
21043
+ healthFactor: hf,
21044
+ healthFactorPost: hf,
21045
+ borrowCapacity: balance.collateral - balance.adjustedDebt,
21046
+ borrowCapacityPost: balance.collateral - balance.adjustedDebt
21047
+ };
21048
+ }
21049
+ function buildLoopResult(balance, newBalance, apr, newApr, useAllActive = false) {
21050
+ const collateralPost = useAllActive ? newBalance.collateralAllActive : newBalance.collateral;
21051
+ return {
21052
+ balanceDataPost: newBalance,
21053
+ aprDataPost: newApr,
21054
+ healthFactor: getHealthFactor2(balance.collateral, balance.adjustedDebt),
21055
+ healthFactorPost: newBalance.adjustedDebt === 0 ? Infinity : positivePart2(getHealthFactor2(collateralPost, newBalance.adjustedDebt)),
21056
+ borrowCapacity: balance.collateral - balance.adjustedDebt,
21057
+ borrowCapacityPost: newBalance.collateral - newBalance.adjustedDebt
21058
+ };
21059
+ }
21060
+
21061
+ // src/lending/margin/loop/yield/getOraganicYieldChange.ts
21062
+ function getOrganicYieldOpen(amountInUSD, amountOutUSD, irModeIn, cashFlowDeposits, cashFlowDebt, deposits, debt, yieldIn, yieldOut) {
21063
+ const _flowIn = amountInUSD * (irModeIn === 1 ? yieldIn.stableBorrowRate : yieldIn.variableBorrowRate);
21064
+ const _flowOut = amountOutUSD * yieldOut.depositRate;
21065
+ const totalCashFlowDebt = cashFlowDebt + _flowIn;
21066
+ const totalCashFlowDeposits = cashFlowDeposits + _flowOut;
21067
+ const newCollat = deposits + amountOutUSD;
21068
+ const newDebt = debt + amountInUSD;
21069
+ return [
21070
+ totalCashFlowDebt / newDebt,
21071
+ totalCashFlowDeposits / newCollat,
21072
+ (totalCashFlowDeposits - totalCashFlowDebt) / (newCollat - newDebt)
21073
+ ];
21074
+ }
21075
+ function getOrganicYieldClose(amountInUSD, amountOutUSD, irModeOut, cashFlowDeposits, cashFlowDebt, deposits, debt, yieldIn, yieldOut) {
21076
+ const _flowIn = amountInUSD * yieldIn.depositRate;
21077
+ const _flowOut = amountOutUSD * (irModeOut === 1 ? yieldOut.stableBorrowRate : yieldOut.variableBorrowRate);
21078
+ const totalCashFlowDebt = cashFlowDebt - _flowOut;
21079
+ const totalCashFlowDeposits = cashFlowDeposits - _flowIn;
21080
+ const newCollat = deposits - amountInUSD;
21081
+ const newDebt = debt - amountOutUSD;
21082
+ return [
21083
+ Math.abs(newDebt) < 0.01 ? 0 : totalCashFlowDebt / newDebt,
21084
+ totalCashFlowDeposits / newCollat,
21085
+ (totalCashFlowDeposits - totalCashFlowDebt) / (newCollat - newDebt)
21086
+ ];
21087
+ }
21088
+ function getOrganicYieldDebtSwap(amountInUSD, amountOutUSD, irModeIn, irModeOut, cashFlowDeposits, cashFlowDebt, deposits, debt, yieldIn, yieldOut) {
21089
+ const _flowIn = amountInUSD * (irModeIn === 1 ? yieldIn.stableBorrowRate : yieldIn.variableBorrowRate);
21090
+ const _flowOut = amountOutUSD * (irModeOut === 1 ? yieldOut.stableBorrowRate : yieldOut.variableBorrowRate);
21091
+ const totalCashFlowDebt = cashFlowDebt + _flowIn - _flowOut;
21092
+ const newDebt = debt - amountOutUSD + amountInUSD;
21093
+ return [
21094
+ Math.abs(newDebt) < 0.01 ? 0 : totalCashFlowDebt / newDebt,
21095
+ cashFlowDeposits / deposits,
21096
+ (cashFlowDeposits - totalCashFlowDebt) / (deposits - newDebt)
21097
+ ];
21098
+ }
21099
+ function getOrganicYieldCollateralSwap(amountInUSD, amountOutUSD, cashFlowDeposits, cashFlowDebt, deposits, debt, yieldIn, yieldOut) {
21100
+ const _flowIn = amountInUSD * yieldIn.depositRate;
21101
+ const _flowOut = amountOutUSD * yieldOut.depositRate;
21102
+ const totalCashFlowDeposits = cashFlowDeposits + _flowOut - _flowIn;
21103
+ const newCollat = deposits + amountOutUSD - amountInUSD;
21104
+ return [
21105
+ Math.abs(debt) < 0.01 ? 0 : cashFlowDebt / debt,
21106
+ totalCashFlowDeposits / newCollat,
21107
+ (totalCashFlowDeposits - cashFlowDebt) / (newCollat - debt)
21108
+ ];
21109
+ }
21110
+
21111
+ // src/lending/margin/loop/yield/getRewardYieldChange.ts
21112
+ function getRewardYieldOpen(amountInUSD, amountOutUSD, irModeIn, cashFlowDeposits, cashFlowDebt, deposits, debt, yieldIn, yieldOut) {
21113
+ const rewardsIn = yieldIn?.rewards;
21114
+ const rewardsOut = yieldOut?.rewards;
21115
+ if (!rewardsIn || !rewardsOut) return {};
21116
+ const data = {};
21117
+ for (const key of keysFromMaps(rewardsIn, rewardsOut)) {
21118
+ const _flowIn = amountInUSD * ((irModeIn === 1 ? rewardsIn[key]?.stableBorrowRate : rewardsIn[key]?.variableBorrowRate) ?? 0);
21119
+ const _flowOut = amountOutUSD * (rewardsOut[key]?.depositRate ?? 0);
21120
+ const totalCashFlowDebt = cashFlowDebt + _flowIn;
21121
+ const totalCashFlowDeposits = cashFlowDeposits + _flowOut;
21122
+ const newCollat = deposits + amountOutUSD;
21123
+ const newDebt = debt + amountInUSD;
21124
+ data[key] = {
21125
+ borrowApr: totalCashFlowDebt / newDebt,
21126
+ depositApr: totalCashFlowDeposits / newCollat,
21127
+ apr: (cashFlowDeposits + cashFlowDebt + _flowIn + _flowOut) / (newCollat - newDebt)
21128
+ };
21129
+ }
21130
+ return data;
21131
+ }
21132
+ function getRewardYieldClose(amountInUSD, amountOutUSD, irModeOut, cashFlowDeposits, cashFlowDebt, deposits, debt, yieldIn, yieldOut) {
21133
+ const rewardsIn = yieldIn?.rewards;
21134
+ const rewardsOut = yieldOut?.rewards;
21135
+ if (!rewardsIn || !rewardsOut) return {};
21136
+ const data = {};
21137
+ for (const key of keysFromMaps(rewardsIn, rewardsOut)) {
21138
+ const _flowIn = amountInUSD * (rewardsIn[key]?.depositRate ?? 0);
21139
+ const _flowOut = amountOutUSD * ((irModeOut === 1 ? rewardsOut[key]?.stableBorrowRate : rewardsOut[key]?.variableBorrowRate) ?? 0);
21140
+ const totalCashFlowDebt = cashFlowDebt - _flowOut;
21141
+ const totalCashFlowDeposits = cashFlowDeposits - _flowIn;
21142
+ const newCollat = deposits - amountInUSD;
21143
+ const newDebt = debt - amountOutUSD;
21144
+ data[key] = {
21145
+ borrowApr: Math.abs(newDebt) < 0.01 ? 0 : totalCashFlowDebt / newDebt,
21146
+ depositApr: totalCashFlowDeposits / newCollat,
21147
+ apr: (cashFlowDeposits + cashFlowDebt - _flowIn - _flowOut) / (newCollat - newDebt)
21148
+ };
21149
+ }
21150
+ return data;
21151
+ }
21152
+ function getRewardYieldDebtSwap(amountInUSD, amountOutUSD, irModeIn, irModeOut, cashFlowDeposits, cashFlowDebt, deposits, debt, yieldIn, yieldOut) {
21153
+ const rewardsIn = yieldIn?.rewards;
21154
+ const rewardsOut = yieldOut?.rewards;
21155
+ if (!rewardsIn || !rewardsOut) return {};
21156
+ const data = {};
21157
+ for (const key of keysFromMaps(rewardsIn, rewardsOut)) {
21158
+ const _flowIn = amountInUSD * ((irModeIn === 1 ? rewardsIn[key]?.stableBorrowRate : rewardsIn[key]?.variableBorrowRate) ?? 0);
21159
+ const _flowOut = amountOutUSD * ((irModeOut === 1 ? rewardsOut[key]?.stableBorrowRate : rewardsOut[key]?.variableBorrowRate) ?? 0);
21160
+ const totalCashFlowDebt = cashFlowDebt + _flowIn - _flowOut;
21161
+ const newDebt = debt - amountOutUSD + amountInUSD;
21162
+ data[key] = {
21163
+ borrowApr: Math.abs(newDebt) < 0.01 ? 0 : totalCashFlowDebt / newDebt,
21164
+ depositApr: cashFlowDeposits / deposits,
21165
+ apr: (cashFlowDeposits + totalCashFlowDebt) / (deposits - newDebt)
21166
+ };
21167
+ }
21168
+ return data;
21169
+ }
21170
+ function getRewardYieldCollateralSwap(amountInUSD, amountOutUSD, cashFlowDeposits, cashFlowDebt, deposits, debt, yieldIn, yieldOut) {
21171
+ const rewardsIn = yieldIn?.rewards;
21172
+ const rewardsOut = yieldOut?.rewards;
21173
+ if (!rewardsIn || !rewardsOut) return {};
21174
+ const data = {};
21175
+ for (const key of keysFromMaps(rewardsIn, rewardsOut)) {
21176
+ const _flowIn = amountInUSD * (rewardsIn[key]?.depositRate ?? 0);
21177
+ const _flowOut = amountOutUSD * (rewardsOut[key]?.depositRate ?? 0);
21178
+ const totalCashFlowDeposits = cashFlowDeposits + _flowOut - _flowIn;
21179
+ const newCollat = deposits + amountOutUSD - amountInUSD;
21180
+ data[key] = {
21181
+ borrowApr: Math.abs(debt) < 0.01 ? 0 : cashFlowDebt / debt,
21182
+ depositApr: totalCashFlowDeposits / newCollat,
21183
+ apr: (totalCashFlowDeposits + cashFlowDebt) / (newCollat - debt)
21184
+ };
21185
+ }
21186
+ return data;
21187
+ }
21188
+
21189
+ // src/lending/margin/loop/yield/getIntrinsicYieldChange.ts
21190
+ function getIntrinsicYieldOpen(amountInUSD, amountOutUSD, cashFlowDeposits, cashFlowDebt, deposits, debt, yieldIn, yieldOut) {
21191
+ const _flowIn = amountInUSD * yieldIn.intrinsicYield;
21192
+ const _flowOut = amountOutUSD * yieldOut.intrinsicYield;
21193
+ const totalCashFlowDebt = cashFlowDebt + _flowIn;
21194
+ const totalCashFlowDeposits = cashFlowDeposits + _flowOut;
21195
+ const newCollat = deposits + amountOutUSD;
21196
+ const newDebt = debt + amountInUSD;
21197
+ return [
21198
+ totalCashFlowDebt / newDebt,
21199
+ totalCashFlowDeposits / newCollat,
21200
+ (totalCashFlowDeposits - totalCashFlowDebt) / (newCollat - newDebt)
21201
+ ];
21202
+ }
21203
+ function getIntrinsicYieldClose(amountInUSD, amountOutUSD, cashFlowDeposits, cashFlowDebt, deposits, debt, yieldIn, yieldOut) {
21204
+ const _flowIn = amountInUSD * yieldIn.intrinsicYield;
21205
+ const _flowOut = amountOutUSD * yieldOut.intrinsicYield;
21206
+ const totalCashFlowDebt = cashFlowDebt - _flowOut;
21207
+ const totalCashFlowDeposits = cashFlowDeposits - _flowIn;
21208
+ const newCollat = deposits - amountInUSD;
21209
+ const newDebt = debt - amountOutUSD;
21210
+ return [
21211
+ Math.abs(newDebt) < 0.01 ? 0 : totalCashFlowDebt / newDebt,
21212
+ totalCashFlowDeposits / newCollat,
21213
+ (totalCashFlowDeposits - totalCashFlowDebt) / (newCollat - newDebt)
21214
+ ];
21215
+ }
21216
+ function getIntrinsicYieldDebtSwap(amountInUSD, amountOutUSD, cashFlowDeposits, cashFlowDebt, deposits, debt, yieldIn, yieldOut) {
21217
+ const _flowIn = amountInUSD * yieldIn.intrinsicYield;
21218
+ const _flowOut = amountOutUSD * yieldOut.intrinsicYield;
21219
+ const totalCashFlowDebt = cashFlowDebt + _flowIn - _flowOut;
21220
+ const newDebt = debt - amountOutUSD + amountInUSD;
21221
+ return [
21222
+ Math.abs(newDebt) < 0.01 ? 0 : totalCashFlowDebt / newDebt,
21223
+ cashFlowDeposits / deposits,
21224
+ (cashFlowDeposits - totalCashFlowDebt) / (deposits - newDebt)
21225
+ ];
21226
+ }
21227
+ function getIntrinsicYieldCollateralSwap(amountInUSD, amountOutUSD, cashFlowDeposits, cashFlowDebt, deposits, debt, yieldIn, yieldOut) {
21228
+ const _flowIn = amountInUSD * yieldIn.intrinsicYield;
21229
+ const _flowOut = amountOutUSD * yieldOut.intrinsicYield;
21230
+ const totalCashFlowDeposits = cashFlowDeposits + _flowOut - _flowIn;
21231
+ const newCollat = deposits + amountOutUSD - amountInUSD;
21232
+ return [
21233
+ Math.abs(debt) < 0.01 ? 0 : cashFlowDebt / debt,
21234
+ totalCashFlowDeposits / newCollat,
21235
+ (totalCashFlowDeposits - cashFlowDebt) / (newCollat - debt)
21236
+ ];
21237
+ }
21238
+
21239
+ // src/lending/margin/loop/compute/computeCloseDeltas.ts
21240
+ function computeCloseTradeDeltas(dollarIn, dollarOut, targetMode, yieldParamsIn, yieldParamsOut, balance, apr, bfOut, ltvIn, collateralLtvIn) {
21241
+ if (dollarIn === 0 || dollarOut === 0) return noOpResult(balance, apr);
21242
+ const cashFlowDeposits = balance.deposits * apr.depositApr;
21243
+ const cashFlowDebt = balance.debt * apr.borrowApr;
21244
+ const rewardFlowDeposits = balance.deposits * (apr.rewardDepositApr ?? 0);
21245
+ const rewardFlowDebt = balance.debt * (apr.rewardBorrowApr ?? 0);
21246
+ const intrinsicFlowDeposits = balance.deposits * apr.intrinsicDepositApr;
21247
+ const intrinsicFlowDebt = balance.debt * apr.intrinsicBorrowApr;
21248
+ const newBalance = { ...balance };
21249
+ const newApr = { ...apr };
21250
+ newBalance.debt = positivePart2(newBalance.debt - dollarOut);
21251
+ newBalance.borrowDiscountedCollateral = positivePart2(
21252
+ newBalance.borrowDiscountedCollateral - ltvIn * dollarIn
21253
+ );
21254
+ newBalance.collateral = positivePart2(
21255
+ newBalance.collateral - collateralLtvIn * dollarIn
21256
+ );
21257
+ newBalance.deposits = positivePart2(newBalance.deposits - dollarIn);
21258
+ newBalance.adjustedDebt = positivePart2(
21259
+ newBalance.adjustedDebt - bfOut * dollarOut
21260
+ );
21261
+ newBalance.nav += dollarOut - dollarIn;
21262
+ [newApr.borrowApr, newApr.depositApr, newApr.apr] = getOrganicYieldClose(
21263
+ dollarIn,
21264
+ dollarOut,
21265
+ targetMode,
21266
+ cashFlowDeposits,
21267
+ cashFlowDebt,
21268
+ balance.deposits,
21269
+ balance.debt,
21270
+ yieldParamsIn,
21271
+ yieldParamsOut
21272
+ );
21273
+ newApr.rewards = getRewardYieldClose(
21274
+ dollarIn,
21275
+ dollarOut,
21276
+ targetMode,
21277
+ rewardFlowDeposits,
21278
+ rewardFlowDebt,
21279
+ balance.deposits,
21280
+ balance.debt,
21281
+ yieldParamsIn,
21282
+ yieldParamsOut
21283
+ );
21284
+ [newApr.intrinsicBorrowApr, newApr.intrinsicDepositApr, newApr.intrinsicApr] = getIntrinsicYieldClose(
21285
+ dollarIn,
21286
+ dollarOut,
21287
+ intrinsicFlowDeposits,
21288
+ intrinsicFlowDebt,
21289
+ balance.deposits,
21290
+ balance.debt,
21291
+ yieldParamsIn,
21292
+ yieldParamsOut
21293
+ );
21294
+ return buildLoopResult(balance, newBalance, apr, newApr);
21295
+ }
21296
+
21297
+ // src/lending/margin/loop/compute/computeCollateralSwapDeltas.ts
21298
+ function computeCollateralSwapDeltas(dollarIn, dollarOut, yieldParamsIn, yieldParamsOut, balance, apr, ltvIn, collateralLtvIn, ltvOut, collateralLtvOut) {
21299
+ if (dollarIn === 0 || dollarOut === 0) return noOpResult(balance, apr);
21300
+ const cashFlowDeposits = balance.deposits * apr.depositApr;
21301
+ const cashFlowDebt = balance.debt * apr.borrowApr;
21302
+ const rewardFlowDeposits = balance.deposits * (apr.rewardDepositApr ?? 0);
21303
+ const rewardFlowDebt = balance.debt * (apr.rewardBorrowApr ?? 0);
21304
+ const intrinsicFlowDeposits = balance.deposits * apr.intrinsicDepositApr;
21305
+ const intrinsicFlowDebt = balance.debt * apr.intrinsicBorrowApr;
21306
+ const newBalance = { ...balance };
21307
+ const newApr = { ...apr };
21308
+ newBalance.borrowDiscountedCollateral += ltvOut * dollarOut - ltvIn * dollarIn;
21309
+ newBalance.deposits += dollarOut - dollarIn;
21310
+ newBalance.collateral += collateralLtvOut * dollarOut - collateralLtvIn * dollarIn;
21311
+ newBalance.nav += dollarOut - dollarIn;
21312
+ [newApr.borrowApr, newApr.depositApr, newApr.apr] = getOrganicYieldCollateralSwap(
21313
+ dollarIn,
21314
+ dollarOut,
21315
+ cashFlowDeposits,
21316
+ cashFlowDebt,
21317
+ balance.deposits,
21318
+ balance.debt,
21319
+ yieldParamsIn,
21320
+ yieldParamsOut
21321
+ );
21322
+ newApr.rewards = getRewardYieldCollateralSwap(
21323
+ dollarIn,
21324
+ dollarOut,
21325
+ rewardFlowDeposits,
21326
+ rewardFlowDebt,
21327
+ balance.deposits,
21328
+ balance.debt,
21329
+ yieldParamsIn,
21330
+ yieldParamsOut
21331
+ );
21332
+ [newApr.intrinsicBorrowApr, newApr.intrinsicDepositApr, newApr.intrinsicApr] = getIntrinsicYieldCollateralSwap(
21333
+ dollarIn,
21334
+ dollarOut,
21335
+ intrinsicFlowDeposits,
21336
+ intrinsicFlowDebt,
21337
+ balance.deposits,
21338
+ balance.debt,
21339
+ yieldParamsIn,
21340
+ yieldParamsOut
21341
+ );
21342
+ return buildLoopResult(balance, newBalance, apr, newApr);
21343
+ }
21344
+
21345
+ // src/lending/margin/loop/compute/computeDebtSwapDeltas.ts
21346
+ function computeDebtSwapDeltas(dollarIn, dollarOut, sourceMode, targetMode, yieldParamsIn, yieldParamsOut, balance, apr, bfInFactor, bfOutFactor) {
21347
+ if (dollarIn === 0 || dollarOut === 0) return noOpResult(balance, apr);
21348
+ const cashFlowDeposits = balance.deposits * apr.depositApr;
21349
+ const cashFlowDebt = balance.debt * apr.borrowApr;
21350
+ const rewardFlowDeposits = balance.deposits * (apr.rewardDepositApr ?? 0);
21351
+ const rewardFlowDebt = balance.debt * apr.rewardBorrowApr;
21352
+ const intrinsicFlowDeposits = balance.deposits * apr.intrinsicDepositApr;
21353
+ const intrinsicFlowDebt = balance.debt * apr.intrinsicBorrowApr;
21354
+ const newBalance = { ...balance };
21355
+ const newApr = { ...apr };
21356
+ newBalance.debt += dollarOut - dollarIn;
21357
+ newBalance.adjustedDebt += bfOutFactor * dollarOut - bfInFactor * dollarIn;
21358
+ newBalance.nav += dollarOut - dollarIn;
21359
+ [newApr.borrowApr, newApr.depositApr, newApr.apr] = getOrganicYieldDebtSwap(
21360
+ dollarIn,
21361
+ dollarOut,
21362
+ sourceMode,
21363
+ targetMode,
21364
+ cashFlowDeposits,
21365
+ cashFlowDebt,
21366
+ balance.deposits,
21367
+ balance.debt,
21368
+ yieldParamsIn,
21369
+ yieldParamsOut
21370
+ );
21371
+ newApr.rewards = getRewardYieldDebtSwap(
21372
+ dollarIn,
21373
+ dollarOut,
21374
+ sourceMode,
21375
+ targetMode,
21376
+ rewardFlowDeposits,
21377
+ rewardFlowDebt,
21378
+ balance.deposits,
21379
+ balance.debt,
21380
+ yieldParamsIn,
21381
+ yieldParamsOut
21382
+ );
21383
+ [newApr.intrinsicBorrowApr, newApr.intrinsicDepositApr, newApr.intrinsicApr] = getIntrinsicYieldDebtSwap(
21384
+ dollarIn,
21385
+ dollarOut,
21386
+ intrinsicFlowDeposits,
21387
+ intrinsicFlowDebt,
21388
+ balance.deposits,
21389
+ balance.debt,
21390
+ yieldParamsIn,
21391
+ yieldParamsOut
21392
+ );
21393
+ return buildLoopResult(balance, newBalance, apr, newApr);
21394
+ }
21395
+
21396
+ // src/lending/margin/loop/compute/computeOpenDeltas.ts
21397
+ function computeOpenTradeDeltas(dollarIn, dollarOut, sourceMode, yieldParamsIn, yieldParamsOut, balance, apr, bfIn, collateralLtvOut, borrowLtvOut, useAllActive = false) {
21398
+ if (dollarIn === 0 || dollarOut === 0) return noOpResult(balance, apr);
21399
+ const cashFlowDeposits = balance.deposits * apr.depositApr;
21400
+ const cashFlowDebt = balance.debt * apr.borrowApr;
21401
+ const rewardFlowDeposits = balance.deposits * (apr.rewardDepositApr ?? 0);
21402
+ const rewardFlowDebt = balance.debt * (apr.rewardBorrowApr ?? 0);
21403
+ const intrinsicFlowDeposits = balance.deposits * apr.intrinsicDepositApr;
21404
+ const intrinsicFlowDebt = balance.debt * apr.intrinsicBorrowApr;
21405
+ const newBalance = { ...balance };
21406
+ const newApr = { ...apr };
21407
+ newBalance.debt += dollarIn;
21408
+ newBalance.borrowDiscountedCollateral += borrowLtvOut * dollarOut;
21409
+ newBalance.borrowDiscountedCollateralAllActive += borrowLtvOut * dollarOut;
21410
+ newBalance.collateral += collateralLtvOut * dollarOut;
21411
+ newBalance.collateralAllActive += collateralLtvOut * dollarOut;
21412
+ newBalance.deposits += dollarOut;
21413
+ newBalance.adjustedDebt += bfIn * dollarIn;
21414
+ newBalance.nav += dollarOut - dollarIn;
21415
+ [newApr.borrowApr, newApr.depositApr, newApr.apr] = getOrganicYieldOpen(
21416
+ dollarIn,
21417
+ dollarOut,
21418
+ sourceMode,
21419
+ cashFlowDeposits,
21420
+ cashFlowDebt,
21421
+ balance.deposits,
21422
+ balance.debt,
21423
+ yieldParamsIn,
21424
+ yieldParamsOut
21425
+ );
21426
+ newApr.rewards = getRewardYieldOpen(
21427
+ dollarIn,
21428
+ dollarOut,
21429
+ sourceMode,
21430
+ rewardFlowDeposits,
21431
+ rewardFlowDebt,
21432
+ balance.deposits,
21433
+ balance.debt,
21434
+ yieldParamsIn,
21435
+ yieldParamsOut
21436
+ );
21437
+ [newApr.intrinsicBorrowApr, newApr.intrinsicDepositApr, newApr.intrinsicApr] = getIntrinsicYieldOpen(
21438
+ dollarIn,
21439
+ dollarOut,
21440
+ intrinsicFlowDeposits,
21441
+ intrinsicFlowDebt,
21442
+ balance.deposits,
21443
+ balance.debt,
21444
+ yieldParamsIn,
21445
+ yieldParamsOut
21446
+ );
21447
+ return buildLoopResult(balance, newBalance, apr, newApr, useAllActive);
21448
+ }
21449
+
21450
+ // src/lending/margin/loop/compute/computeZapDeltas.ts
21451
+ function computeZapTradeDeltas(dollarIn, dollarOut, sourceMode, yieldParamsIn, yieldParamsOut, balance, apr, bfIn, collateralLtvOut, borrowLtvOut) {
21452
+ if (dollarIn === 0 || dollarOut === 0) return noOpResult(balance, apr);
21453
+ const cashFlowDeposits = balance.deposits * apr.depositApr;
21454
+ const cashFlowDebt = balance.debt * apr.borrowApr;
21455
+ const rewardFlowDeposits = balance.deposits * (apr.rewardDepositApr ?? 0);
21456
+ const rewardFlowDebt = balance.debt * (apr.rewardBorrowApr ?? 0);
21457
+ const intrinsicFlowDeposits = balance.deposits * apr.intrinsicDepositApr;
21458
+ const intrinsicFlowDebt = balance.debt * apr.intrinsicBorrowApr;
21459
+ const newBalance = { ...balance };
21460
+ const newApr = { ...apr };
21461
+ newBalance.debt += dollarIn;
21462
+ newBalance.borrowDiscountedCollateral += borrowLtvOut * dollarOut;
21463
+ newBalance.collateral += collateralLtvOut * dollarOut;
21464
+ newBalance.deposits += dollarOut;
21465
+ newBalance.adjustedDebt += bfIn * dollarIn;
21466
+ newBalance.nav += dollarOut - dollarIn;
21467
+ [newApr.borrowApr, newApr.depositApr, newApr.apr] = getOrganicYieldOpen(
21468
+ dollarIn,
21469
+ dollarOut,
21470
+ sourceMode,
21471
+ cashFlowDeposits,
21472
+ cashFlowDebt,
21473
+ balance.deposits,
21474
+ balance.debt,
21475
+ yieldParamsIn,
21476
+ yieldParamsOut
21477
+ );
21478
+ newApr.rewards = getRewardYieldOpen(
21479
+ dollarIn,
21480
+ dollarOut,
21481
+ sourceMode,
21482
+ rewardFlowDeposits,
21483
+ rewardFlowDebt,
21484
+ balance.deposits,
21485
+ balance.debt,
21486
+ yieldParamsIn,
21487
+ yieldParamsOut
21488
+ );
21489
+ [newApr.intrinsicBorrowApr, newApr.intrinsicDepositApr, newApr.intrinsicApr] = getIntrinsicYieldOpen(
21490
+ dollarIn,
21491
+ dollarOut,
21492
+ intrinsicFlowDeposits,
21493
+ intrinsicFlowDebt,
21494
+ balance.deposits,
21495
+ balance.debt,
21496
+ yieldParamsIn,
21497
+ yieldParamsOut
21498
+ );
21499
+ return buildLoopResult(balance, newBalance, apr, newApr);
21500
+ }
21501
+
20121
21502
  // src/assets/liquidityThresholds.ts
20122
21503
  var DEFAULT_LIQUIDITY_THRESHOLDS = {
20123
21504
  minDepositsUSD: 25e3,
@@ -20220,6 +21601,17 @@ var getMaxLeverage = (lender, longData, shortData) => {
20220
21601
  const bf = shortData.config[configId]?.borrowFactor;
20221
21602
  return 1 / (1 - cf2 / bf);
20222
21603
  }
21604
+ if (isSumerType(lender)) {
21605
+ const shortEntries = Object.entries(shortData?.config ?? {});
21606
+ if (shortEntries.length === 0) return 1;
21607
+ const shortGroupId = Number(
21608
+ shortEntries.sort(
21609
+ ([, a], [, b]) => b.borrowCollateralFactor - a.borrowCollateralFactor
21610
+ )[0][0]
21611
+ );
21612
+ const cf2 = longData?.config?.[shortGroupId]?.borrowCollateralFactor ?? 0;
21613
+ return cf2 > 0 && cf2 < 1 ? 1 / (1 - cf2) : 1;
21614
+ }
20223
21615
  const cf = longData?.config?.[LENDER_MODE_NO_MODE2]?.borrowCollateralFactor ?? 0.8;
20224
21616
  return 1 / (1 - cf);
20225
21617
  };
@@ -20267,8 +21659,8 @@ function generateLendingPairs(lenderData, prices, histPrices) {
20267
21659
  const borrowRate = baseYields.stableBorrowRate >= baseYields.variableBorrowRate ? baseYields.stableBorrowRate : baseYields.variableBorrowRate;
20268
21660
  borrowRewards += borrowRate;
20269
21661
  }
20270
- const depositApr = long.depositRate + long.stakingYield;
20271
- const borrowApr = short.variableBorrowRate + short.stakingYield;
21662
+ const depositApr = long.depositRate + long.intrinsicYield;
21663
+ const borrowApr = short.variableBorrowRate + short.intrinsicYield;
20272
21664
  const [assetGroupLong, keyLong] = getPriceKey2(long.asset);
20273
21665
  const [assetGroupShort, keyShort] = getPriceKey2(short.asset);
20274
21666
  const priceLong = prices[keyLong] ?? 0;
@@ -25137,6 +26529,283 @@ function attachPricesToFlashLiquidity(chainId, liq, prices, list = {}) {
25137
26529
  return liqCopy;
25138
26530
  }
25139
26531
 
26532
+ // src/lending/margin/sumer/deposit.ts
26533
+ function computeSumerDepositDelta(amount, price, targetMarketUid, balanceData2, positions, createNewSubAccount = false, apr, yieldParams) {
26534
+ const base = createNewSubAccount ? EMPTY_BALANCE : balanceData2;
26535
+ const dollarAmount = amount * price;
26536
+ const updatedPositions = applyPositionDelta(
26537
+ positions,
26538
+ targetMarketUid,
26539
+ dollarAmount,
26540
+ 0,
26541
+ 0
26542
+ );
26543
+ const { groupRatesMap, gAccum, gAccumAll } = buildSumerAccumulators(updatedPositions);
26544
+ const groups = Object.values(groupRatesMap);
26545
+ const waterfallCollateral = computeSumerWaterfall(groups, gAccum);
26546
+ const waterfallCollateralAll = computeSumerWaterfall(groups, gAccumAll);
26547
+ const postTrade = {
26548
+ ...base,
26549
+ borrowDiscountedCollateral: waterfallCollateral,
26550
+ borrowDiscountedCollateralAllActive: waterfallCollateralAll,
26551
+ collateral: waterfallCollateral,
26552
+ collateralAllActive: waterfallCollateralAll,
26553
+ deposits: base.deposits + dollarAmount,
26554
+ debt: base.debt,
26555
+ adjustedDebt: base.debt,
26556
+ nav: base.deposits + dollarAmount - base.debt
26557
+ };
26558
+ const result = computePostTradeMetrics(base, postTrade);
26559
+ if (apr && yieldParams) {
26560
+ const cashFlowDeposits = base.deposits * apr.depositApr;
26561
+ const cashFlowDebt = base.debt * apr.borrowApr;
26562
+ const rewardFlowDeposits = base.deposits * (apr.rewardDepositApr ?? 0);
26563
+ const rewardFlowDebt = base.debt * (apr.rewardBorrowApr ?? 0);
26564
+ const intrinsicFlowDeposits = base.deposits * apr.intrinsicDepositApr;
26565
+ const intrinsicFlowDebt = base.debt * apr.intrinsicBorrowApr;
26566
+ const newApr = { ...apr };
26567
+ [newApr.borrowApr, newApr.depositApr, newApr.apr] = getOrganicYieldDeposit(
26568
+ dollarAmount,
26569
+ cashFlowDeposits,
26570
+ cashFlowDebt,
26571
+ base.deposits,
26572
+ base.debt,
26573
+ yieldParams
26574
+ );
26575
+ newApr.rewards = getRewardYieldDeposit(
26576
+ dollarAmount,
26577
+ rewardFlowDeposits,
26578
+ rewardFlowDebt,
26579
+ base.deposits,
26580
+ base.debt,
26581
+ yieldParams
26582
+ );
26583
+ [
26584
+ newApr.intrinsicBorrowApr,
26585
+ newApr.intrinsicDepositApr,
26586
+ newApr.intrinsicApr
26587
+ ] = getIntrinsicYieldDeposit(
26588
+ dollarAmount,
26589
+ intrinsicFlowDeposits,
26590
+ intrinsicFlowDebt,
26591
+ base.deposits,
26592
+ base.debt,
26593
+ yieldParams
26594
+ );
26595
+ result.aprDataPost = newApr;
26596
+ }
26597
+ return result;
26598
+ }
26599
+
26600
+ // src/lending/margin/sumer/withdraw.ts
26601
+ function computeSumerWithdrawDelta(amount, price, targetMarketUid, balanceData2, positions, apr, yieldParams) {
26602
+ const dollarAmount = amount * price;
26603
+ const updatedPositions = applyPositionDelta(
26604
+ positions,
26605
+ targetMarketUid,
26606
+ -dollarAmount,
26607
+ 0,
26608
+ 0
26609
+ );
26610
+ const { groupRatesMap, gAccum, gAccumAll } = buildSumerAccumulators(updatedPositions);
26611
+ const groups = Object.values(groupRatesMap);
26612
+ const waterfallCollateral = computeSumerWaterfall(groups, gAccum);
26613
+ const waterfallCollateralAll = computeSumerWaterfall(groups, gAccumAll);
26614
+ const postTrade = {
26615
+ ...balanceData2,
26616
+ borrowDiscountedCollateral: waterfallCollateral,
26617
+ borrowDiscountedCollateralAllActive: waterfallCollateralAll,
26618
+ collateral: waterfallCollateral,
26619
+ collateralAllActive: waterfallCollateralAll,
26620
+ deposits: balanceData2.deposits - dollarAmount,
26621
+ debt: balanceData2.debt,
26622
+ adjustedDebt: balanceData2.debt,
26623
+ nav: balanceData2.deposits - dollarAmount - balanceData2.debt
26624
+ };
26625
+ const result = computePostTradeMetrics(balanceData2, postTrade);
26626
+ if (apr && yieldParams) {
26627
+ const cashFlowDeposits = balanceData2.deposits * apr.depositApr;
26628
+ const cashFlowDebt = balanceData2.debt * apr.borrowApr;
26629
+ const rewardFlowDeposits = balanceData2.deposits * (apr.rewardDepositApr ?? 0);
26630
+ const rewardFlowDebt = balanceData2.debt * (apr.rewardBorrowApr ?? 0);
26631
+ const intrinsicFlowDeposits = balanceData2.deposits * apr.intrinsicDepositApr;
26632
+ const intrinsicFlowDebt = balanceData2.debt * apr.intrinsicBorrowApr;
26633
+ const newApr = { ...apr };
26634
+ [newApr.borrowApr, newApr.depositApr, newApr.apr] = getOrganicYieldWithdraw(
26635
+ dollarAmount,
26636
+ cashFlowDeposits,
26637
+ cashFlowDebt,
26638
+ balanceData2.deposits,
26639
+ balanceData2.debt,
26640
+ yieldParams
26641
+ );
26642
+ newApr.rewards = getRewardYieldWithdraw(
26643
+ dollarAmount,
26644
+ rewardFlowDeposits,
26645
+ rewardFlowDebt,
26646
+ balanceData2.deposits,
26647
+ balanceData2.debt,
26648
+ yieldParams
26649
+ );
26650
+ [
26651
+ newApr.intrinsicBorrowApr,
26652
+ newApr.intrinsicDepositApr,
26653
+ newApr.intrinsicApr
26654
+ ] = getIntrinsicYieldWithdraw(
26655
+ dollarAmount,
26656
+ intrinsicFlowDeposits,
26657
+ intrinsicFlowDebt,
26658
+ balanceData2.deposits,
26659
+ balanceData2.debt,
26660
+ yieldParams
26661
+ );
26662
+ result.aprDataPost = newApr;
26663
+ }
26664
+ return result;
26665
+ }
26666
+
26667
+ // src/lending/margin/sumer/borrow.ts
26668
+ function computeSumerBorrowDelta(amount, price, targetMarketUid, balanceData2, positions, apr, yieldParams, irMode) {
26669
+ const dollarAmount = amount * price;
26670
+ const mode = irMode ?? 2;
26671
+ const updatedPositions = applyPositionDelta(
26672
+ positions,
26673
+ targetMarketUid,
26674
+ 0,
26675
+ mode === 1 ? 0 : dollarAmount,
26676
+ mode === 1 ? dollarAmount : 0
26677
+ );
26678
+ const { groupRatesMap, gAccum, gAccumAll } = buildSumerAccumulators(updatedPositions);
26679
+ const groups = Object.values(groupRatesMap);
26680
+ const waterfallCollateral = computeSumerWaterfall(groups, gAccum);
26681
+ const waterfallCollateralAll = computeSumerWaterfall(groups, gAccumAll);
26682
+ const newDebt = balanceData2.debt + dollarAmount;
26683
+ const postTrade = {
26684
+ ...balanceData2,
26685
+ borrowDiscountedCollateral: waterfallCollateral,
26686
+ borrowDiscountedCollateralAllActive: waterfallCollateralAll,
26687
+ collateral: waterfallCollateral,
26688
+ collateralAllActive: waterfallCollateralAll,
26689
+ deposits: balanceData2.deposits,
26690
+ debt: newDebt,
26691
+ adjustedDebt: newDebt,
26692
+ nav: balanceData2.nav - dollarAmount
26693
+ };
26694
+ const result = computePostTradeMetrics(balanceData2, postTrade);
26695
+ if (apr && yieldParams) {
26696
+ const cashFlowDeposits = balanceData2.deposits * apr.depositApr;
26697
+ const cashFlowDebt = balanceData2.debt * apr.borrowApr;
26698
+ const rewardFlowDeposits = balanceData2.deposits * (apr.rewardDepositApr ?? 0);
26699
+ const rewardFlowDebt = balanceData2.debt * (apr.rewardBorrowApr ?? 0);
26700
+ const intrinsicFlowDeposits = balanceData2.deposits * apr.intrinsicDepositApr;
26701
+ const intrinsicFlowDebt = balanceData2.debt * apr.intrinsicBorrowApr;
26702
+ const newApr = { ...apr };
26703
+ [newApr.borrowApr, newApr.depositApr, newApr.apr] = getOrganicYieldBorrow(
26704
+ dollarAmount,
26705
+ mode,
26706
+ cashFlowDeposits,
26707
+ cashFlowDebt,
26708
+ balanceData2.deposits,
26709
+ balanceData2.debt,
26710
+ yieldParams
26711
+ );
26712
+ newApr.rewards = getRewardYieldBorrow(
26713
+ dollarAmount,
26714
+ mode,
26715
+ rewardFlowDeposits,
26716
+ rewardFlowDebt,
26717
+ balanceData2.deposits,
26718
+ balanceData2.debt,
26719
+ yieldParams
26720
+ );
26721
+ [
26722
+ newApr.intrinsicBorrowApr,
26723
+ newApr.intrinsicDepositApr,
26724
+ newApr.intrinsicApr
26725
+ ] = getIntrinsicYieldBorrow(
26726
+ dollarAmount,
26727
+ intrinsicFlowDeposits,
26728
+ intrinsicFlowDebt,
26729
+ balanceData2.deposits,
26730
+ balanceData2.debt,
26731
+ yieldParams
26732
+ );
26733
+ result.aprDataPost = newApr;
26734
+ }
26735
+ return result;
26736
+ }
26737
+
26738
+ // src/lending/margin/sumer/repay.ts
26739
+ function computeSumerRepayDelta(amount, price, targetMarketUid, balanceData2, positions, apr, yieldParams, irMode) {
26740
+ const dollarAmount = amount * price;
26741
+ const mode = irMode ?? 2;
26742
+ const updatedPositions = applyPositionDelta(
26743
+ positions,
26744
+ targetMarketUid,
26745
+ 0,
26746
+ mode === 1 ? 0 : -dollarAmount,
26747
+ mode === 1 ? -dollarAmount : 0
26748
+ );
26749
+ const { groupRatesMap, gAccum, gAccumAll } = buildSumerAccumulators(updatedPositions);
26750
+ const groups = Object.values(groupRatesMap);
26751
+ const waterfallCollateral = computeSumerWaterfall(groups, gAccum);
26752
+ const waterfallCollateralAll = computeSumerWaterfall(groups, gAccumAll);
26753
+ const newDebt = balanceData2.debt - dollarAmount;
26754
+ const postTrade = {
26755
+ ...balanceData2,
26756
+ borrowDiscountedCollateral: waterfallCollateral,
26757
+ borrowDiscountedCollateralAllActive: waterfallCollateralAll,
26758
+ collateral: waterfallCollateral,
26759
+ collateralAllActive: waterfallCollateralAll,
26760
+ deposits: balanceData2.deposits,
26761
+ debt: newDebt,
26762
+ adjustedDebt: Math.max(0, newDebt),
26763
+ nav: balanceData2.nav + dollarAmount
26764
+ };
26765
+ const result = computePostTradeMetrics(balanceData2, postTrade);
26766
+ if (apr && yieldParams) {
26767
+ const cashFlowDeposits = balanceData2.deposits * apr.depositApr;
26768
+ const cashFlowDebt = balanceData2.debt * apr.borrowApr;
26769
+ const rewardFlowDeposits = balanceData2.deposits * (apr.rewardDepositApr ?? 0);
26770
+ const rewardFlowDebt = balanceData2.debt * (apr.rewardBorrowApr ?? 0);
26771
+ const intrinsicFlowDeposits = balanceData2.deposits * apr.intrinsicDepositApr;
26772
+ const intrinsicFlowDebt = balanceData2.debt * apr.intrinsicBorrowApr;
26773
+ const newApr = { ...apr };
26774
+ [newApr.borrowApr, newApr.depositApr, newApr.apr] = getOrganicYieldRepay(
26775
+ dollarAmount,
26776
+ mode,
26777
+ cashFlowDeposits,
26778
+ cashFlowDebt,
26779
+ balanceData2.deposits,
26780
+ balanceData2.debt,
26781
+ yieldParams
26782
+ );
26783
+ newApr.rewards = getRewardYieldRepay(
26784
+ dollarAmount,
26785
+ mode,
26786
+ rewardFlowDeposits,
26787
+ rewardFlowDebt,
26788
+ balanceData2.deposits,
26789
+ balanceData2.debt,
26790
+ yieldParams
26791
+ );
26792
+ [
26793
+ newApr.intrinsicBorrowApr,
26794
+ newApr.intrinsicDepositApr,
26795
+ newApr.intrinsicApr
26796
+ ] = getIntrinsicYieldRepay(
26797
+ dollarAmount,
26798
+ intrinsicFlowDeposits,
26799
+ intrinsicFlowDebt,
26800
+ balanceData2.deposits,
26801
+ balanceData2.debt,
26802
+ yieldParams
26803
+ );
26804
+ result.aprDataPost = newApr;
26805
+ }
26806
+ return result;
26807
+ }
26808
+
25140
26809
  // src/utils/rpcParse.ts
25141
26810
  function parseRawRpcResponses(responses, callMetadata, allowFailure = true) {
25142
26811
  const sortedResponses = [...responses].sort((a, b) => a.id - b.id);
@@ -25447,31 +27116,56 @@ function parseTokenBalanceResult(rawResult, query2) {
25447
27116
  }
25448
27117
  return result;
25449
27118
  }
27119
+ async function rpcFetchWithRetry(rpcUrls, body, maxRetries2) {
27120
+ let lastError;
27121
+ for (let attempt = 0; attempt <= maxRetries2; attempt++) {
27122
+ const url = rpcUrls[attempt % rpcUrls.length];
27123
+ try {
27124
+ const res = await fetch(url, {
27125
+ method: "POST",
27126
+ headers: { "Content-Type": "application/json" },
27127
+ body
27128
+ });
27129
+ if (!res.ok) {
27130
+ lastError = new Error(`RPC ${res.status} ${res.statusText}`);
27131
+ continue;
27132
+ }
27133
+ const json = await res.json();
27134
+ if (json.error) {
27135
+ lastError = new Error(`RPC error: ${JSON.stringify(json.error)}`);
27136
+ continue;
27137
+ }
27138
+ return json.result ?? "0x";
27139
+ } catch (e) {
27140
+ lastError = e instanceof Error ? e : new Error(String(e));
27141
+ }
27142
+ }
27143
+ throw lastError ?? new Error("All RPC attempts failed");
27144
+ }
25450
27145
  async function fetchTokenBalances(chainId, account, tokens, options = {}) {
25451
- const { blockTag = "latest", rpcUrl } = options;
27146
+ const { blockTag = "latest", rpcUrl, rpcUrls, maxRetries: maxRetries2 = 3 } = options;
25452
27147
  const prepared = prepareTokenBalanceRpcCalls(chainId, account, tokens, blockTag);
25453
- const chain = getEvmChain(chainId);
25454
- const url = rpcUrl || chain.rpcUrls?.default?.http?.[0];
25455
- if (!url) {
25456
- throw new Error(`No RPC URL available for chain ${chainId}`);
25457
- }
25458
- const response = await fetch(url, {
25459
- method: "POST",
25460
- headers: {
25461
- "Content-Type": "application/json"
25462
- },
25463
- body: JSON.stringify(prepared.call)
25464
- });
25465
- if (!response.ok) {
25466
- throw new Error(`RPC request failed: ${response.status} ${response.statusText}`);
25467
- }
25468
- const result = await response.json();
25469
- if (result.error) {
25470
- throw new Error(`RPC error: ${JSON.stringify(result.error)}`);
27148
+ let urls;
27149
+ if (rpcUrls?.length) {
27150
+ urls = rpcUrls;
27151
+ } else if (rpcUrl) {
27152
+ urls = [rpcUrl];
27153
+ } else {
27154
+ const chain = getEvmChain(chainId);
27155
+ const defaultUrl = chain.rpcUrls?.default?.http?.[0];
27156
+ if (!defaultUrl) {
27157
+ throw new Error(`No RPC URL available for chain ${chainId}`);
27158
+ }
27159
+ urls = [defaultUrl];
25471
27160
  }
25472
- return parseTokenBalanceResult(result.result || "0x", prepared.query);
27161
+ const rawResult = await rpcFetchWithRetry(
27162
+ urls,
27163
+ JSON.stringify(prepared.call),
27164
+ maxRetries2
27165
+ );
27166
+ return parseTokenBalanceResult(rawResult, prepared.query);
25473
27167
  }
25474
27168
 
25475
- export { MORPHO_LENS, MorphoLensAbi, attachPricesToFlashLiquidity, buildMorphoTypeCall, buildMorphoTypeUserCallWithLens, buildPortfolioTotals, buildSummaries, calculateLeverage, calculateNetApr, calculateOverallNetApr, calculateWeightedAverage, convertLenderUserDataResult, createMarketUid, createMulticallRpcCall, createRawRpcCalls, decodeListaMarkets, decodeMarkets, decodePackedListaUserDataset, decodePackedMorphoUserDataset, encodeBalanceFetcherCalldata, fetchDefillamaData, fetchDefillamaHistData, fetchFlashLiquidityForChain, fetchGeneralYields, fetchMainPrices, fetchOraclePrices, fetchPendlePrices, fetchTokenBalances, fetchTokenMetadata, filterActiveLenders, filterLendersByProtocol, flattenToUSDPriceMap, fuseLenderData, generateLendingPairs, generateLendingPools, getAavesForChain, getLenderAssets, getLenderPublicData, getLenderPublicDataAll, getLenderPublicDataViaApi, getLenderUserDataMulti, getLenderUserDataResult, getLendersForChain, getMorphoTypeMarketConverter, getTopPairs, isAaveType, isAaveV2Type, isAaveV32Type, isAaveV3Type, isCompoundV3, isCompoundV3Type, isInit, isMorphoType, isMultiMarket, isYLDR, multicall3Abi, normalizeToBytes, parseBalanceFetcherResult, parseMulticallRpcResponses, parseRawRpcBatchResponses, parseRawRpcResponses, parseTokenBalanceResult, prepareLenderUserDataRpcCalls, prepareMulticallInputs, prepareTokenBalanceRpcCalls, unflattenLenderData };
27169
+ export { EMPTY_BALANCE, MORPHO_LENS, applyPositionDelta, attachPricesToFlashLiquidity, buildLoopResult, buildMorphoTypeCall, buildMorphoTypeUserCallWithLens, buildPortfolioTotals, buildSumerAccumulators, buildSummaries, calculateLeverage, calculateNetApr, calculateOverallNetApr, calculateWeightedAverage, computeBorrowDelta, computeCloseTradeDeltas, computeCollateralSwapDeltas, computeDebtSwapDeltas, computeDepositDelta, computeOpenTradeDeltas, computePostTradeMetrics, computeRepayDelta, computeSumerBorrowDelta, computeSumerDepositDelta, computeSumerRepayDelta, computeSumerWaterfall, computeSumerWithdrawDelta, computeWithdrawDelta, computeZapTradeDeltas, convertLenderUserDataResult, createMarketUid, createMulticallRpcCall, createRawRpcCalls, decodeListaMarkets, decodeMarkets, decodePackedListaUserDataset, decodePackedMorphoUserDataset, encodeBalanceFetcherCalldata, fetchDefillamaData, fetchDefillamaHistData, fetchFlashLiquidityForChain, fetchGeneralYields, fetchMainPrices, fetchOraclePrices, fetchPendlePrices, fetchTokenBalances, fetchTokenMetadata, filterActiveLenders, filterLendersByProtocol, flattenToUSDPriceMap, fuseLenderData, generateLendingPairs, generateLendingPools, getAavesForChain, getAssetConfig, getBorrowCapacity, getHealthFactor, getLenderAssets, getLenderPublicData, getLenderPublicDataAll, getLenderPublicDataViaApi, getLenderUserDataMulti, getLenderUserDataResult, getLendersForChain, getMorphoTypeMarketConverter, getTopPairs, isAaveType, isAaveV2Type, isAaveV32Type, isAaveV3Type, isCompoundV3, isCompoundV3Type, isInit, isMorphoType, isMultiMarket, isYLDR, keysFromMaps, multicall3Abi, nanTo, noOpResult, normalizeToBytes, parseBalanceFetcherResult, parseMulticallRpcResponses, parseRawRpcBatchResponses, parseRawRpcResponses, parseTokenBalanceResult, positivePart2 as positivePart, prepareLenderUserDataRpcCalls, prepareMulticallInputs, prepareTokenBalanceRpcCalls, unflattenLenderData };
25476
27170
  //# sourceMappingURL=index.js.map
25477
27171
  //# sourceMappingURL=index.js.map