Title: repayWithCollateral will revert because of underflow
Impact
Repayments are always a healthy action on the protocol, and shouldn't revert. Due to this bug, repayment with collateral will revert, preventing users from repaying their debt in certain conditions and improving their loan health.
The bugs simply concerns the line mentioned above, if principalPaid is less than interestPaid the transaction will revert due to underflow. Please also notice when reducing loan balance of a userLoan, it is the intended design to repay the interest off first before reducing the collateral
Recomendation
To fix this, and avoid the underflow, a possible fix would be like this
To showcase the problem we simply made a simple reimplementation of the vulenrable code to showcase the underflow: In this example:
initial depositData.totalAmount = 1000
interestPaid = 150
principalPaid = 100
=> this will revert with an underflow Result:
└─$ forge test --mt test_poc_03 -vv[⠊] Compiling...No files changed, compilation skippedRan 1 test for test/pocs/test_poc.sol:Pocs_3[FAIL. Reason: panic: arithmetic underflow or overflow (0x11)] test_poc_03() (gas: 407)Suite result: FAILED. 0 passed; 1 failed; 0 skipped; finished in 706.78ms (143.02µs CPU time)Ran 1 test suite in 711.03ms (706.78ms CPU time): 0 tests passed, 1 failed, 0 skipped (1 total tests)Failing tests:Encountered 1 failing test in test/pocs/test_poc.sol:Pocs_3[FAIL. Reason: panic: arithmetic underflow or overflow (0x11)] test_poc_03() (gas: 407)Encountered a total of 1 failing tests, 0 tests succeeded
contractPocs_3isTest {// Mock pool structstructPool {uint256 totalAmount; }functionupdatePool(Poolmemory_pool,uint256_principalPaid,uint256_interestPaid) internalpure { _pool.totalAmount -= _principalPaid - _interestPaid; }functiontest_poc_03() public {// Setupuint256 initialTotalAmount =1000;uint256 principalPaid =100;uint256 interestPaid =150; Pool memory pool =Pool(initialTotalAmount);// Test// vm.expectRevert(stdError.arithmeticError);updatePool(pool, principalPaid, interestPaid); }}