Skip to content

Commit

Permalink
fix: issue-122
Browse files Browse the repository at this point in the history
  • Loading branch information
fann95 committed Oct 30, 2023
1 parent f5860c8 commit 96ad6c1
Show file tree
Hide file tree
Showing 2 changed files with 99 additions and 7 deletions.
38 changes: 31 additions & 7 deletions contracts/LiquidityBorrowingManager.sol
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,7 @@ contract LiquidityBorrowingManager is
oldBorrowing.dailyRateCollateralBalance,
accLoanRatePerSeconds
);
// Ensure that the collateral balance is greater than or equal to 0
// Ensure the position is under liquidation
(collateralBalance >= 0).revertError(ErrLib.ErrorCode.FORBIDDEN);
// Pick up platform fees from the oldBorrowing's holdToken and add them to the feesOwed
currentFees = _pickUpPlatformFees(oldBorrowing.holdToken, currentFees);
Expand Down Expand Up @@ -447,7 +447,6 @@ contract LiquidityBorrowingManager is
newBorrowing.dailyRateCollateralBalance +=
(collateralAmt - minPayment) *
Constants.COLLATERAL_BALANCE_PRECISION;
//newBorrowing.accLoanRatePerSeconds = oldBorrowing.accLoanRatePerSeconds;
_pay(oldBorrowing.holdToken, msg.sender, VAULT_ADDRESS, collateralAmt + feesDebt);
emit TakeOverDebt(oldBorrowing.borrower, msg.sender, borrowingKey, newBorrowingKey);
}
Expand Down Expand Up @@ -562,11 +561,14 @@ contract LiquidityBorrowingManager is

// Calculate liquidation bonus and adjust fees owed

if (
collateralBalance > 0 &&
(currentFees + borrowing.feesOwed) / Constants.COLLATERAL_BALANCE_PRECISION >
Constants.MINIMUM_AMOUNT
) {
if (collateralBalance > 0) {
uint256 compensation = _calcFeeCompensationUpToMin(
collateralBalance,
currentFees,
borrowing.feesOwed
);
currentFees += compensation;
collateralBalance -= int256(compensation);
liquidationBonus +=
uint256(collateralBalance) /
Constants.COLLATERAL_BALANCE_PRECISION;
Expand Down Expand Up @@ -702,6 +704,28 @@ contract LiquidityBorrowingManager is
liquidationBonus *= times;
}

/**
* @dev Calculates the fee compensation up to the minimum amount.
* @param collateralBalance The current balance of collateral.
* @param currentFees The current fees.
* @param feesOwed The fees owed.
* @return compensation The fee compensation up to the minimum amount.
*/
function _calcFeeCompensationUpToMin(
int256 collateralBalance,
uint256 currentFees,
uint256 feesOwed
) private pure returns (uint256 compensation) {
uint256 minimum = Constants.MINIMUM_AMOUNT * Constants.COLLATERAL_BALANCE_PRECISION;
uint256 total = currentFees + feesOwed;
if (total < minimum) {
compensation = minimum - total;
if (uint256(collateralBalance) < compensation) {
compensation = uint256(collateralBalance);
}
}
}

/**
* @notice Calculates the amount to be repaid in an emergency situation.
* @dev This function removes loans associated with a borrowing key owned by the `msg.sender`.
Expand Down
68 changes: 68 additions & 0 deletions test/WagmiLeverageTests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,74 @@ describe("WagmiLeverageTests", () => {
snapshot_global = await takeSnapshot();
});

it("The token flow should be correct(borrow then repay)", async () => {
const amountWBTC = ethers.utils.parseUnits("0.05", 8); //token0
const deadline = (await time.latest()) + 60;
const minLeverageDesired = 50;
const maxCollateralWBTC = amountWBTC.div(minLeverageDesired);

const loans = [
{
liquidity: nftpos[3].liquidity,
tokenId: nftpos[3].tokenId,
},
];

const swapParams: ApproveSwapAndPay.SwapParamsStruct = {
swapTarget: constants.AddressZero,
swapAmountInDataIndex: 0,
maxGasForCall: 0,
swapData: swapData,
};

const borrowParams: LiquidityBorrowingManager.BorrowParamsStruct = {
internalSwapPoolfee: 500,
saleToken: WETH_ADDRESS,
holdToken: WBTC_ADDRESS,
minHoldTokenOut: amountWBTC,
maxCollateral: maxCollateralWBTC,
externalSwap: swapParams,
loans: loans,
};

//borrow tokens
await borrowingManager.connect(bob).borrow(borrowParams, deadline);

const borrowingKey = await borrowingManager.userBorrowingKeys(bob.address, 0);

let repayParams = {
isEmergency: false,
internalSwapPoolfee: 500,
externalSwap: swapParams,
borrowingKey: borrowingKey,
swapSlippageBP1000: 990, //1%
};

const WBTC: IERC20 = await ethers.getContractAt("IERC20", WBTC_ADDRESS);
const prevBalanceLender = await WBTC.balanceOf(alice.address);
const prevBalance = await WBTC.balanceOf(bob.address);
const prevPlatformsFees = (await borrowingManager.getPlatformsFeesInfo([WBTC_ADDRESS]))[0];

//query amount of collateral available
const borrowingsInfo = await borrowingManager.borrowingsInfo(borrowingKey);
const dailyCollateral = borrowingsInfo.dailyRateCollateralBalance.div(COLLATERAL_BALANCE_PRECISION);
const liquidationBonus = borrowingsInfo.liquidationBonus;
//should be more than 0
expect(dailyCollateral).to.be.gt(0);
expect(liquidationBonus).to.be.gt(0);
//console.log("dailyCollateral", dailyCollateral.toString());

//BOB repay his loan but loose his dailyCollateral even tho it hasn't been a day
await borrowingManager.connect(bob).repay(repayParams, deadline);

const newBalance = await WBTC.balanceOf(bob.address);
const newBalanceLender = await WBTC.balanceOf(alice.address);
const newPlatformsFees = (await borrowingManager.getPlatformsFeesInfo([WBTC_ADDRESS]))[0];
expect(newPlatformsFees).to.be.equal(prevPlatformsFees.add(200));//+20% of MINIMUM_AMOUNT
expect(newBalanceLender).to.be.equal(prevBalanceLender.add(800));//+80% of MINIMUM_AMOUNT
expect(newBalance).to.be.equal(prevBalance.add(liquidationBonus).add(dailyCollateral.sub(1000)));//- MINIMUM_AMOUNT
});

it("LEFT_OUTRANGE_TOKEN_1 borrowing liquidity (long position WBTC zeroForSaleToken = false) will be successful", async () => {
const amountWBTC = ethers.utils.parseUnits("0.05", 8); //token0
const deadline = (await time.latest()) + 60;
Expand Down

0 comments on commit 96ad6c1

Please sign in to comment.