@carrot-protocol/clend-rpc 0.0.1-mrgn-fork1-dev-61aff5b → 0.0.3-mrgn-fork1-dev-e66607b

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 (52) hide show
  1. package/dist/src/addresses.js.map +1 -0
  2. package/dist/src/events.d.ts +13 -0
  3. package/dist/src/events.js +3 -0
  4. package/dist/src/events.js.map +1 -0
  5. package/dist/src/idl/clend.js.map +1 -0
  6. package/dist/src/index.js.map +1 -0
  7. package/dist/{instructions.d.ts → src/instructions.d.ts} +2 -1
  8. package/dist/{instructions.js → src/instructions.js} +15 -2
  9. package/dist/src/instructions.js.map +1 -0
  10. package/dist/src/jupUtils.js.map +1 -0
  11. package/dist/{jupiterUtils.js → src/jupiterUtils.js} +1 -1
  12. package/dist/src/jupiterUtils.js.map +1 -0
  13. package/dist/src/logger.js.map +1 -0
  14. package/dist/{math.d.ts → src/math.d.ts} +78 -57
  15. package/dist/{math.js → src/math.js} +239 -113
  16. package/dist/src/math.js.map +1 -0
  17. package/dist/src/mockJupiterUtils.js.map +1 -0
  18. package/dist/{rpc.d.ts → src/rpc.d.ts} +36 -2
  19. package/dist/{rpc.js → src/rpc.js} +485 -188
  20. package/dist/src/rpc.js.map +1 -0
  21. package/dist/{state.d.ts → src/state.d.ts} +65 -27
  22. package/dist/{state.js → src/state.js} +34 -14
  23. package/dist/src/state.js.map +1 -0
  24. package/dist/{utils.d.ts → src/utils.d.ts} +2 -0
  25. package/dist/{utils.js → src/utils.js} +28 -13
  26. package/dist/src/utils.js.map +1 -0
  27. package/package.json +1 -1
  28. package/dist/addresses.js.map +0 -1
  29. package/dist/idl/clend.js.map +0 -1
  30. package/dist/index.js.map +0 -1
  31. package/dist/instructions.js.map +0 -1
  32. package/dist/jupUtils.js.map +0 -1
  33. package/dist/jupiterUtils.js.map +0 -1
  34. package/dist/logger.js.map +0 -1
  35. package/dist/math.js.map +0 -1
  36. package/dist/mockJupiterUtils.js.map +0 -1
  37. package/dist/rpc.js.map +0 -1
  38. package/dist/state.js.map +0 -1
  39. package/dist/utils.js.map +0 -1
  40. /package/dist/{addresses.d.ts → src/addresses.d.ts} +0 -0
  41. /package/dist/{addresses.js → src/addresses.js} +0 -0
  42. /package/dist/{idl → src/idl}/clend.d.ts +0 -0
  43. /package/dist/{idl → src/idl}/clend.js +0 -0
  44. /package/dist/{index.d.ts → src/index.d.ts} +0 -0
  45. /package/dist/{index.js → src/index.js} +0 -0
  46. /package/dist/{jupUtils.d.ts → src/jupUtils.d.ts} +0 -0
  47. /package/dist/{jupUtils.js → src/jupUtils.js} +0 -0
  48. /package/dist/{jupiterUtils.d.ts → src/jupiterUtils.d.ts} +0 -0
  49. /package/dist/{logger.d.ts → src/logger.d.ts} +0 -0
  50. /package/dist/{logger.js → src/logger.js} +0 -0
  51. /package/dist/{mockJupiterUtils.d.ts → src/mockJupiterUtils.d.ts} +0 -0
  52. /package/dist/{mockJupiterUtils.js → src/mockJupiterUtils.js} +0 -0
@@ -13,16 +13,17 @@ exports.calculateSupplyApy = calculateSupplyApy;
13
13
  exports.calculateBorrowApy = calculateBorrowApy;
14
14
  exports.computeAdjustLeverageAmounts = computeAdjustLeverageAmounts;
15
15
  exports.computeMaxLeverage = computeMaxLeverage;
16
- exports.computeLiquidationThreshold = computeLiquidationThreshold;
17
16
  exports.computeLoopingAmounts = computeLoopingAmounts;
18
17
  exports.calculateWeightedValue = calculateWeightedValue;
18
+ exports.calculateWeightedAmount = calculateWeightedAmount;
19
19
  exports.calculateWeightedLeverage = calculateWeightedLeverage;
20
- exports.calculateRequiredBorrowAmount = calculateRequiredBorrowAmount;
21
20
  exports.computeWithdrawLeverageAmounts = computeWithdrawLeverageAmounts;
22
- exports.calculateHealthFactor = calculateHealthFactor;
23
- exports.calculateUsdValue = calculateUsdValue;
21
+ exports.calculateHealthFactorAndLeverage = calculateHealthFactorAndLeverage;
22
+ exports.calculateAccruedInterest = calculateAccruedInterest;
23
+ exports.adjustBorrowForImmediateCosts = adjustBorrowForImmediateCosts;
24
+ exports.adjustBorrowForSlippage = adjustBorrowForSlippage;
24
25
  const anchor_1 = require("@coral-xyz/anchor");
