@carrot-protocol/clend-rpc 0.1.6 → 0.1.7-fe-math-dev-24c809a
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1 -1
- package/dist/index.js +25 -2
- package/dist/index.js.map +1 -1
- package/dist/rpc.js +57 -57
- package/dist/rpc.js.map +1 -1
- package/dist/state.js +11 -11
- package/dist/state.js.map +1 -1
- package/package.json +10 -11
- package/dist/math.d.ts +0 -322
- package/dist/math.js +0 -737
- package/dist/math.js.map +0 -1
package/dist/index.d.ts
CHANGED
|
@@ -4,5 +4,5 @@ export { MockJupiterUtils } from "./mockJupiterUtils";
|
|
|
4
4
|
export { IJupiterUtils, JupiterUtils, SwapInputs, SwapQuote, SwapIxs, } from "./jupiterUtils";
|
|
5
5
|
export * from "./addresses";
|
|
6
6
|
export { BankConfigCompact, ClendGroup, Bank, ClendAccount, FeeState, Balance, newInterestRateConfigCompact, newBankConfigCompact, RiskTier, BankOperationalState, AssetTag, newClendAccountBalance, InterestRateConfigCompact, TOKEN_DECIMALS, TOKEN_PROGRAMS, USDC_MINT, JLP_MINT, } from "./state";
|
|
7
|
-
export * from "./math";
|
|
8
7
|
export * from "./events";
|
|
8
|
+
export * as Common from "@carrot-protocol/clend-common";
|
package/dist/index.js
CHANGED
|
@@ -10,11 +10,33 @@ var __createBinding = (this && this.__createBinding) || (Object.create ? (functi
|
|
|
10
10
|
if (k2 === undefined) k2 = k;
|
|
11
11
|
o[k2] = m[k];
|
|
12
12
|
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
13
18
|
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
19
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
20
|
};
|
|
21
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
22
|
+
var ownKeys = function(o) {
|
|
23
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
24
|
+
var ar = [];
|
|
25
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
26
|
+
return ar;
|
|
27
|
+
};
|
|
28
|
+
return ownKeys(o);
|
|
29
|
+
};
|
|
30
|
+
return function (mod) {
|
|
31
|
+
if (mod && mod.__esModule) return mod;
|
|
32
|
+
var result = {};
|
|
33
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
34
|
+
__setModuleDefault(result, mod);
|
|
35
|
+
return result;
|
|
36
|
+
};
|
|
37
|
+
})();
|
|
16
38
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
exports.JLP_MINT = exports.USDC_MINT = exports.TOKEN_PROGRAMS = exports.TOKEN_DECIMALS = exports.newClendAccountBalance = exports.AssetTag = exports.BankOperationalState = exports.RiskTier = exports.newBankConfigCompact = exports.newInterestRateConfigCompact = exports.JupiterUtils = exports.MockJupiterUtils = exports.Instructions = exports.ClendClient = void 0;
|
|
39
|
+
exports.Common = exports.JLP_MINT = exports.USDC_MINT = exports.TOKEN_PROGRAMS = exports.TOKEN_DECIMALS = exports.newClendAccountBalance = exports.AssetTag = exports.BankOperationalState = exports.RiskTier = exports.newBankConfigCompact = exports.newInterestRateConfigCompact = exports.JupiterUtils = exports.MockJupiterUtils = exports.Instructions = exports.ClendClient = void 0;
|
|
18
40
|
var rpc_1 = require("./rpc");
|
|
19
41
|
Object.defineProperty(exports, "ClendClient", { enumerable: true, get: function () { return rpc_1.ClendClient; } });
|
|
20
42
|
var instructions_1 = require("./instructions");
|
|
@@ -35,6 +57,7 @@ Object.defineProperty(exports, "TOKEN_DECIMALS", { enumerable: true, get: functi
|
|
|
35
57
|
Object.defineProperty(exports, "TOKEN_PROGRAMS", { enumerable: true, get: function () { return state_1.TOKEN_PROGRAMS; } });
|
|
36
58
|
Object.defineProperty(exports, "USDC_MINT", { enumerable: true, get: function () { return state_1.USDC_MINT; } });
|
|
37
59
|
Object.defineProperty(exports, "JLP_MINT", { enumerable: true, get: function () { return state_1.JLP_MINT; } });
|
|
38
|
-
__exportStar(require("./math"), exports);
|
|
39
60
|
__exportStar(require("./events"), exports);
|
|
61
|
+
// re-export clend-common
|
|
62
|
+
exports.Common = __importStar(require("@carrot-protocol/clend-common"));
|
|
40
63
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,6BAAoC;AAA3B,kGAAA,WAAW,OAAA;AACpB,+CAA8C;AAArC,4GAAA,YAAY,OAAA;AACrB,uDAAsD;AAA7C,oHAAA,gBAAgB,OAAA;AACzB,+CAMwB;AAJtB,4GAAA,YAAY,OAAA;AAKd,8CAA4B;AAC5B,iCAkBiB;AAXf,qHAAA,4BAA4B,OAAA;AAC5B,6GAAA,oBAAoB,OAAA;AACpB,iGAAA,QAAQ,OAAA;AACR,6GAAA,oBAAoB,OAAA;AACpB,iGAAA,QAAQ,OAAA;AACR,+GAAA,sBAAsB,OAAA;AAEtB,uGAAA,cAAc,OAAA;AACd,uGAAA,cAAc,OAAA;AACd,kGAAA,SAAS,OAAA;AACT,iGAAA,QAAQ,OAAA;AAEV,2CAAyB;AAEzB,yBAAyB;AACzB,wEAAwD"}
|
package/dist/rpc.js
CHANGED
|
@@ -11,10 +11,10 @@ const spl_token_1 = require("@solana/spl-token");
|
|
|
11
11
|
const utils_1 = require("./utils");
|
|
12
12
|
const addresses_1 = require("./addresses");
|
|
13
13
|
const state_1 = require("./state");
|
|
14
|
-
const
|
|
14
|
+
const clend_common_1 = require("@carrot-protocol/clend-common");
|
|
15
15
|
const jupiterUtils_1 = require("./jupiterUtils");
|
|
16
16
|
const api_1 = require("@jup-ag/api");
|
|
17
|
-
const
|
|
17
|
+
const clend_common_2 = require("@carrot-protocol/clend-common");
|
|
18
18
|
const pyth_solana_receiver_1 = require("@pythnetwork/pyth-solana-receiver");
|
|
19
19
|
const events_1 = require("./events");
|
|
20
20
|
class ClendClient {
|
|
@@ -205,16 +205,16 @@ class ClendClient {
|
|
|
205
205
|
const totalLiabilityShares = (0, utils_1.wrappedI80F48toBigNumber)(data.totalLiabilityShares);
|
|
206
206
|
const liabilityShareValue = Number((0, utils_1.wrappedI80F48toBigNumber)(data.liabilityShareValue));
|
|
207
207
|
const mintDecimals = Number(data.mintDecimals);
|
|
208
|
-
const assetAmount = (0,
|
|
209
|
-
const assetAmountUi = (0,
|
|
210
|
-
const liabilityAmount = (0,
|
|
211
|
-
const liabilityAmountUi = (0,
|
|
212
|
-
const utilizationRate = (0,
|
|
213
|
-
const baseInterestRate = (0,
|
|
214
|
-
const supplyApy = (0,
|
|
215
|
-
const borrowApy = (0,
|
|
208
|
+
const assetAmount = (0, clend_common_1.calculateTotalAssetQuantity)(totalAssetShares, assetShareValue);
|
|
209
|
+
const assetAmountUi = (0, clend_common_1.amountToUi)(assetAmount, mintDecimals);
|
|
210
|
+
const liabilityAmount = (0, clend_common_1.calculateTotalLiabilityQuantity)(totalLiabilityShares, liabilityShareValue);
|
|
211
|
+
const liabilityAmountUi = (0, clend_common_1.amountToUi)(liabilityAmount, mintDecimals);
|
|
212
|
+
const utilizationRate = (0, clend_common_1.calculateBankUtilizationRate)(totalAssetShares, assetShareValue, totalLiabilityShares, liabilityShareValue);
|
|
213
|
+
const baseInterestRate = (0, clend_common_1.calculateBaseInterestRate)(utilizationRate, bankConfig.interestRateConfig.optimalUtilizationRate, bankConfig.interestRateConfig.plateauInterestRate, bankConfig.interestRateConfig.maxInterestRate);
|
|
214
|
+
const supplyApy = (0, clend_common_1.calculateSupplyApy)(utilizationRate, baseInterestRate, bankConfig.interestRateConfig.protocolIrFee, bankConfig.interestRateConfig.insuranceIrFee);
|
|
215
|
+
const borrowApy = (0, clend_common_1.calculateBorrowApy)(baseInterestRate, bankConfig.interestRateConfig.protocolFixedFeeApr, bankConfig.interestRateConfig.insuranceFeeFixedApr);
|
|
216
216
|
const currentTimestamp = Math.floor(Date.now() / 1000);
|
|
217
|
-
const accruedInterest = (0,
|
|
217
|
+
const accruedInterest = (0, clend_common_1.calculateAccruedInterest)(data.lastUpdate, assetAmountUi, liabilityAmountUi, utilizationRate, bankConfig.interestRateConfig, currentTimestamp);
|
|
218
218
|
return {
|
|
219
219
|
key: bank,
|
|
220
220
|
mint: new anchor_1.web3.PublicKey(data.mint),
|
|
@@ -299,12 +299,12 @@ class ClendClient {
|
|
|
299
299
|
}
|
|
300
300
|
// calculate account health factor and leverage
|
|
301
301
|
// uses weighted values of assets and liabilities
|
|
302
|
-
const { healthFactor: healthFactorWeighted, leverage: leverageWeighted } = (0,
|
|
302
|
+
const { healthFactor: healthFactorWeighted, leverage: leverageWeighted } = (0, clend_common_1.calculateHealthFactorAndLeverage)(healthFactorWeightedAssetArgs, healthFactorWeightedLiabilityArgs);
|
|
303
303
|
// calculate account health factor and leverage
|
|
304
304
|
// uses unweighted values of assets and liabilities
|
|
305
|
-
const { healthFactor: healthFactorUnweighted, leverage: leverageUnweighted, } = (0,
|
|
305
|
+
const { healthFactor: healthFactorUnweighted, leverage: leverageUnweighted, } = (0, clend_common_1.calculateHealthFactorAndLeverage)(healthFactorUnweightedAssetArgs, healthFactorUnweightedLiabilityArgs);
|
|
306
306
|
// calculate ltv with maintenance margin
|
|
307
|
-
const ltv = (0,
|
|
307
|
+
const ltv = (0, clend_common_1.calculateLtv)(balances.map((b) => b.assetWeightedMaintValue), balances.map((b) => b.liabilityWeightedMaintValue));
|
|
308
308
|
return {
|
|
309
309
|
key: clendAccount,
|
|
310
310
|
authority: new anchor_1.web3.PublicKey(data.authority),
|
|
@@ -515,9 +515,9 @@ class ClendClient {
|
|
|
515
515
|
weightAsset = bankData.config.assetWeightMaint;
|
|
516
516
|
weightLiab = bankData.config.liabilityWeightMaint;
|
|
517
517
|
// Calculate weighted values for this balance
|
|
518
|
-
currentWeightedAssetsMaint += (0,
|
|
518
|
+
currentWeightedAssetsMaint += (0, clend_common_1.calculateWeightedValue)(balance.assetBalanceUi, balance.price, // Use price from the balance data
|
|
519
519
|
weightAsset);
|
|
520
|
-
currentWeightedLiabilitiesMaint += (0,
|
|
520
|
+
currentWeightedLiabilitiesMaint += (0, clend_common_1.calculateWeightedValue)(balance.liabilityBalanceUi, balance.price, // Use price from the balance data
|
|
521
521
|
weightLiab);
|
|
522
522
|
}
|
|
523
523
|
// Check if the specific collateral and liability balances were found
|
|
@@ -598,7 +598,7 @@ class ClendClient {
|
|
|
598
598
|
throw new Error("Calculated asset amount for liquidation is zero or negative.");
|
|
599
599
|
}
|
|
600
600
|
// Convert the final UI amount to BN for the instruction
|
|
601
|
-
const finalAssetAmount = (0,
|
|
601
|
+
const finalAssetAmount = (0, clend_common_1.uiToAmount)(calculatedAssetAmountUi, assetBankData.mintDecimals);
|
|
602
602
|
utils_1.logger.info("Final Asset Amount to Liquidate", {
|
|
603
603
|
assetAmountUi: calculatedAssetAmountUi,
|
|
604
604
|
});
|
|
@@ -736,22 +736,22 @@ class ClendClient {
|
|
|
736
736
|
const debtBankData = await this.getBank(debtBank);
|
|
737
737
|
const collateralBankData = await this.getBank(collateralBank);
|
|
738
738
|
// Calculate borrow amount based on target leverage
|
|
739
|
-
const depositAmountUI = (0,
|
|
739
|
+
const depositAmountUI = (0, clend_common_1.amountToUi)(depositAmount, collateralDecimals);
|
|
740
740
|
// Get current prices from Jupiter
|
|
741
741
|
const collateralPrice = await this.getOraclePrice(collateralMint);
|
|
742
742
|
const debtPrice = await this.getOraclePrice(debtMint);
|
|
743
743
|
// Calculate collateral value in debt token terms
|
|
744
|
-
const { borrowAmountUi, totalDepositAmountUi } = (0,
|
|
745
|
-
const borrowAmount = (0,
|
|
744
|
+
const { borrowAmountUi, totalDepositAmountUi } = (0, clend_common_1.computeLoopingAmounts)(depositAmountUI, targetLeverage, collateralPrice, debtPrice, 1, 1);
|
|
745
|
+
const borrowAmount = (0, clend_common_1.uiToAmount)(borrowAmountUi, debtDecimals);
|
|
746
746
|
// get origination fee rate
|
|
747
747
|
const originationFeeRate = debtBankData.config.interestRateConfig.protocolOriginationFee;
|
|
748
748
|
// adjust borrow amount for borrowing costs
|
|
749
|
-
const borrowAmountAfterBorrowingCosts = (0,
|
|
749
|
+
const borrowAmountAfterBorrowingCosts = (0, clend_common_1.adjustBorrowForOriginationFee)(borrowAmount, originationFeeRate);
|
|
750
750
|
// 3. Adjust for Slippage (Borrow MORE)
|
|
751
751
|
// Apply slippage adjustment to the amount already adjusted for costs
|
|
752
|
-
const finalBorrowAmount = (0,
|
|
752
|
+
const finalBorrowAmount = (0, clend_common_1.adjustAmountForSlippage)(borrowAmountAfterBorrowingCosts, // Input the cost-adjusted amount
|
|
753
753
|
slippageBps);
|
|
754
|
-
const finalBorrowAmountUi = (0,
|
|
754
|
+
const finalBorrowAmountUi = (0, clend_common_1.amountToUi)(finalBorrowAmount, debtDecimals);
|
|
755
755
|
utils_1.logger.info("depositLeverage params calculated", {
|
|
756
756
|
borrowAmount: borrowAmount.toString(),
|
|
757
757
|
borrowAmountAfterBorrowingCosts: borrowAmountAfterBorrowingCosts.toString(),
|
|
@@ -769,7 +769,7 @@ class ClendClient {
|
|
|
769
769
|
});
|
|
770
770
|
return {
|
|
771
771
|
borrowAmount: finalBorrowAmount,
|
|
772
|
-
totalDepositAmount: (0,
|
|
772
|
+
totalDepositAmount: (0, clend_common_1.uiToAmount)(totalDepositAmountUi, collateralDecimals),
|
|
773
773
|
debtBankData,
|
|
774
774
|
collateralBankData,
|
|
775
775
|
};
|
|
@@ -906,7 +906,7 @@ class ClendClient {
|
|
|
906
906
|
if (withdrawAll) {
|
|
907
907
|
utils_1.logger.info("withdrawLeverage withdrawing all");
|
|
908
908
|
collateralToWithdraw = collateralAmount;
|
|
909
|
-
debtToRepay = (0,
|
|
909
|
+
debtToRepay = (0, clend_common_1.calculateLiabilityInterest)(debtBalance.liabilityShares, debtBankData.liabilityShareValue, debtBankData.borrowApy, debtBankData.lastUpdate.toNumber(), new Date().getTime() / 1000);
|
|
910
910
|
utils_1.logger.info(`calculated debt to repay`, {
|
|
911
911
|
debtToRepayWithInterest: debtToRepay.toString(),
|
|
912
912
|
debtToRepayRaw: debtAmount.toString(),
|
|
@@ -915,7 +915,7 @@ class ClendClient {
|
|
|
915
915
|
else {
|
|
916
916
|
utils_1.logger.info("withdrawLeverage partial withdrawal");
|
|
917
917
|
// For partial withdrawal, calculate debt to maintain leverage
|
|
918
|
-
const withdrawAmountUI = (0,
|
|
918
|
+
const withdrawAmountUI = (0, clend_common_1.amountToUi)(withdrawAmount, collateralDecimals);
|
|
919
919
|
// Get the weights for leverage calculation
|
|
920
920
|
const collateralMaintWeight = collateralBankData.config.assetWeightMaint;
|
|
921
921
|
const debtMaintWeight = debtBankData.config.liabilityWeightMaint;
|
|
@@ -924,7 +924,7 @@ class ClendClient {
|
|
|
924
924
|
debtMaintWeight,
|
|
925
925
|
});
|
|
926
926
|
// Calculate leverage-preserving withdrawal
|
|
927
|
-
const { debtToRepayUi, newCollateralUi, newDebtUi, currentLeverage, newLeverage, } = (0,
|
|
927
|
+
const { debtToRepayUi, newCollateralUi, newDebtUi, currentLeverage, newLeverage, } = (0, clend_common_2.computeWithdrawLeverageAmounts)(collateralAmountUI, debtAmountUI, withdrawAmountUI, collateralPrice, debtPrice, 1, 1);
|
|
928
928
|
utils_1.logger.debug("withdrawLeverage params calculated", {
|
|
929
929
|
debtToRepayUi,
|
|
930
930
|
newCollateralUi,
|
|
@@ -934,12 +934,12 @@ class ClendClient {
|
|
|
934
934
|
});
|
|
935
935
|
// Set the amounts to withdraw and repay
|
|
936
936
|
collateralToWithdraw = withdrawAmount;
|
|
937
|
-
debtToRepay = (0,
|
|
937
|
+
debtToRepay = (0, clend_common_1.uiToAmount)(debtToRepayUi, debtDecimals);
|
|
938
938
|
}
|
|
939
939
|
// add interest accrual buffer to debt to repay
|
|
940
940
|
// for now we do a conservative 120 seconds
|
|
941
941
|
const timeBufferSec = 120;
|
|
942
|
-
debtToRepay = (0,
|
|
942
|
+
debtToRepay = (0, clend_common_1.addInterestAccrualBuffer)(debtToRepay, debtBankData.borrowApy, timeBufferSec);
|
|
943
943
|
utils_1.logger.debug("final calculated amounts", {
|
|
944
944
|
collateralToWithdraw: collateralToWithdraw.toString(),
|
|
945
945
|
debtToRepay: debtToRepay.toString(),
|
|
@@ -1011,11 +1011,11 @@ class ClendClient {
|
|
|
1011
1011
|
if (withdrawAll) {
|
|
1012
1012
|
utils_1.logger.info("WithdrawAll selected");
|
|
1013
1013
|
collateralToWithdraw = collateralAmount;
|
|
1014
|
-
debtToRepay = (0,
|
|
1014
|
+
debtToRepay = (0, clend_common_1.calculateLiabilityInterest)(debtBalance.liabilityShares, debtBankData.liabilityShareValue, debtBankData.borrowApy, debtBankData.lastUpdate.toNumber(), new Date().getTime() / 1000);
|
|
1015
1015
|
// add interest accrual buffer to debt to repay
|
|
1016
1016
|
// for now we do a conservative 120 seconds
|
|
1017
1017
|
const timeBufferSec = 120;
|
|
1018
|
-
debtToRepay = (0,
|
|
1018
|
+
debtToRepay = (0, clend_common_1.addInterestAccrualBuffer)(debtToRepay, debtBankData.borrowApy, timeBufferSec);
|
|
1019
1019
|
utils_1.logger.info(`calculated debt to repay`, {
|
|
1020
1020
|
debtToRepayWithInterest: debtToRepay.toString(),
|
|
1021
1021
|
debtToRepayRaw: debtAmount.toString(),
|
|
@@ -1024,13 +1024,13 @@ class ClendClient {
|
|
|
1024
1024
|
else {
|
|
1025
1025
|
utils_1.logger.info("Calculating partial deleverage for net withdrawal");
|
|
1026
1026
|
// 1. Calculate estimated current debt accurately
|
|
1027
|
-
const estimatedCurrentDebt = (0,
|
|
1028
|
-
const estimatedCurrentDebtUi = (0,
|
|
1029
|
-
const collateralAmountUI = (0,
|
|
1027
|
+
const estimatedCurrentDebt = (0, clend_common_1.calculateLiabilityInterest)(debtBalance.liabilityShares, debtBankData.liabilityShareValue, debtBankData.borrowApy, debtBankData.lastUpdate.toNumber(), Math.floor(Date.now() / 1000));
|
|
1028
|
+
const estimatedCurrentDebtUi = (0, clend_common_1.amountToUi)(estimatedCurrentDebt, debtDecimals);
|
|
1029
|
+
const collateralAmountUI = (0, clend_common_1.amountToUi)(collateralAmount, collateralDecimals);
|
|
1030
1030
|
const collateralValue = collateralAmountUI * collateralPrice;
|
|
1031
1031
|
const estimatedCurrentDebtValue = estimatedCurrentDebtUi * debtPrice;
|
|
1032
1032
|
// 2. Calculate ideal portion of debt to repay (baseDebtToRepay)
|
|
1033
|
-
const desiredNetWithdrawalUi = (0,
|
|
1033
|
+
const desiredNetWithdrawalUi = (0, clend_common_1.amountToUi)(desiredNetWithdraw, collateralDecimals);
|
|
1034
1034
|
const denominator = 1 - estimatedCurrentDebtValue / collateralValue;
|
|
1035
1035
|
if (denominator <= 0) {
|
|
1036
1036
|
throw new Error("Invalid calculation state: denominator non-positive.");
|
|
@@ -1040,11 +1040,11 @@ class ClendClient {
|
|
|
1040
1040
|
? (estimatedCurrentDebtUi / collateralAmountUI) *
|
|
1041
1041
|
idealCollateralToWithdrawUi
|
|
1042
1042
|
: 0;
|
|
1043
|
-
const baseDebtToRepay = (0,
|
|
1043
|
+
const baseDebtToRepay = (0, clend_common_1.uiToAmount)(idealDebtToRepayUi, debtDecimals);
|
|
1044
1044
|
// 3. Calculate final debt target (including future buffer)
|
|
1045
1045
|
const timeBufferSec = 60; // Or pass as parameter
|
|
1046
|
-
const finalDebtToRepay = (0,
|
|
1047
|
-
const finalDebtToRepayUi = (0,
|
|
1046
|
+
const finalDebtToRepay = (0, clend_common_1.addInterestAccrualBuffer)(baseDebtToRepay, debtBankData.borrowApy, timeBufferSec);
|
|
1047
|
+
const finalDebtToRepayUi = (0, clend_common_1.amountToUi)(finalDebtToRepay, debtDecimals);
|
|
1048
1048
|
utils_1.logger.debug("Calculated final debt repay target", {
|
|
1049
1049
|
finalDebtToRepay: finalDebtToRepay.toString(),
|
|
1050
1050
|
});
|
|
@@ -1061,9 +1061,9 @@ class ClendClient {
|
|
|
1061
1061
|
.mul(debtPrice)
|
|
1062
1062
|
.div(collateralPrice);
|
|
1063
1063
|
// Ideal collateral input for the swap (BN)
|
|
1064
|
-
const idealCollateralForSwapBN = (0,
|
|
1064
|
+
const idealCollateralForSwapBN = (0, clend_common_1.uiToAmount)(idealCollateralForSwapUi.toNumber(), collateralDecimals);
|
|
1065
1065
|
// Max collateral input for the swap (BN), using the adjustment function
|
|
1066
|
-
const collateralToSwapMax = (0,
|
|
1066
|
+
const collateralToSwapMax = (0, clend_common_1.adjustAmountForSlippage)(idealCollateralForSwapBN, slippageBps);
|
|
1067
1067
|
utils_1.logger.debug("Calculated max collateral needed for swap", {
|
|
1068
1068
|
collateralToSwapMax: collateralToSwapMax.toString(),
|
|
1069
1069
|
});
|
|
@@ -1152,10 +1152,10 @@ class ClendClient {
|
|
|
1152
1152
|
const collateralPrice = collateralBalance.price;
|
|
1153
1153
|
const debtPrice = debtBalance.price;
|
|
1154
1154
|
// Estimate current debt including accrued interest
|
|
1155
|
-
const estimatedCurrentDebt = (0,
|
|
1155
|
+
const estimatedCurrentDebt = (0, clend_common_1.calculateLiabilityInterest)(
|
|
1156
1156
|
// Using user's function name
|
|
1157
1157
|
debtBalance.liabilityShares, debtBankData.liabilityShareValue, debtBankData.borrowApy, debtBankData.lastUpdate.toNumber(), Math.floor(Date.now() / 1000));
|
|
1158
|
-
const estimatedCurrentDebtUi = (0,
|
|
1158
|
+
const estimatedCurrentDebtUi = (0, clend_common_1.amountToUi)(estimatedCurrentDebt, debtDecimals);
|
|
1159
1159
|
utils_1.logger.debug("Estimated current state", {
|
|
1160
1160
|
collateralAmountUI,
|
|
1161
1161
|
estimatedCurrentDebtUi,
|
|
@@ -1164,11 +1164,11 @@ class ClendClient {
|
|
|
1164
1164
|
});
|
|
1165
1165
|
// Calculate current leverage (using notional/unweighted for consistency with compute function)
|
|
1166
1166
|
// Use estimatedCurrentDebtUi for accuracy
|
|
1167
|
-
const currentLeverage = (0,
|
|
1167
|
+
const currentLeverage = (0, clend_common_1.calculateWeightedLeverage)(collateralAmountUI, collateralPrice, 1, estimatedCurrentDebtUi, // Use estimated current debt
|
|
1168
1168
|
debtPrice, 1);
|
|
1169
1169
|
utils_1.logger.debug("Calculated current leverage", { currentLeverage });
|
|
1170
1170
|
// Calculate the IDEAL deltas based on estimated current state
|
|
1171
|
-
const { collateralDelta: idealCollateralDeltaUi, debtDelta: idealDebtDeltaUi, isIncrease, } = (0,
|
|
1171
|
+
const { collateralDelta: idealCollateralDeltaUi, debtDelta: idealDebtDeltaUi, isIncrease, } = (0, clend_common_1.computeAdjustLeverageAmounts)(collateralAmountUI, estimatedCurrentDebtUi, // Use estimated current debt
|
|
1172
1172
|
collateralPrice, debtPrice, currentLeverage, targetLeverage, 1, 1);
|
|
1173
1173
|
utils_1.logger.debug("Ideal deltas calculated", {
|
|
1174
1174
|
idealCollateralDeltaUi,
|
|
@@ -1187,16 +1187,16 @@ class ClendClient {
|
|
|
1187
1187
|
}
|
|
1188
1188
|
else {
|
|
1189
1189
|
// 1. Convert ideal UI delta to BN
|
|
1190
|
-
const idealAdditionalDebtAmount = (0,
|
|
1190
|
+
const idealAdditionalDebtAmount = (0, clend_common_1.uiToAmount)(idealDebtDeltaUi, debtDecimals);
|
|
1191
1191
|
// 2. Adjust for origination fee
|
|
1192
1192
|
const originationFeeRate = debtBankData.config.interestRateConfig.protocolOriginationFee;
|
|
1193
|
-
const additionalDebtAfterFee = (0,
|
|
1193
|
+
const additionalDebtAfterFee = (0, clend_common_1.adjustBorrowForOriginationFee)(idealAdditionalDebtAmount, originationFeeRate);
|
|
1194
1194
|
// 3. Adjust for slippage (borrow MORE)
|
|
1195
|
-
const finalAdditionalDebt = (0,
|
|
1195
|
+
const finalAdditionalDebt = (0, clend_common_1.adjustAmountForSlippage)(
|
|
1196
1196
|
// Use renamed function
|
|
1197
1197
|
additionalDebtAfterFee, slippageBps);
|
|
1198
1198
|
// 4. Convert final adjusted BN back to UI units for return
|
|
1199
|
-
finalDebtDeltaUi = (0,
|
|
1199
|
+
finalDebtDeltaUi = (0, clend_common_1.amountToUi)(finalAdditionalDebt, debtDecimals);
|
|
1200
1200
|
utils_1.logger.debug("Debt delta adjustments applied (Increase)", {
|
|
1201
1201
|
idealDebtDeltaUi,
|
|
1202
1202
|
idealAdditionalDebtAmount: idealAdditionalDebtAmount.toString(),
|
|
@@ -1216,13 +1216,13 @@ class ClendClient {
|
|
|
1216
1216
|
}
|
|
1217
1217
|
else {
|
|
1218
1218
|
// 1. Convert ideal UI delta (amount to repay) to BN
|
|
1219
|
-
const baseDebtToRepay = (0,
|
|
1219
|
+
const baseDebtToRepay = (0, clend_common_1.uiToAmount)(idealDebtDeltaUi, debtDecimals);
|
|
1220
1220
|
const timeBufferSec = 60;
|
|
1221
1221
|
// 2. Add future interest buffer using addInterestAccrualBuffer
|
|
1222
|
-
const finalDebtToRepayTargetBN = (0,
|
|
1222
|
+
const finalDebtToRepayTargetBN = (0, clend_common_1.addInterestAccrualBuffer)(
|
|
1223
1223
|
// Using user's function name
|
|
1224
1224
|
baseDebtToRepay, debtBankData.borrowApy, timeBufferSec);
|
|
1225
|
-
finalDebtDeltaUi = (0,
|
|
1225
|
+
finalDebtDeltaUi = (0, clend_common_1.amountToUi)(finalDebtToRepayTargetBN, debtDecimals); // This is the final debt change target
|
|
1226
1226
|
utils_1.logger.debug("Debt delta adjustments applied (Decrease)", {
|
|
1227
1227
|
idealDebtDeltaUi,
|
|
1228
1228
|
baseDebtToRepay: baseDebtToRepay.toString(),
|
|
@@ -1242,13 +1242,13 @@ class ClendClient {
|
|
|
1242
1242
|
.mul(debtPrice)
|
|
1243
1243
|
.div(collateralPrice);
|
|
1244
1244
|
// Ideal collateral input for the swap (BN)
|
|
1245
|
-
const idealCollateralForSwapBN = (0,
|
|
1245
|
+
const idealCollateralForSwapBN = (0, clend_common_1.uiToAmount)(idealCollateralForSwapUi.toNumber(), collateralDecimals);
|
|
1246
1246
|
// Max collateral needed for swap (BN), using the adjustment function
|
|
1247
|
-
const collateralToSwapMax = (0,
|
|
1247
|
+
const collateralToSwapMax = (0, clend_common_1.adjustAmountForSlippage)(
|
|
1248
1248
|
// Use renamed function
|
|
1249
1249
|
idealCollateralForSwapBN, slippageBps);
|
|
1250
1250
|
// This collateral amount is the change needed (it will be withdrawn)
|
|
1251
|
-
finalCollateralDeltaUi = (0,
|
|
1251
|
+
finalCollateralDeltaUi = (0, clend_common_1.amountToUi)(collateralToSwapMax, collateralDecimals);
|
|
1252
1252
|
utils_1.logger.debug("Collateral delta recalculated for swap (Decrease)", {
|
|
1253
1253
|
finalDebtDeltaUi,
|
|
1254
1254
|
idealCollateralForSwapUi: idealCollateralForSwapUi.toString(),
|
|
@@ -1323,7 +1323,7 @@ class ClendClient {
|
|
|
1323
1323
|
if (isIncrease) {
|
|
1324
1324
|
utils_1.logger.info("Building instructions for increasing leverage");
|
|
1325
1325
|
// Use the finalDebtDeltaUi passed in (already adjusted)
|
|
1326
|
-
const additionalDebtAmount = (0,
|
|
1326
|
+
const additionalDebtAmount = (0, clend_common_1.uiToAmount)(finalDebtDeltaUi, debtBankData.mintDecimals);
|
|
1327
1327
|
utils_1.logger.debug("additionalDebtAmount to borrow (final adjusted)", {
|
|
1328
1328
|
additionalDebtAmount: additionalDebtAmount.toString(),
|
|
1329
1329
|
});
|
|
@@ -1361,9 +1361,9 @@ class ClendClient {
|
|
|
1361
1361
|
// Decreasing Leverage
|
|
1362
1362
|
utils_1.logger.info("Building instructions for decreasing leverage");
|
|
1363
1363
|
// Use the finalDebtDeltaUi passed in (already includes future buffer)
|
|
1364
|
-
const finalDebtToRepayBN = (0,
|
|
1364
|
+
const finalDebtToRepayBN = (0, clend_common_1.uiToAmount)(finalDebtDeltaUi, debtBankData.mintDecimals);
|
|
1365
1365
|
// Use the finalCollateralDeltaUi passed in (already includes slippage adjustment for swap)
|
|
1366
|
-
const finalCollateralToWithdrawBN = (0,
|
|
1366
|
+
const finalCollateralToWithdrawBN = (0, clend_common_1.uiToAmount)(finalCollateralDeltaUi, collateralBankData.mintDecimals);
|
|
1367
1367
|
utils_1.logger.debug("Final amounts for decrease operation (Native)", {
|
|
1368
1368
|
finalDebtToRepayBN: finalDebtToRepayBN.toString(),
|
|
1369
1369
|
finalCollateralToWithdrawBN: finalCollateralToWithdrawBN.toString(),
|