Skip to content

Commit

Permalink
Invariants improvements (#955)
Browse files Browse the repository at this point in the history
* Fix test_regression_failure_A8_5

* Remove repayDebtByThirdParty handler in SettleERC20PoolHandler, as repayment for borrower in auction is restricted

* Add failing regression test_regression_bucket_take_arithmetic_over_underflow

* Fix test_regression_bucket_take_arithmetic_over_underflow

* Invariant RE9 improvement

* Add failing regression test_regression_bucket_take_reserves_failure

* Fix test_regression_bucket_take_reserves_failure

* Add failing regression test_regression_bucket_take_re9_failure

* Move failing regression tests to RegressionTestReservesWith8QuotePrecision12CollateralPrecisionERC20Pool

* Fix test_regression_bucket_take_re9_failure

* Fix regression tests failing due to reserve error margin calculation when auction price is 0

* Universal deposit fee (#983)

* charge fee on all deposit

* unit tests compile

* test harness updates

* working on ERC20PoolQuoteTokenTest

* removed deposit fee cap

* more work on ERC20PoolQuoteTokenTest

* do not charge deposit fee if moving liquidity to higher price

* Eliminate reserves bad debt allocation and add margin to TP  (#962)

* this underflows instead of giving expected revert

* move isCollateralized check after updating borrower collateral

* remove local calculation of encumbered collateral

* trying to properly fix testBorrowRepayPrecision

* resolve rounding issue in fuzz test

* testCollateralization improvements

* updated unit tests for new _collateralization implementation

* more collateralization tests

* Add 1.04 factor in borrower collateralization

* Update nptp ratio to '1 + sqrt(r)/2'

* Remove Settle debt with pool reserves

* Remove 0.995 factor from claimable reserves calculation

* Update bond factor calculation to minimum 0.005

* added testcase where debt exceeds deposit

* updated test so debt exceeds deposit

* allow  up to half of current orig fee to be used to settle bad debt

* updated testTakeAndSettle

* more test fixes

* Enabled settling with all reserves if
 Deposits.treeSum==0 or 72 hrs pass

* cleanup

* Half orig fee res | Matt example (#966)

* added Matts test as proof that attack no longer works on his branch

* Revert "Remove multicall from position manager (#948)" (#961)

This reverts commit f540c8a.

* added test testSpendOrigFeePushBadDebtToBorrowers test

* cleaned up testStealReservesWithMarginm to match minted balances

* responded to Matts comments

---------

Co-authored-by: Ian Harvey <[email protected]>
Co-authored-by: Mike Hathaway <[email protected]>

* Revert "Remove Settle debt with pool reserves"

This reverts commit 290d6cf.

* Update half origination fees reserves settlement time to 144 hours from kickTime

* Fix alignment and extra spaces

* Fix some unit tests

* PR feedback

* Update encumberance and collateralization method in poolInfoUtils

* Fix some unit tests

---------

Co-authored-by: Ed Noepel <[email protected]>
Co-authored-by: Ian Harvey <[email protected]>
Co-authored-by: mwc <[email protected]>
Co-authored-by: Ian Harvey <[email protected]>
Co-authored-by: Mike Hathaway <[email protected]>

* Fix invariant setup

* Fix some unit tests

* ERC20PoolQuoteTokenTest updated

* updated ERC20PoolPurchaseQuoteTokenTest

* Fixed tests in ERC20PoolReserveAuction.t.sol

* updated ERC20PoolBorrowTest and ERC20PoolBorrowFuzzyTest

* Fix ERC20PoolCollateral and ERC20PoolInfoUtils tests

* Fixed ERC20 arbtake and depositTake tests

* Fix ERC20PoolLiquidationsKickTest, ERC20PoolLiquidationKickFuzzyTest and ERC20PoolLiquidationsLenderKickAuctionTest

* updated ERC20PoolMulticallTest

* cleaned up ERC20PoolDebtExceedsDepositTest

* fixed testTakeLoanColConstraintBpfPosNoResidual

* fixed testTakeCallerColConstraintBpfPosNoResidual

* fixed testTakeCallerColConstraintBpfPosResidual

* fixed testTakeCallerColConstraintBpfNegResidual

* fixed testTakeLoanDebtConstraintBpfPosResidual

* fixed testTakeAndSettle

* cleaned up ERC20PoolDebtExceedsDepositTest

* updated ERC20PoolPrecisionTest

* Update ERC20PoolLiquidationsSettleTest

* Update ERC20PoolLiquidationsMisc

* Update ERC20PoolLiquidationSettleFuzzyTest

* Update ERC20PoolLiquidationTakeFuzzyTest

* fixeed revert tests

* ERC20PoolLiquidationsTake -- fixed rest

* Mh update tests (#985)

* fix most position manager tests

* fix additional pm tests

* fix rewards requiredCollateralRewards setup

* fix ClaimRewards tests

* update additional rewards manager tests

* fix additional tests

* more test fixes

* commit wip bankruptcy tests

* fixed testMoveLiquidityToOverwriteBankruptBucket

* fix additional tests

* fix testMoveLiquidityWithDebtInPool

* fix remaining rewards manager tests

---------

Co-authored-by: Mike <[email protected]>
Co-authored-by: mwc <[email protected]>

* Add 1.04 factor in HTP calculations (#987)

* Add 1.04 factor in HTP calculations

* Add COLLATERALIZATION_FACTOR constant in PoolHelpers

* Add collateralization factor in dwatp

* Fix poolPricesInfo

* Update ERC20PoolBorrowFuzzyTest

* Fix some unit tests

* Fix some unit tests

* Fix some unit tests

* Update ERC20PoolTransferLPs

* fix most rewards manager tests

* update remaining rewards manager tests

* update ERC721SubsetPoolBorrowTest and commit wip changes to testMergeOrRemoveERC721Collateral

* updated testSettlePartialDebtSubsetPool (#988)

* updated testSettlePartialDebtSubsetPool

* re-added teardown

---------

Co-authored-by: Ian Harvey <[email protected]>

* fix ERC721PoolCollateral tests

* fix borrowRepayDebtFuzzy and additional PM tests

* cleaned up testBorrowAndRepayWith4DecimalQuote

---------

Co-authored-by: Mike <[email protected]>
Co-authored-by: Ian Harvey <[email protected]>
Co-authored-by: Ian Harvey <[email protected]>

* Fix some unit tests

* Deployment updates for RC8+ releases (#986)

* cherry-picked from master

* updated README

* Fix ERC721PoolLiquidationsTakeTest

* updated ERC721PoolReserveAuctionTest

* updated testMergeOrRemoveERC721Collateral (#989)

Co-authored-by: Ian Harvey <[email protected]>

* updated ERC721PoolPurchaseQuoteTest and fixed bug in ERC721 tearDown

* cleaned up testLiquidationLenderKickAuction, testLiquidationSingleBorrower, testSettleAuctionWithoutTakes

* updated testMoveLiquidityToOverwriteBankruptBucket

* updated PoolHelperTest

* cleaned up asserts in addLiquidity

* update testMoveLiquidityInBankruptBucket_LP_report_179_494

* updated ERC721PoolEMAsTest

* fixed testKickHighThresholdPriceBorrower

* updated testBorrowerInterestCalculationAfterRepayingAllDebtOnce and testBorrowerInterestCalculation

* updated testMultipleBorrowerInterestAccumulation

* Fix regression tests

* updated RE3, fixed _addQuoteToken

* addQuoteToken - return amount added (#993)

* addQuoteToken now returns amount added

* update unit tests to validate return values

* Fix up add liquidity (#992)

* cleaned up addLiquidity() method in ERC20PoolLiquidationsScaled.t.sol

* remove console

---------

Co-authored-by: Ian Harvey <[email protected]>

* fixed issue with test_regression_fenwick_index_2 in non-18-decimal env

* added regression tests for two failing reserves scenarios

* rename tests such that automake runs them with other regression tests

* UnboundedLiquidationPoolHandler bucketTake fix (#994)

* updated UnboundedLiquidationPoolHandler to handle compensated collateral in bucketTake

* cleanup, trap unhandled use case

* settle event now emits actual debt settled rather than t0 amount (#999)

* settle event now emits actual debt settled rather than t0 amount

* updated test_regression_settle_with_reserves

* Updated auctionInfo (#996)

* add thresholdPrice to auctionInfo; update test iterface usages

* temp fix tests

* remove unneeded comment

* Update auction status (#998)

* wip auction status update w/ stack too deep

* update auctionStatus; add auctionInfo method to poolInfoUtils

---------

Co-authored-by: Mike <[email protected]>

---------

Co-authored-by: Mike <[email protected]>

* updated brownie tests, removed obsolete invariant tests (#1001)

* Block addqt above auction price (#997)

* initial commit

* tweaks to Matt's PR to block adding quote token above auction price (#1000)

* reduce cost of reference price assignment

* reduce pool contract size

* fixed testDepositTakeAndSettleByRegularTakeSubsetPool

* fixed tests in ERC20PoolLiquidationsArbTake.t.sol

* fixed tests in ERC20PoolLiquidationsDepositTake.sol

* fixed two more

* updated testDepositTakeAndSettleSubsetPool

* updated testKickAndSettleSubsetPoolFractionalCollateral

* updated testSettleWithDepositFuzzy

* Fixed final tests

* add "AddAboveAuctionPrice" as expected pool error

* implemented invariant A9: reference prices in liquidation queue shall not decrease

* Update assertAuction to use ThresholdPrice from auctionInfo (#1003)

* use auctionInfo thresholdprice instead of recalculating

* fix most tests

* update remaining tests

---------

Co-authored-by: Mike <[email protected]>

* Contract size mitigation (#1004)

* moved debtInfo to PoolCommons, saving 10 bytes

* moved withdrawBonds to KickerActions

* added unit test showing adding qt above auction price reverts

* updated nit spellings

---------

Co-authored-by: mwc <[email protected]>
Co-authored-by: Ed Noepel <[email protected]>
Co-authored-by: Ed Noepel <[email protected]>
Co-authored-by: Mike Hathaway <[email protected]>
Co-authored-by: Mike <[email protected]>
Co-authored-by: Ian Harvey <[email protected]>

* Invariant testing fixes (#1006)

* initial commit

* tweaks to Matt's PR to block adding quote token above auction price (#1000)

* reduce cost of reference price assignment

* reduce pool contract size

* fixed testDepositTakeAndSettleByRegularTakeSubsetPool

* fixed tests in ERC20PoolLiquidationsArbTake.t.sol

* fixed tests in ERC20PoolLiquidationsDepositTake.sol

* fixed two more

* updated testDepositTakeAndSettleSubsetPool

* updated testKickAndSettleSubsetPoolFractionalCollateral

* updated testSettleWithDepositFuzzy

* Fixed final tests

* add "AddAboveAuctionPrice" as expected pool error

* implemented invariant A9: reference prices in liquidation queue shall not decrease

* Update assertAuction to use ThresholdPrice from auctionInfo (#1003)

* use auctionInfo thresholdprice instead of recalculating

* fix most tests

* update remaining tests

---------

Co-authored-by: Mike <[email protected]>

* Contract size mitigation (#1004)

* moved debtInfo to PoolCommons, saving 10 bytes

* moved withdrawBonds to KickerActions

* documented a sample of invariant failures in regression tests

* added unit test showing adding qt above auction price reverts

* fixed _isCollateralized bug not returning true in all 0-debt use cases

* updated nit spellings

* fixed underflow calculating kicker reward

* _repayDebtByThirdParty should check for expected pool errors

* Round down when reward kicker, round up when kicker is penalized
Fix roundings in tests

* update test comments

* fix and enable A9 invariant

---------

Co-authored-by: mwc <[email protected]>
Co-authored-by: Mike Hathaway <[email protected]>
Co-authored-by: Mike <[email protected]>
Co-authored-by: Ian Harvey <[email protected]>
Co-authored-by: grandizzy <[email protected]>
Co-authored-by: grandizzy <[email protected]>

* RC9 suggested improvements (#1005)

* Revert AuctionNotTakeable in same place, load auction kickTime only once from storage

* Calculate ERC721 collateralTaken only once
cosmetize code (read from result struct in local var and reuse)
Results in shrinking a little bit contract sizes

* Read borrower Np Tp ratio from storage only once when kick

* If block style, proper indentation

* Proposed changes to PR #972:
- avoid calculating current LUP twice in lender kick
- change _kick function to accept proposed LUP (for regular kick proposed LUP is current LUP, for lender kick proposed LUP is calculated based on additional debt)
- in both kick cases return current LUP in kick result
- reduce gas costs by saving a Fenwick traversal
- reduce contract size by removing LUP calculation within Pool

* Cosmetic flashloan code changes, PoolCommons.flashLoan doesn't return false but always reverts if flashloan fails

* PR#983 style, remove redundant line

* PR#999 suggested improvement - calculate current settled debt only once and include in settle result for state update

* PR #962 proposed changes:
- get Fenwick deposits only once when settle with reserves
- define constants for min bond factor and max npTp ratio values

* PR #987 proposed improvement:
- add and reuse _htp helper function (instead duplicated maths)

* Continuation of PR #962: (#1008)

- Record settle amount limmit in Liquidtion struct, at the time of kick (that is instead incrementing accumulator in Borrower struct, each time debt is drawn)
- This way accumulator will be reseted when auction is settled
- fix tests

TODO:
- assert Liquidation.t0ReserveSettleAmount in unit tests (_assertAuction), make sure is set to 0 after auction settled and decreased when partial settles done
- update invariant test to check new introduced accumulator

* Misc test fixes (#1009)

* handle another reward rounding error use case

* fix intermittant fuzz test failure - cannot draw debt from liquidity in bucket 7388

* PositionManager should expect AddAboveAuctionPrice, which can happen in moveLiquidity

* Invariant fix: round up quote tokens calculated from rewarded LP (because LP rewarded are calculated in bucketTake as rewarded quote tokens -> LP rounded down)

* Take 1 - invariant code cleanup

* Take 2: reserves and other helpers

* Merge branch 'merge-rc9' into failing-regressions

* Fix pool address in tests

* Take 3 - more changes

* Pr feedback

* Fix failing unit tests

* Fix failing unit tests

* Take 4

* Fix test_regression_rw_reserves_failure_4

* buckettake reserves failure

* Fix test_regression_failure_reserves_on_bucketTake, update Invariant RE9

* Fix _takeAuction

* Fix unit tests

* PR feedback

* Fix bucketIndex in _bucketTake handler

* Add getLoansInfo helper, remove duplicated settle code, more style

* Additional code style and helper use

* Add back Positions tests

* Update TP naming in invariants

---------

Co-authored-by: Ed Noepel <[email protected]>
Co-authored-by: Ed Noepel <[email protected]>
Co-authored-by: Ian Harvey <[email protected]>
Co-authored-by: mwc <[email protected]>
Co-authored-by: Ian Harvey <[email protected]>
Co-authored-by: Mike Hathaway <[email protected]>
Co-authored-by: Mike <[email protected]>
Co-authored-by: mattcushman <[email protected]>
Co-authored-by: grandizzy <[email protected]>
Co-authored-by: grandizzy <[email protected]>
  • Loading branch information
11 people authored Dec 18, 2023
1 parent 59c1b5b commit b826e7f
Show file tree
Hide file tree
Showing 31 changed files with 1,340 additions and 775 deletions.
2 changes: 1 addition & 1 deletion tests/INVARIANTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@
- **RE6**: Reserves are unchanged by removing collateral token from a bucket
- **RE7**: Reserves increase by bond penalty/reward plus borrower penalty on take above TP.
- **RE8**: Reserves increase by bond penalty/reward plus borrower penalty on bucket takes above TP.
- **RE9**: Reserves unchanges by takes and bucket takes below TP.
- **RE9**: Reserves unchanged by takes and bucket takes below TP (at the time of kick).
- **RE10**: Reserves increase by origination fee: max(1 week interest, 0.05% of borrow amount), on draw debt
- **RE11**: Reserves decrease by claimableReserves by kickReserveAuction
- **RE12**: Reserves decrease by amount of reserve used to settle a auction
Expand Down
59 changes: 33 additions & 26 deletions tests/forge/invariants/ERC20Pool/handlers/BasicERC20PoolHandler.sol
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,7 @@ contract BasicERC20PoolHandler is UnboundedBasicERC20PoolHandler, BasicPoolHandl
numberOfCalls['BBasicHandler.pledgeCollateral']++;

// borrower cannot make any action when in auction
(uint256 kickTime,,,,,,,,) = _poolInfo.auctionStatus(address(_pool), _actor);
if (kickTime != 0) return;
if (_getAuctionInfo(_actor).kickTime != 0) return;

// Prepare test phase
uint256 boundedAmount = _prePledgeCollateral(amountToPledge_);
Expand All @@ -92,8 +91,7 @@ contract BasicERC20PoolHandler is UnboundedBasicERC20PoolHandler, BasicPoolHandl
numberOfCalls['BBasicHandler.pullCollateral']++;

// borrower cannot make any action when in auction
(uint256 kickTime,,,,,,,,) = _poolInfo.auctionStatus(address(_pool), _actor);
if (kickTime != 0) return;
if (_getAuctionInfo(_actor).kickTime != 0) return;

// Prepare test phase
uint256 boundedAmount = _prePullCollateral(amountToPull_);
Expand All @@ -110,8 +108,7 @@ contract BasicERC20PoolHandler is UnboundedBasicERC20PoolHandler, BasicPoolHandl
numberOfCalls['BBasicHandler.drawDebt']++;

// borrower cannot make any action when in auction
(uint256 kickTime,,,,,,,,) = _poolInfo.auctionStatus(address(_pool), _actor);
if (kickTime != 0) return;
if (_getAuctionInfo(_actor).kickTime != 0) return;

// Prepare test phase
uint256 boundedAmount = _preDrawDebt(amountToBorrow_);
Expand All @@ -128,8 +125,7 @@ contract BasicERC20PoolHandler is UnboundedBasicERC20PoolHandler, BasicPoolHandl
numberOfCalls['BBasicHandler.repayDebt']++;

// borrower cannot make any action when in auction
(uint256 kickTime,,,,,,,,) = _poolInfo.auctionStatus(address(_pool), _actor);
if (kickTime != 0) return;
if (_getAuctionInfo(_actor).kickTime != 0) return;

// Prepare test phase
uint256 boundedAmount = _preRepayDebt(amountToRepay_);
Expand All @@ -145,47 +141,56 @@ contract BasicERC20PoolHandler is UnboundedBasicERC20PoolHandler, BasicPoolHandl
function _preAddCollateral(
uint256 amountToAdd_
) internal view returns (uint256 boundedAmount_) {
boundedAmount_ = constrictToRange(amountToAdd_, MIN_COLLATERAL_AMOUNT, MAX_COLLATERAL_AMOUNT);
boundedAmount_ = constrictToRange(
amountToAdd_, MIN_COLLATERAL_AMOUNT, MAX_COLLATERAL_AMOUNT
);
}

function _preRemoveCollateral(
uint256 amountToRemove_
) internal returns (uint256 boundedAmount_) {
boundedAmount_ = constrictToRange(amountToRemove_, MIN_COLLATERAL_AMOUNT, MAX_COLLATERAL_AMOUNT);
boundedAmount_ = constrictToRange(
amountToRemove_, MIN_COLLATERAL_AMOUNT, MAX_COLLATERAL_AMOUNT
);

// ensure actor has collateral to remove
(uint256 lpBalanceBefore, ) = _pool.lenderInfo(_lenderBucketIndex, _actor);
if (lpBalanceBefore == 0) _addCollateral(boundedAmount_, _lenderBucketIndex);
if (_getLenderInfo(_lenderBucketIndex, _actor).lpBalance == 0) {
_addCollateral(boundedAmount_, _lenderBucketIndex);
}
}

function _prePledgeCollateral(
uint256 amountToPledge_
) internal view returns (uint256 boundedAmount_) {
boundedAmount_ = constrictToRange(amountToPledge_, _erc20Pool.collateralScale(), MAX_COLLATERAL_AMOUNT);
boundedAmount_ = constrictToRange(
amountToPledge_, _erc20Pool.collateralScale(), MAX_COLLATERAL_AMOUNT
);
}

function _prePullCollateral(
uint256 amountToPull_
) internal view returns (uint256 boundedAmount_) {
boundedAmount_ = constrictToRange(amountToPull_, MIN_COLLATERAL_AMOUNT, MAX_COLLATERAL_AMOUNT);
boundedAmount_ = constrictToRange(
amountToPull_, MIN_COLLATERAL_AMOUNT, MAX_COLLATERAL_AMOUNT
);
}

function _preDrawDebt(
uint256 amountToBorrow_
) internal override returns (uint256 boundedAmount_) {
boundedAmount_ = constrictToRange(amountToBorrow_, MIN_DEBT_AMOUNT, MAX_DEBT_AMOUNT);
boundedAmount_ = constrictToRange(
amountToBorrow_, MIN_DEBT_AMOUNT, MAX_DEBT_AMOUNT
);

// borrower cannot make any action when in auction
(uint256 kickTime, uint256 collateral,,,,,,,) = _poolInfo.auctionStatus(address(_pool), _actor);
if (kickTime != 0) return boundedAmount_;
if (_getAuctionInfo(_actor).kickTime != 0) return boundedAmount_;

// Pre Condition
// 1. borrower's debt should exceed minDebt
// 2. pool needs sufficent quote token to draw debt
// 3. drawDebt should not make borrower under collateralized

// 1. borrower's debt should exceed minDebt
(uint256 debt,, ) = _poolInfo.borrowerInfo(address(_pool), _actor);
(uint256 minDebt, , , ) = _poolInfo.poolUtilizationInfo(address(_pool));

if (boundedAmount_ < minDebt && minDebt < MAX_DEBT_AMOUNT) boundedAmount_ = minDebt + 1;
Expand All @@ -202,27 +207,29 @@ contract BasicERC20PoolHandler is UnboundedBasicERC20PoolHandler, BasicPoolHandl
(uint256 currentPoolDebt, , , ) = _pool.debtInfo();
uint256 nextPoolDebt = currentPoolDebt + boundedAmount_;
uint256 newLup = _priceAt(_pool.depositIndex(nextPoolDebt));
(debt, collateral, ) = _poolInfo.borrowerInfo(address(_pool), _actor);

BorrowerInfo memory borrowerInfo = _getBorrowerInfo(_actor);

// repay debt if borrower becomes undercollateralized with new debt at new lup
if (!_isCollateralized(debt + boundedAmount_, collateral, newLup, _pool.poolType())) {
if (!_isCollateralized(borrowerInfo.debt + boundedAmount_, borrowerInfo.collateral, newLup, _pool.poolType())) {
_repayDebt(type(uint256).max);

(debt, collateral, ) = _poolInfo.borrowerInfo(address(_pool), _actor);
_pullCollateral(collateral);
borrowerInfo = _getBorrowerInfo(_actor);
_pullCollateral(borrowerInfo.collateral);

require(debt == 0, "borrower has debt");
require(borrowerInfo.debt == 0, "borrower has debt");
}
}

function _preRepayDebt(
uint256 amountToRepay_
) internal returns (uint256 boundedAmount_) {
boundedAmount_ = constrictToRange(amountToRepay_, Maths.max(_pool.quoteTokenScale(), MIN_QUOTE_AMOUNT), MAX_QUOTE_AMOUNT);
boundedAmount_ = constrictToRange(
amountToRepay_, Maths.max(_pool.quoteTokenScale(), MIN_QUOTE_AMOUNT), MAX_QUOTE_AMOUNT
);

// ensure actor has debt to repay
(uint256 debt, , ) = PoolInfoUtils(_poolInfo).borrowerInfo(address(_pool), _actor);
if (debt == 0) {
if (_getBorrowerInfo(_actor).debt == 0) {
boundedAmount_ = _preDrawDebt(boundedAmount_);
_drawDebt(boundedAmount_);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

pragma solidity 0.8.18;

import { LiquidationPoolHandler } from '../../base/handlers/LiquidationPoolHandler.sol';
import { BasicERC20PoolHandler } from './BasicERC20PoolHandler.sol';
import { LiquidationPoolHandler } from '../../base/handlers/LiquidationPoolHandler.sol';
import { BasicERC20PoolHandler } from './BasicERC20PoolHandler.sol';

contract LiquidationERC20PoolHandler is LiquidationPoolHandler, BasicERC20PoolHandler {

Expand All @@ -18,7 +18,9 @@ contract LiquidationERC20PoolHandler is LiquidationPoolHandler, BasicERC20PoolHa
}

function _constrictTakeAmount(uint256 amountToTake_) internal view override returns(uint256 boundedAmount_) {
boundedAmount_ = constrictToRange(amountToTake_, MIN_COLLATERAL_AMOUNT, MAX_COLLATERAL_AMOUNT);
boundedAmount_ = constrictToRange(
amountToTake_, MIN_COLLATERAL_AMOUNT, MAX_COLLATERAL_AMOUNT
);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ contract PanicExitERC20PoolHandler is UnboundedLiquidationPoolHandler, Unbounded
_setupLendersAndDeposits(LENDERS);
_setupBorrowersAndLoans(LOANS_COUNT);

( , , uint256 totalLoans) = _pool.loansInfo();
uint256 totalLoans = _getLoansInfo().noOfLoans;
require(totalLoans == LOANS_COUNT, "loans setup failed");

vm.warp(block.timestamp + 100_000 days);
Expand All @@ -56,19 +56,22 @@ contract PanicExitERC20PoolHandler is UnboundedLiquidationPoolHandler, Unbounded
uint256 borrowerIndex_,
uint256 skippedTime_
) external useTimestamps skipTime(skippedTime_) writeLogs {
borrowerIndex_ = constrictToRange(borrowerIndex_, 0, _activeBorrowers.values().length - 1);
borrowerIndex_ = constrictToRange(
borrowerIndex_, 0, _activeBorrowers.values().length - 1
);

_actor = _borrowers[borrowerIndex_];

changePrank(_actor);
(,,, uint256 kickTime,,,,,,) = _pool.auctionInfo(_actor);
if (block.timestamp > kickTime + 72 hours) {
if (block.timestamp > _getAuctionInfo(_actor).kickTime + 72 hours) {
numberOfCalls['BPanicExitPoolHandler.settleDebt']++;
_settleAuction(_actor, numberOfBuckets);
} else {
numberOfCalls['BPanicExitPoolHandler.repayLoan']++;
_repayDebt(type(uint256).max);
}
(, uint256 collateral, ) = _poolInfo.borrowerInfo(address(_pool), _actor);

uint256 collateral = _getBorrowerInfo(_actor).collateral;
_pullCollateral(collateral);

_resetSettledAuction(_actor, borrowerIndex_);
Expand Down Expand Up @@ -98,7 +101,8 @@ contract PanicExitERC20PoolHandler is UnboundedLiquidationPoolHandler, Unbounded

if (takeAuction_) {
vm.warp(block.timestamp + 61 minutes);
( , uint256 auctionedCollateral, ) = _pool.borrowerInfo(borrower);

uint256 auctionedCollateral = _getBorrowerInfo(borrower).collateral;
_takeAuction(borrower, auctionedCollateral, _actor);
_resetSettledAuction(borrower, borrowerIndex_);
}
Expand Down Expand Up @@ -151,20 +155,18 @@ contract PanicExitERC20PoolHandler is UnboundedLiquidationPoolHandler, Unbounded
) external useTimestamps skipTime(skippedTime_) writeLogs {
numberOfCalls['BPanicExitPoolHandler.withdrawBonds']++;

kickerIndex_ = constrictToRange(kickerIndex_, 0, LENDERS - 1);
address kicker = _lenders[kickerIndex_];

(uint256 kickerClaimable, ) = _pool.kickerInfo(kicker);
kickerIndex_ = constrictToRange(kickerIndex_, 0, LENDERS - 1);
address kicker = _lenders[kickerIndex_];

_actor = kicker;
changePrank(_actor);
_withdrawBonds(kicker, kickerClaimable);
_withdrawBonds(kicker, _getKickerInfo(kicker).claimableBond);
}

function settleHeadAuction(
uint256 skippedTime_
) external useTimestamps skipTime(skippedTime_) writeLogs {
(, , , , , , , address headAuction, , ) = _pool.auctionInfo(address(0));
address headAuction = _getAuctionInfo(address(0)).head;
if (headAuction != address(0)) {
_settleAuction(headAuction, 10);
_resetSettledAuction(headAuction, 0);
Expand Down Expand Up @@ -218,8 +220,7 @@ contract PanicExitERC20PoolHandler is UnboundedLiquidationPoolHandler, Unbounded
}

function _resetSettledAuction(address borrower_, uint256 borrowerIndex_) internal {
(,,, uint256 kickTime,,,,,,) = _pool.auctionInfo(borrower_);
if (kickTime == 0) {
if (_getAuctionInfo(borrower_).kickTime == 0) {
if (borrowerIndex_ != 0) _activeBorrowers.remove(borrowerIndex_);
}
}
Expand Down
Loading

0 comments on commit b826e7f

Please sign in to comment.