25
- const utils_1 = require("./utils");
26
+ const decimal_js_1 = require("decimal.js");
26
27
  /**
27
28
  * Convert a UI number to a token amount BN
28
29
  * @param uiAmount Amount in UI format (e.g., 1.5 USDC)
@@ -65,8 +66,7 @@ function calculateAssetQuantity(assetShares, assetShareValue) {
65
66
  const shares = typeof assetShares === "number"
66
67
  ? assetShares
67
68
  : Number(assetShares.toString());
68
- const shareValue = Number((0, utils_1.wrappedI80F48toBigNumber)(assetShareValue).toString());
69
- return shares * shareValue;
69
+ return shares * assetShareValue;
70
70
  }
71
71
  /**
72
72
  * Calculate liability quantity from liability shares
@@ -78,8 +78,7 @@ function calculateLiabilityQuantity(liabilityShares, liabilityShareValue) {
78
78
  const shares = typeof liabilityShares === "number"
79
79
  ? liabilityShares
80
80
  : Number(liabilityShares.toString());
81
- const shareValue = Number((0, utils_1.wrappedI80F48toBigNumber)(liabilityShareValue).toString());
82
- return shares * shareValue;
81
+ return shares * liabilityShareValue;
83
82
  }
84
83
  /**
85
84
  * Calculate total asset quantity
@@ -92,7 +91,7 @@ function calculateLiabilityQuantity(liabilityShares, liabilityShareValue) {
92
91
  * - assetShareValue = bank.assetShareValue
93
92
  */
94
93
  function calculateTotalAssetQuantity(totalAssetShares, assetShareValue) {
95
- return calculateAssetQuantity((0, utils_1.wrappedI80F48toBigNumber)(totalAssetShares), assetShareValue);
94
+ return calculateAssetQuantity(totalAssetShares, assetShareValue);
96
95
  }
97
96
  /**
98
97
  * Calculate total liability quantity
@@ -105,7 +104,7 @@ function calculateTotalAssetQuantity(totalAssetShares, assetShareValue) {
105
104
  * - liabilityShareValue = bank.liabilityShareValue
106
105
  */
107
106
  function calculateTotalLiabilityQuantity(totalLiabilityShares, liabilityShareValue) {
108
- return calculateLiabilityQuantity((0, utils_1.wrappedI80F48toBigNumber)(totalLiabilityShares), liabilityShareValue);
107
+ return calculateLiabilityQuantity(totalLiabilityShares, liabilityShareValue);
109
108
  }
110
109
  /**
111
110
  * Calculate the bank's utilization rate
@@ -140,19 +139,17 @@ function calculateBankUtilizationRate(totalAssetShares, assetShareValue, totalLi
140
139
  * - maxInterestRate = bank.config.interestRateConfig.maxInterestRate
141
140
  */
142
141
  function calculateBaseInterestRate(utilizationRate, optimalUtilizationRate, plateauInterestRate, maxInterestRate) {
143
- const optimalRate = Number((0, utils_1.wrappedI80F48toBigNumber)(optimalUtilizationRate).toString());
144
- const plateauRate = Number((0, utils_1.wrappedI80F48toBigNumber)(plateauInterestRate).toString());
145
- const maxRate = Number((0, utils_1.wrappedI80F48toBigNumber)(maxInterestRate).toString());
146
- if (utilizationRate <= optimalRate) {
142
+ if (utilizationRate <= optimalUtilizationRate) {
147
143
  // Below optimal: linear increase from 0 to plateau rate
148
- return (utilizationRate / optimalRate) * plateauRate;
144
+ return (utilizationRate / optimalUtilizationRate) * plateauInterestRate;
149
145
  }
150
146
  else {
151
147
  // Above optimal: linear increase from plateau to max rate
152
- const excessUtilization = utilizationRate - optimalRate;
153
- const remainingUtilization = 1 - optimalRate;
154
- const excessRate = maxRate - plateauRate;
155
- return (plateauRate + (excessUtilization / remainingUtilization) * excessRate);
148
+ const excessUtilization = utilizationRate - optimalUtilizationRate;
149
+ const remainingUtilization = 1 - optimalUtilizationRate;
150
+ const excessRate = maxInterestRate - plateauInterestRate;
151
+ return (plateauInterestRate +
152
+ (excessUtilization / remainingUtilization) * excessRate);
156
153
  }
157
154
  }
158
155
  /**
@@ -171,9 +168,7 @@ function calculateBaseInterestRate(utilizationRate, optimalUtilizationRate, plat
171
168
  */
172
169
  function calculateSupplyApy(utilizationRate, baseInterestRate, protocolIrFee, insuranceIrFee) {
173
170
  // Supply rate = base rate * utilization rate * (1 - protocol fees)
174
- const protocolFee = Number((0, utils_1.wrappedI80F48toBigNumber)(protocolIrFee).toString());
175
- const insuranceFee = Number((0, utils_1.wrappedI80F48toBigNumber)(insuranceIrFee).toString());
176
- const totalFeeRate = protocolFee + insuranceFee;
171
+ const totalFeeRate = protocolIrFee + insuranceIrFee;
177
172
  return baseInterestRate * utilizationRate * (1 - totalFeeRate);
178
173
  }
179
174
  /**
@@ -190,9 +185,8 @@ function calculateSupplyApy(utilizationRate, baseInterestRate, protocolIrFee, in
190
185
  */
191
186
  function calculateBorrowApy(baseInterestRate, protocolFixedFeeApr, insuranceFeeFixedApr) {
192
187
  // Borrow rate = base rate + fixed protocol fee + fixed insurance fee
193
- const protocolFee = Number((0, utils_1.wrappedI80F48toBigNumber)(protocolFixedFeeApr).toString());
194
- const insuranceFee = Number((0, utils_1.wrappedI80F48toBigNumber)(insuranceFeeFixedApr).toString());
195
- return baseInterestRate + protocolFee + insuranceFee;
188
+ const totalFeeRate = protocolFixedFeeApr + insuranceFeeFixedApr;
189
+ return baseInterestRate + totalFeeRate;
196
190
  }
197
191
  /**
198
192
  * Computes amounts needed to adjust leverage
@@ -202,23 +196,28 @@ function calculateBorrowApy(baseInterestRate, protocolFixedFeeApr, insuranceFeeF
202
196
  * @param debtPrice - Current debt token price in USD
203
197
  * @param currentLeverage - Current leverage ratio
204
198
  * @param targetLeverage - Desired leverage ratio
199
+ * @param collateralWeight - Weight of collateral for maintenance (0-1)
200
+ * @param debtWeight - Weight of debt for maintenance (1+)
205
201
  */
206
- function computeAdjustLeverageAmounts(currentCollateral, currentDebt, collateralPrice, debtPrice, currentLeverage, targetLeverage) {
207
- // Convert everything to USD value
208
- const currentPositionValue = currentCollateral * collateralPrice;
209
- const currentDebtValue = currentDebt * debtPrice;
210
- const currentEquity = currentPositionValue - currentDebtValue;
211
- // Target position size based on desired leverage
212
- const targetPositionValue = currentEquity * targetLeverage;
213
- const targetCollateral = targetPositionValue / collateralPrice;
214
- const targetDebtValue = targetPositionValue - currentEquity;
215
- const targetDebt = targetDebtValue / debtPrice;
202
+ function computeAdjustLeverageAmounts(currentCollateral, currentDebt, collateralPrice, debtPrice, currentLeverage, targetLeverage, collateralWeight, debtWeight) {
203
+ // Convert everything to weighted USD value
204
+ const weightedCollateralValue = calculateWeightedValue(currentCollateral, collateralPrice, collateralWeight);
205
+ const weightedDebtValue = calculateWeightedValue(currentDebt, debtPrice, debtWeight);
206
+ const weightedEquity = weightedCollateralValue - weightedDebtValue;
207
+ if (weightedEquity <= 0) {
208
+ throw new Error("Weighted equity must be positive");
209
+ }
210
+ // Target weighted position size based on desired leverage
211
+ const targetWeightedPositionValue = weightedEquity * targetLeverage;
212
+ const targetWeightedDebtValue = targetWeightedPositionValue - weightedEquity;
213
+ // Convert back to raw token amounts
214
+ const targetCollateral = targetWeightedPositionValue / (collateralPrice * collateralWeight);
215
+ const targetDebt = targetWeightedDebtValue / (debtPrice * debtWeight);
216
216
  // Calculate changes needed
217
217
  const collateralDelta = targetCollateral - currentCollateral;
218
218
  const debtDelta = targetDebt - currentDebt;
219
- const isIncrease = targetLeverage > currentLeverage;
220
219
  return {
221
- isIncrease,
220
+ isIncrease: targetLeverage > currentLeverage,
222
221
  collateralDelta: Math.abs(collateralDelta),
223
222
  debtDelta: Math.abs(debtDelta),
224
223
  };
@@ -251,31 +250,6 @@ function computeMaxLeverage(depositAssetWeight, borrowLiabilityWeight) {
251
250
  ltv,
252
251
  };
253
252
  }
254
- /**
255
- * Computes the liquidation threshold (LT) given deposit and borrow asset maintenance weights.
256
- * The LT represents the Loan-to-Value ratio at which liquidation can occur.
257
- * @param depositAssetWeightMaint - Maintenance risk weight of deposit asset (0-1).
258
- * @param borrowLiabilityWeightMaint - Maintenance risk weight of borrow asset (0-2).
259
- * @returns Object containing:
260
- * - liquidationThreshold: The LTV ratio at which liquidation occurs. Returns -1 if parameters are invalid.
261
- */
262
- function computeLiquidationThreshold(depositAssetWeightMaint, borrowLiabilityWeightMaint) {
263
- // Handle edge cases/invalid inputs
264
- if (borrowLiabilityWeightMaint <= 0 || depositAssetWeightMaint < 0) {
265
- // LT cannot be calculated if liability weight is non-positive
266
- // or asset weight is negative.
267
- return { liquidationThreshold: -1 };
268
- }
269
- // Liquidation Threshold (LT) is the LTV calculated using maintenance weights.
270
- // It represents the point where weighted assets no longer cover weighted liabilities.
271
- const liquidationThreshold = depositAssetWeightMaint / borrowLiabilityWeightMaint;
272
- // LT can theoretically be >= 1 if weights are set permissively,
273
- // although this implies liquidation is impossible or happens immediately
274
- // depending on initial LTV. We return the calculated value.
275
- return {
276
- liquidationThreshold,
277
- };
278
- }
279
253
  /**
280
254
  * Computes the borrow and deposit amounts needed to achieve target leverage, accounting for weights
281
255
  * @param principal - Initial deposit amount
@@ -354,7 +328,18 @@ function computeLoopingAmounts(principal, targetLeverage, depositPrice, borrowPr
354
328
  * @returns Weighted value in USD terms
355
329
  */
356
330
  function calculateWeightedValue(amount, price, weight) {
357
- return amount * price * weight;
331
+ const weightedAmount = calculateWeightedAmount(amount, weight);
332
+ return weightedAmount * price;
333
+ }
334
+ /**
335
+ * Calculates the weighted value of an amount based on its price and weight
336
+ * @param amount - Raw amount of the token
337
+ * @param price - Price of the token
338
+ * @param weight - Weight to apply (0-1 for assets, 1+ for liabilities)
339
+ * @returns Weighted value in USD terms
340
+ */
341
+ function calculateWeightedAmount(amount, weight) {
342
+ return amount * weight;
358
343
  }
359
344
  /**
360
345
  * Calculates leverage using weighted values
@@ -375,25 +360,6 @@ function calculateWeightedLeverage(collateralAmount, collateralPrice, collateral
375
360
  }
376
361
  return weightedCollateralValue / netValue;
377
362
  }
378
- /**
379
- * Calculates the required borrow amount to achieve target leverage
380
- * @param collateralAmount - Initial collateral amount
381
- * @param collateralPrice - Price of collateral
382
- * @param collateralWeight - Weight of collateral (0-1)
383
- * @param debtPrice - Price of debt
384
- * @param debtWeight - Weight of debt (1+)
385
- * @param targetLeverage - Desired leverage ratio
386
- * @returns Required borrow amount in debt token units
387
- */
388
- function calculateRequiredBorrowAmount(collateralAmount, collateralPrice, collateralWeight, debtPrice, debtWeight, targetLeverage) {
389
- const weightedCollateralValue = calculateWeightedValue(collateralAmount, collateralPrice, collateralWeight);
390
- // Solve for debt value in the leverage equation:
391
- // leverage = weightedCollateralValue / (weightedCollateralValue - weightedDebtValue)
392
- // => weightedDebtValue = weightedCollateralValue * (1 - 1/leverage)
393
- const weightedDebtValue = weightedCollateralValue * (1 - 1 / targetLeverage);
394
- // Convert weighted debt value to actual debt amount
395
- return weightedDebtValue / (debtPrice * debtWeight);
396
- }
397
363
  /**
398
364
  * Calculates the debt to repay when withdrawing collateral to maintain the same leverage ratio
399
365
  * @param currentCollateral - Current collateral amount
@@ -414,9 +380,6 @@ function computeWithdrawLeverageAmounts(currentCollateral, currentDebt, withdraw
414
380
  }
415
381
  // Calculate new collateral amount
416
382
  const newCollateral = currentCollateral - withdrawAmount;
417
- // Calculate weighted values for current position
418
- const currentWeightedCollateral = currentCollateral * collateralPrice * collateralWeight;
419
- const currentWeightedDebt = currentDebt * debtPrice * debtWeight;
420
383
  // Calculate weighted collateral after withdrawal
421
384
  const newWeightedCollateral = newCollateral * collateralPrice * collateralWeight;
422
385
  // To maintain the same leverage, we need:
@@ -435,48 +398,211 @@ function computeWithdrawLeverageAmounts(currentCollateral, currentDebt, withdraw
435
398
  // Calculate what the new leverage will be (should be very close to currentLeverage)
436
399
  const newLeverage = calculateWeightedLeverage(newCollateral, collateralPrice, collateralWeight, newDebt, debtPrice, debtWeight);
437
400
  return {
438
- debtToRepay,
439
- newCollateral,
440
- newDebt,
401
+ debtToRepayUi: debtToRepay,
402
+ newCollateralUi: newCollateral,
403
+ newDebtUi: newDebt,
441
404
  currentLeverage,
442
405
  newLeverage,
443
406
  };
444
407
  }
445
408
  /**
446
- * Calculates the health factor of a Marginfi account.
447
- * Health Factor = Total Weighted Assets (Maintenance) / Total Weighted Liabilities (Maintenance)
448
- * A health factor > 1 indicates solvency. Liquidation occurs when it approaches 1.
409
+ * Calculates the health factor and leverage of a Marginfi account using weighted maintenance values.
410
+ *
411
+ * Standard Health Factor = Total Weighted Assets (Maintenance) / Total Weighted Liabilities (Maintenance)
412
+ * Interpretation:
413
+ * - HF > 1: Position is overcollateralized (safe).
414
+ * - HF = 1: Position is at the liquidation threshold.
415
+ * - HF < 1: Position is undercollateralized and liquidatable.
416
+ * - HF = Infinity: Position has no debt (healthiest).
449
417
  *
450
- * @param assets - An array of the user's deposited assets with their values and maintenance weights.
451
- * @param liabilities - An array of the user's borrowed liabilities with their values and maintenance weights.
452
- * @returns The health factor. Returns Infinity if there are no liabilities.
418
+ * Leverage = Total Weighted Assets (Maintenance) / (Total Weighted Assets (Maintenance) - Total Weighted Liabilities (Maintenance))
419
+ *
420
+ * @param weightedAssetValues - An array of the user's weighted asset values (maintenance).
421
+ * @param weightedLiabilityValues - An array of the user's weighted liability values (maintenance).
422
+ * @returns An object containing the healthFactor and leverage.
453
423
  */
454
- function calculateHealthFactor(assets, liabilities) {
424
+ function calculateHealthFactorAndLeverage(weightedAssetValues, weightedLiabilityValues) {
455
425
  let totalWeightedAssets = 0;
456
- for (const asset of assets) {
457
- totalWeightedAssets +=
458
- asset.assetAmountUi * asset.assetPrice * asset.maintAssetWeight;
426
+ for (const weightedAssetValue of weightedAssetValues) {
427
+ totalWeightedAssets += weightedAssetValue;
459
428
  }
460
429
  let totalWeightedLiabilities = 0;
461
- for (const liability of liabilities) {
462
- totalWeightedLiabilities +=
463
- liability.liabilityAmountUi *
464
- liability.liabilityPrice *
465
- liability.maintLiabilityWeight;
430
+ for (const weightedLiabilityValue of weightedLiabilityValues) {
431
+ totalWeightedLiabilities += weightedLiabilityValue;
466
432
  }
467
- // if no borrows, 100% health
433
+ // Calculate health factor using standard convention (Assets / Liabilities)
434
+ let healthFactor;
468
435
  if (totalWeightedLiabilities === 0) {
469
- return 1;
436
+ // Handle division by zero: No liabilities means infinite health
437
+ healthFactor = Infinity;
438
+ }
439
+ else if (totalWeightedAssets === 0) {
440
+ // Handle edge case where assets are zero but liabilities are not (should imply HF=0)
441
+ healthFactor = 0;
442
+ }
443
+ else {
444
+ // Standard calculation
445
+ healthFactor = totalWeightedAssets / totalWeightedLiabilities;
470
446
  }
471
- return totalWeightedAssets / totalWeightedLiabilities;
447
+ // Calculate leverage (same formula as before, using weighted values)
448
+ let leverage = 0; // Default to 0 if equity is zero or negative
449
+ const equity = totalWeightedAssets - totalWeightedLiabilities;
450
+ if (equity > 0 && totalWeightedAssets > 0) {
451
+ // Ensure equity is positive and avoid division by zero if assets are zero
452
+ leverage = totalWeightedAssets / equity;
453
+ }
454
+ else if (totalWeightedAssets > 0 && totalWeightedLiabilities === 0) {
455
+ // If only assets exist, leverage is 1x
456
+ leverage = 1;
457
+ }
458
+ return { healthFactor, leverage };
472
459
  }
473
460
  /**
474
- * Calculate USD value from UI amount and price
475
- * @param uiAmount Amount in UI format (e.g., 1.5 USDC)
476
- * @param price Price of the token in USD
477
- * @returns USD value
461
+ * Calculates the interest that has accrued but not yet been applied to a bank
462
+ * @param lastUpdate The timestamp of the last update
463
+ * @param assetAmountUi The total asset amount in UI format
464
+ * @param liabilityAmountUi The total liability amount in UI format
465
+ * @param utilizationRate The current utilization rate
466
+ * @param interestRateConfig The interest rate configuration
467
+ * @param currentTimestamp Optional current timestamp (in seconds). Defaults to Math.floor(Date.now() / 1000)
468
+ * @returns Object containing:
469
+ * - assetInterestAccrued: Interest accrued for lenders (in token units)
470
+ * - liabilityInterestAccrued: Interest accrued for borrowers (in token units)
471
+ * - insuranceFeesAccrued: Insurance fees accrued (in token units)
472
+ * - groupFeesAccrued: Group fees accrued (in token units)
473
+ * - protocolFeesAccrued: Protocol fees accrued (in token units)
478
474
  */
479
- function calculateUsdValue(uiAmount, price) {
480
- return uiAmount * price;
475
+ function calculateAccruedInterest(lastUpdate, assetAmountUi, liabilityAmountUi, utilizationRate, interestRateConfig, currentTimestamp) {
476
+ const timeDelta = currentTimestamp - lastUpdate.toNumber();
477
+ // If no time has passed, return zero values
478
+ if (timeDelta <= 0) {
479
+ return {
480
+ assetInterestAccrued: 0,
481
+ liabilityInterestAccrued: 0,
482
+ insuranceFeesAccrued: 0,
483
+ groupFeesAccrued: 0,
484
+ protocolFeesAccrued: 0,
485
+ };
486
+ }
487
+ // Get total assets and liabilities
488
+ const totalAssets = assetAmountUi;
489
+ const totalLiabilities = liabilityAmountUi;
490
+ // If either total assets or liabilities are zero, return zero values
491
+ if (totalAssets === 0 || totalLiabilities === 0) {
492
+ return {
493
+ assetInterestAccrued: 0,
494
+ liabilityInterestAccrued: 0,
495
+ insuranceFeesAccrued: 0,
496
+ groupFeesAccrued: 0,
497
+ protocolFeesAccrued: 0,
498
+ };
499
+ }
500
+ // Get interest rate configuration
501
+ const { optimalUtilizationRate, plateauInterestRate, maxInterestRate, insuranceFeeFixedApr, insuranceIrFee, protocolFixedFeeApr, protocolIrFee, } = interestRateConfig;
502
+ // Calculate base interest rate
503
+ const baseInterestRate = calculateBaseInterestRate(utilizationRate, optimalUtilizationRate, plateauInterestRate, maxInterestRate);
504
+ // Calculate lending rate (supply rate)
505
+ const lendingRate = baseInterestRate * utilizationRate * (1 - (protocolIrFee + insuranceIrFee));
506
+ // Calculate borrowing rate
507
+ const borrowingRate = baseInterestRate * (1 + protocolIrFee) +
508
+ protocolFixedFeeApr +
509
+ insuranceFeeFixedApr;
510
+ // Calculate fee rates
511
+ const insuranceFeeRate = baseInterestRate * insuranceIrFee + insuranceFeeFixedApr;
512
+ const groupFeeRate = baseInterestRate * protocolIrFee + protocolFixedFeeApr;
513
+ const protocolFeeRate = baseInterestRate * protocolIrFee + protocolFixedFeeApr;
514
+ // Calculate interest accrued for the time period
515
+ const secondsPerYear = 365 * 24 * 60 * 60;
516
+ const timeDeltaFraction = timeDelta / secondsPerYear;
517
+ // Calculate asset interest accrued (for lenders)
518
+ const assetInterestAccrued = totalAssets * lendingRate * timeDeltaFraction;
519
+ // Calculate liability interest accrued (for borrowers)
520
+ const liabilityInterestAccrued = totalLiabilities * borrowingRate * timeDeltaFraction;
521
+ // Calculate fees accrued
522
+ const insuranceFeesAccrued = totalLiabilities * insuranceFeeRate * timeDeltaFraction;
523
+ const groupFeesAccrued = totalLiabilities * groupFeeRate * timeDeltaFraction;
524
+ const protocolFeesAccrued = totalLiabilities * protocolFeeRate * timeDeltaFraction;
525
+ return {
526
+ assetInterestAccrued,
527
+ liabilityInterestAccrued,
528
+ insuranceFeesAccrued,
529
+ groupFeesAccrued,
530
+ protocolFeesAccrued,
531
+ };
532
+ }
533
+ const SECONDS_PER_YEAR = new decimal_js_1.Decimal(365.25 * 24 * 60 * 60);
534
+ /**
535
+ * Adjusts the ideal borrow amount downwards to compensate for immediate costs
536
+ * (primarily origination fee + estimated short-term interest accrual).
537
+ *
538
+ * @param idealBorrowAmount - The ideally calculated borrow amount (native units, BN).
539
+ * @param originationFeeRate - The protocol origination fee rate (e.g., 0.01 for 1%).
540
+ * @param borrowApy - The current estimated borrow APY of the debt asset (e.g., 0.025 for 2.5%).
541
+ * @param debtDecimals - Decimals of the debt asset.
542
+ * @param estimatedTimeSec - Estimated seconds for immediate interest accrual effect (default: 1.5s).
543
+ * @returns Adjusted borrow amount (native units, BN), slightly less than ideal. Returns ideal amount if rates are zero.
544
+ */
545
+ function adjustBorrowForImmediateCosts(idealBorrowAmount, originationFeeRate, borrowApy, estimatedTimeSec = 1.5) {
546
+ const costRate = new decimal_js_1.Decimal(originationFeeRate);
547
+ const interestRatePerSecond = new decimal_js_1.Decimal(borrowApy).div(SECONDS_PER_YEAR);
548
+ const estimatedInterestRate = interestRatePerSecond.mul(estimatedTimeSec);
549
+ // Combine origination fee rate and estimated interest rate for the period
550
+ const totalEffectiveCostRate = costRate.add(estimatedInterestRate);
551
+ if (totalEffectiveCostRate.isZero() || totalEffectiveCostRate.isNegative()) {
552
+ return idealBorrowAmount; // No adjustment if no cost
553
+ }
554
+ // Formula: B_actual ≈ B_ideal / (1 + totalEffectiveCostRate)
555
+ // We borrow slightly less to account for the cost being added to liability
556
+ const denominator = new decimal_js_1.Decimal(1).add(totalEffectiveCostRate);
557
+ // Should not happen with valid inputs, but safety check
558
+ if (denominator.isZero() ||
559
+ denominator.isNaN() ||
560
+ !denominator.isFinite() ||
561
+ denominator.isNegative()) {
562
+ console.warn("Invalid denominator in cost adjustment, returning ideal amount");
563
+ return idealBorrowAmount;
564
+ }
565
+ const idealBorrowDecimal = new decimal_js_1.Decimal(idealBorrowAmount.toString());
566
+ const adjustedBorrowDecimal = idealBorrowDecimal.div(denominator);
567
+ // Round down when reducing amount due to costs
568
+ const adjustedBorrowAmount = new anchor_1.BN(adjustedBorrowDecimal.floor().toFixed());
569
+ // Ensure we don't adjust below zero
570
+ return anchor_1.BN.max(adjustedBorrowAmount, new anchor_1.BN(0));
571
+ }
572
+ /**
573
+ * Adjusts a borrow amount upwards to compensate for potential swap slippage,
574
+ * assuming worst-case based on slippageBps.
575
+ *
576
+ * @param amountToAdjust - The borrow amount to adjust (native units, BN), typically after cost adjustments.
577
+ * @param slippageBps - The maximum slippage tolerance in basis points (e.g., 100 for 1%).
578
+ * @param debtDecimals - Decimals of the debt asset.
579
+ * @returns Adjusted borrow amount (native units, BN), slightly more than the input amount. Returns input amount if slippageBps is zero or invalid.
580
+ */
581
+ function adjustBorrowForSlippage(amountToAdjust, slippageBps, debtDecimals) {
582
+ if (slippageBps <= 0) {
583
+ return amountToAdjust; // No adjustment if no slippage tolerance
584
+ }
585
+ const S = new decimal_js_1.Decimal(slippageBps).div(10000); // Slippage factor S as decimal
586
+ // Ensure S is less than 1 (100% slippage)
587
+ if (S.gte(1)) {
588
+ console.warn(`Slippage factor ${S.toString()} is >= 100%, returning original amount.`);
589
+ return amountToAdjust;
590
+ }
591
+ // Formula: B_actual ≈ B_ideal / (1 - S)
592
+ // We borrow slightly more, anticipating the swap output will be worth less by factor S.
593
+ const denominator = new decimal_js_1.Decimal(1).sub(S);
594
+ // Should not happen with S < 1, but safety check
595
+ if (denominator.isZero() ||
596
+ denominator.isNaN() ||
597
+ !denominator.isFinite() ||
598
+ denominator.isNegative()) {
599
+ console.warn("Invalid denominator in slippage adjustment, returning input amount");
600
+ return amountToAdjust;
601
+ }
602
+ const amountToAdjustDecimal = new decimal_js_1.Decimal(amountToAdjust.toString());
603
+ const adjustedBorrowDecimal = amountToAdjustDecimal.div(denominator);
604
+ // Round up when increasing amount due to needing more input for slippage
605
+ const adjustedBorrowAmount = new anchor_1.BN(adjustedBorrowDecimal.ceil().toFixed());
606
+ return adjustedBorrowAmount;
481
607
  }
482
608
  //# sourceMappingURL=math.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"math.js","sourceRoot":"","sources":["../../src/math.ts"],"names":[],"mappings":";;AAkBA,gCAEC;AAQD,gCAKC;AAQD,4DAMC;AAQD,wDASC;AAQD,gEASC;AAYD,kEAKC;AAYD,0EAKC;AAgBD,oEAgBC;AAeD,8DAoBC;AAgBD,gDAUC;AAcD,gDASC;AAaD,oEAiDC;AAUD,gDA0BC;AAcD,sDA2EC;AASD,wDAOC;AASD,0DAKC;AAYD,8DA0BC;AAaD,wEAuEC;AAkBD,4EAuCC;AAiBD,4DAmGC;AAeD,sEA0CC;AAWD,0DA2CC;AAt1BD,8CAAuC;AAUvC,2CAAqC;AAErC;;;;;GAKG;AACH,SAAgB,UAAU,CAAC,QAAgB,EAAE,QAAgB;IAC3D,OAAO,IAAI,WAAE,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,GAAG,EAAE,IAAI,QAAQ,CAAC,CAAC,CAAC;AACvD,CAAC;AAED;;;;;GAKG;AACH,SAAgB,UAAU,CAAC,MAAmB,EAAE,QAAgB;IAC9D,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;QAC/B,OAAO,MAAM,GAAG,EAAE,IAAI,QAAQ,CAAC;IACjC,CAAC;IACD,OAAO,MAAM,CAAC,QAAQ,EAAE,GAAG,EAAE,IAAI,QAAQ,CAAC;AAC5C,CAAC;AAED;;;;;GAKG;AACH,SAAgB,wBAAwB,CACtC,WAAmB,EACnB,WAAmB;IAEnB,IAAI,WAAW,KAAK,CAAC,IAAI,WAAW,KAAK,CAAC;QAAE,OA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OAAO,GAAG,KAAK,CAAC,QAAQ,EAAE,IAAI,MAAM,CAAC,SAAS,CAAC,QAAQ,EAAE,IAAI,MAAM,CAAC,UAAU,CAAC,QAAQ,EAAE,EAAE,CAAC;IAC9F,CAAC;CACF;AAlGD,4CAkGC"}
@@ -9,7 +9,8 @@ export declare class ClendClient {
9
9
  readonly provider: AnchorProvider;
10
10
  readonly instructions: Instructions;
11
11
  private jupiterUtils;
12
- constructor(connection: web3.Connection, wallet: Wallet, skipPreflight?: boolean, jupiterUtils?: IJupiterUtils);
12
+ private dryRun;
13
+ constructor(connection: web3.Connection, wallet: Wallet, skipPreflight?: boolean, jupiterUtils?: IJupiterUtils, dryRun?: boolean);
13
14
  address(): web3.PublicKey;
14
15
  /**
15
16
  * Get Jupiter price for a token pair
@@ -47,9 +48,42 @@ export declare class ClendClient {
47
48
  withdraw(clendGroup: web3.PublicKey, clendAccount: web3.PublicKey, mint: web3.PublicKey, amount: BN, withdrawAll?: boolean | null): Promise<string>;
48
49
  borrow(clendGroup: web3.PublicKey, clendAccount: web3.PublicKey, mint: web3.PublicKey, amount: BN): Promise<string>;
49
50
  repay(clendGroup: web3.PublicKey, clendAccount: web3.PublicKey, mint: web3.PublicKey, amount: BN, repayAll?: boolean | null): Promise<string>;
50
- editGlobalFeeWallet(newGlobalFeeWallet: web3.PublicKey): Promise<string>;
51
+ editGlobalFeeState(clendGroup: web3.PublicKey, newGlobalFeeWallet: web3.PublicKey | null, newBankInitFlatSolFee: number | null, newProgramFeeFixed: number | null, newProgramFeeRate: number | null): Promise<string>;
51
52
  configureBankInterestRate(clendGroup: web3.PublicKey, bank: web3.PublicKey, interestRateConfig: InterestRateConfigOpt): Promise<string>;
52
53
  depositLeverage(clendGroup: web3.PublicKey, clendAccount: web3.PublicKey | null, collateralMint: web3.PublicKey, debtMint: web3.PublicKey, depositAmount: BN, targetLeverage: number, slippageBps: number): Promise<string>;
54
+ getDepositLeverageIxns(clendGroup: web3.PublicKey, user: web3.PublicKey, clendAccount: web3.PublicKey | null, collateralMint: web3.PublicKey, debtMint: web3.PublicKey, debtMintDecimals: number, collateralMintDecimals: number, borrowAmount: BN, depositAmount: BN, slippageBps: number, additionalIxnCount: number): Promise<{
55
+ ixns: web3.TransactionInstruction[];
56
+ luts: web3.PublicKey[];
57
+ }>;
58
+ getDepositLeverageParams(clendGroup: web3.PublicKey, collateralMint: web3.PublicKey, debtMint: web3.PublicKey, depositAmount: BN, targetLeverage: number): Promise<{
59
+ borrowAmount: BN;
60
+ totalDepositAmountUi: BN;
61
+ debtBankData: Bank;
62
+ collateralBankData: Bank;
63
+ }>;
53
64
  withdrawLeverage(clendGroup: web3.PublicKey, clendAccount: web3.PublicKey, collateralMint: web3.PublicKey, debtMint: web3.PublicKey, withdrawAmount: BN, withdrawAll: boolean, slippageBps: number): Promise<string>;
65
+ getWithdrawLeverageIxns(clendGroup: web3.PublicKey, clendAccount: web3.PublicKey, collateralMint: web3.PublicKey, debtMint: web3.PublicKey, collateralDecimals: number, debtDecimals: number, withdrawAll: boolean, debtToRepay: BN, collateralToWithdraw: BN, slippageBps: number, additionalIxnCount: number): Promise<{
66
+ ixns: web3.TransactionInstruction[];
67
+ luts: web3.PublicKey[];
68
+ }>;
69
+ getWithdrawLeverageParams(clendGroup: web3.PublicKey, clendAccount: web3.PublicKey, collateralMint: web3.PublicKey, debtMint: web3.PublicKey, withdrawAmount: BN, withdrawAll: boolean): Promise<{
70
+ debtToRepay: BN;
71
+ collateralToWithdraw: BN;
72
+ collateralBankData: Bank;
73
+ debtBankData: Bank;
74
+ }>;
54
75
  adjustLeverage(clendGroup: web3.PublicKey, clendAccount: web3.PublicKey, collateralMint: web3.PublicKey, debtMint: web3.PublicKey, targetLeverage: number, slippageBps: number): Promise<string>;
76
+ getAdjustLeverageParams(clendGroup: web3.PublicKey, clendAccount: web3.PublicKey, collateralMint: web3.PublicKey, debtMint: web3.PublicKey, targetLeverage: number): Promise<{
77
+ collateralDeltaUi: number;
78
+ debtDeltaUi: number;
79
+ isIncrease: boolean;
80
+ collateralBankData: Bank;
81
+ debtBankData: Bank;
82
+ }>;
83
+ getAdjustLeverageIxns(clendGroup: web3.PublicKey, clendAccount: web3.PublicKey, user: web3.PublicKey, debtBankData: Bank, collateralBankData: Bank, isIncrease: boolean, debtDeltaUi: number, slippageBps: number, additionalIxnCount: number): Promise<{
84
+ ixns: web3.TransactionInstruction[];
85
+ luts: web3.PublicKey[];
86
+ }>;
87
+ getEvents(txSigs: string[]): Promise<any[]>;
88
+ getAccountsForAuthority(group: web3.PublicKey, authority: web3.PublicKey): Promise<web3.PublicKey[]>;
55
89
  }