Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merge changes from private-contracts repo into develop #950

Merged
merged 13 commits into from
Oct 12, 2023

Conversation

EdNoepel
Copy link
Contributor

@EdNoepel EdNoepel commented Oct 12, 2023

Description of change

High level

Merge changes from private-contracts repository designed to mitigate griefing vector found through bug bounty program, and address issues with liquidations game-theory.

Description of bug or vulnerability and solution

Contract size

~2% reduction in pool contract size.

Pre Change

============ Deployment Bytecode Sizes ============
  ERC721Pool               -  24,478B  (99.60%)
  ERC20Pool                -  23,761B  (96.68%)
  PositionManager          -  18,787B  (76.44%)
  PositionNFTSVG           -  15,257B  (62.08%)
  TakerActions             -  15,146B  (61.63%)
  PoolInfoUtils            -  13,622B  (55.43%)

Post Change

============ Deployment Bytecode Sizes ============
  ERC721Pool               -  24,010B  (97.69%)
  ERC20Pool                -  23,341B  (94.97%)
  PositionManager          -  18,787B  (76.44%)
  TakerActions             -  15,866B  (64.56%)
  PositionNFTSVG           -  15,257B  (62.08%)
  PoolInfoUtils            -  13,288B  (54.07%)

Gas usage

Pre Change

src/ERC20Pool.sol:ERC20Pool contract
Function Name min avg median max # calls
addCollateral 1553 162305 144032 400771 34
addQuoteToken 1950 253028 170017 723088 935
bucketCollateralDust 1152 1948 1152 3099 17
bucketExchangeRate 14696 17221 16006 33332 889
bucketInfo 4571 7308 6173 36833 3134
bucketTake 8184 123958 127809 423264 33
drawDebt 7540 248578 252878 617766 555
kick 6950 553939 619213 773745 56
kickReserveAuction 3974 57147 57400 129779 110
kickerInfo 1304 2390 1304 5304 151
moveQuoteToken 1918 142033 107079 634633 41
removeCollateral 4412 54932 56406 157370 73
removeQuoteToken 4698 69308 62490 621261 431
repayDebt 10042 165664 107530 590635 322
settle 11765 197788 182134 509375 27
take 9175 175718 194245 591333 47
takeReserves 25814 104374 122736 134064 59
src/ERC721Pool.sol:ERC721Pool contract
Function Name min avg median max # calls
addCollateral 23601 314258 303067 970887 9
addQuoteToken 43467 281480 193195 682194 199
bucketInfo 4148 10145 7478 39239 155901
bucketTake 78794 221603 176716 531020 14
bucketTokenIds 1279 1279 1279 1279 38
drawDebt 10720 841261 325808 91976916 175
kick 6950 556558 611749 835049 13
kickReserveAuction 6796 71688 80572 131622 8
kickerInfo 1326 2742 1326 5326 48
moveQuoteToken 45953 53109 46131 67228 6
removeCollateral 3779 65628 63033 167878 18
removeQuoteToken 4830 62275 58923 182722 150
repayDebt 8555 600472 113034 59207740 133
settle 109200 323254 255788 715264 11
take 12160 317870 385349 728012 13
takeReserves 4449 74464 63969 142883 8

Post Change

src/ERC20Pool.sol:ERC20Pool contract
Function Name min avg median max # calls
addCollateral 1553 162272 143653 400771 34
addQuoteToken 1950 255301 172461 723088 921
bucketCollateralDust 1152 1947 1152 3099 17
bucketExchangeRate 14696 17235 16006 33332 886
bucketInfo 4571 7228 6206 36833 3413
bucketTake 8165 112991 107028 397012 34
drawDebt 7442 242913 229782 592550 502
kick 6878 474303 572805 713526 55
kickReserveAuction 4090 47808 51755 100698 107
kickerInfo 1304 2332 1304 5304 140
moveQuoteToken 1918 141583 107168 634633 41
removeCollateral 4412 57077 57314 157370 103
removeQuoteToken 4698 70236 63583 621261 407
repayDebt 9850 192239 121285 589836 296
settle 11765 205911 171570 509375 59
take 9156 184757 184703 569729 42
takeReserves 6714 113142 140256 153184 61
src/ERC721Pool.sol:ERC721Pool contract
Function Name min avg median max # calls
addCollateral 23601 406461 303067 1800710 9
addQuoteToken 43467 279826 215624 682428 185
bucketInfo 4148 9476 7181 39239 111542
bucketTake 98327 193479 136773 508779 13
bucketTokenIds 1279 1279 1279 1279 44
drawDebt 12207 847730 302620 91958312 166
kick 6878 517649 565965 783665 13
kickReserveAuction 6912 57451 64977 104077 8
kickerInfo 1326 2468 1326 5326 42
moveQuoteToken 45953 53109 46131 67228 6
removeCollateral 3779 79748 66745 245092 21
removeQuoteToken 4830 62755 59002 182722 142
repayDebt 8351 682049 117364 59207802 118
settle 108920 332643 268003 714682 15
take 12141 311598 382011 706248 13
takeReserves 4449 82426 63969 164783 8

grandizzy and others added 13 commits June 3, 2023 19:39
* Logging for RewardsManager and PositionManager invariants (#925)

* added logging for positionManager

* added rewards and position logging

* clean up

* updated rewards mapping back to public so tests pass

* how modifier was being called in rewardsPoolHandler

* revised so logging pools is not required when logging positions

* cleanup

* readme cleanup

---------

Co-authored-by: Ian Harvey <iharvey@comcast.net>

* Invariants Improvement: Add multiple pool support in position and rewards manager invariant testing (#927)

* Add multiple pools in position and rewards manager invariant testing

* Fix RW6 regression test

* Fix rewardsClaimed and updateRewardsClaimed in Rewards manager

* Fix compile error

* PR feedback

* Add configurable number of pools for position and rewards manager invariant testing

* Positions Invariants: Multiple positions, transfer positions (#926)

* added randomness

* added the ability to transfer positions

* increased chance of rewards being claimed in handlers

* cleanup

* responded to comments

---------

Co-authored-by: Ian Harvey <iharvey@comcast.net>

* Fuzz test additions (#924)

* Add fuzz test for borrower borrows fuzzed amount and getting kick after some time

* Add fuzz test for take fuzzed amount of collateral from auction

* Add fuzz test for settle with fuzzed pool deposit

* Add fuzz test for add and remove collateral in ERC721Pool

* Fuzzed buckets used in borrow and kick fuzz test

* PR feedback

* Invariant Improvements: Position rewards logging for multiple pools (#931)

* Update position and rewards manager invariant logging for multiple pools

* Fix regression test to run for any token precision and Quote token limits

* PR feedback

* Invariants Improvements: Add Multiple position in single handler in Position (#928)

* Update Position invariants handler to memorialize and redeem multiple positions

* PR feedback

* Add partial random positions redeem in redeem position handler

* Add random time skips between epochs in rewards manager

* Add bucket bankruptcy scenario for rewards manager (#930)

* Add bucket bankruptcy scenario for rewards manager

* Fix evm reverts

* PR feedback

* Update prepare test methods to add position in NFT if there is no position in it

---------

Co-authored-by: Ian Harvey <iharvey@comcast.net>
Co-authored-by: Prateek Gupta <prateek105@users.noreply.github.com>
Copy link
Contributor

@ith-harvey ith-harvey left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

Copy link
Contributor

@mattcushman mattcushman left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

@EdNoepel EdNoepel requested a review from grandizzy October 12, 2023 21:29
@ith-harvey ith-harvey merged commit 5784b62 into develop Oct 12, 2023
3 checks passed
Copy link
Collaborator

@MikeHathaway MikeHathaway left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

ith-harvey added a commit that referenced this pull request Oct 13, 2023
* Logging for RewardsManager and PositionManager invariants (#925)

* added logging for positionManager

* added rewards and position logging

* clean up

* updated rewards mapping back to public so tests pass

* how modifier was being called in rewardsPoolHandler

* revised so logging pools is not required when logging positions

* cleanup

* readme cleanup

---------

Co-authored-by: Ian Harvey <iharvey@comcast.net>

* Invariants Improvement: Add multiple pool support in position and rewards manager invariant testing (#927)

* Add multiple pools in position and rewards manager invariant testing

* Fix RW6 regression test

* Fix rewardsClaimed and updateRewardsClaimed in Rewards manager

* Fix compile error

* PR feedback

* Add configurable number of pools for position and rewards manager invariant testing

* Positions Invariants: Multiple positions, transfer positions (#926)

* added randomness

* added the ability to transfer positions

* increased chance of rewards being claimed in handlers

* cleanup

* responded to comments

---------

Co-authored-by: Ian Harvey <iharvey@comcast.net>

* Fuzz test additions (#924)

* Add fuzz test for borrower borrows fuzzed amount and getting kick after some time

* Add fuzz test for take fuzzed amount of collateral from auction

* Add fuzz test for settle with fuzzed pool deposit

* Add fuzz test for add and remove collateral in ERC721Pool

* Fuzzed buckets used in borrow and kick fuzz test

* PR feedback

* Invariant Improvements: Position rewards logging for multiple pools (#931)

* Update position and rewards manager invariant logging for multiple pools

* Fix regression test to run for any token precision and Quote token limits

* PR feedback

* Invariants Improvements: Add Multiple position in single handler in Position (#928)

* Update Position invariants handler to memorialize and redeem multiple positions

* PR feedback

* Add partial random positions redeem in redeem position handler

* Add random time skips between epochs in rewards manager

* Add bucket bankruptcy scenario for rewards manager (#930)

* Add bucket bankruptcy scenario for rewards manager

* Fix evm reverts

* PR feedback

* Update prepare test methods to add position in NFT if there is no position in it

* Fixed RewardsManager exchangeRate emit (#941)

* stopped updatedExchangeRates emit when the rates are not updated

* removed epoch check in _updateBucketExchangeRates

---------

Co-authored-by: Ian Harvey <iharvey@comcast.net>

* Invariant Improvements: Add settle invariant scenario (#933)

* Add settle invariant scenario

* Reduce Loans and skip time to make undercollateralize

* Reduce time to skip in bucket bankruptcy scenario setup to fix regression tests (#936)

* Update unit test to increase test coverage (#938)

* Add unit tests to check deposits and debt limits in pool (#939)

* Add unit test to check exp function limit

* Add unit tests to check pool deposit and debt limits

* PR cleanup

* Add missing external function calls (#946)

* Update Position Manager unit tests to test against both ERC721 subset Pool and Collection Pool (#945)

* Merge changes from private-contracts repo into develop (#950)

* Merge Develop into Master (#934)

* Logging for RewardsManager and PositionManager invariants (#925)

* added logging for positionManager

* added rewards and position logging

* clean up

* updated rewards mapping back to public so tests pass

* how modifier was being called in rewardsPoolHandler

* revised so logging pools is not required when logging positions

* cleanup

* readme cleanup

---------

Co-authored-by: Ian Harvey <iharvey@comcast.net>

* Invariants Improvement: Add multiple pool support in position and rewards manager invariant testing (#927)

* Add multiple pools in position and rewards manager invariant testing

* Fix RW6 regression test

* Fix rewardsClaimed and updateRewardsClaimed in Rewards manager

* Fix compile error

* PR feedback

* Add configurable number of pools for position and rewards manager invariant testing

* Positions Invariants: Multiple positions, transfer positions (#926)

* added randomness

* added the ability to transfer positions

* increased chance of rewards being claimed in handlers

* cleanup

* responded to comments

---------

Co-authored-by: Ian Harvey <iharvey@comcast.net>

* Fuzz test additions (#924)

* Add fuzz test for borrower borrows fuzzed amount and getting kick after some time

* Add fuzz test for take fuzzed amount of collateral from auction

* Add fuzz test for settle with fuzzed pool deposit

* Add fuzz test for add and remove collateral in ERC721Pool

* Fuzzed buckets used in borrow and kick fuzz test

* PR feedback

* Invariant Improvements: Position rewards logging for multiple pools (#931)

* Update position and rewards manager invariant logging for multiple pools

* Fix regression test to run for any token precision and Quote token limits

* PR feedback

* Invariants Improvements: Add Multiple position in single handler in Position (#928)

* Update Position invariants handler to memorialize and redeem multiple positions

* PR feedback

* Add partial random positions redeem in redeem position handler

* Add random time skips between epochs in rewards manager

* Add bucket bankruptcy scenario for rewards manager (#930)

* Add bucket bankruptcy scenario for rewards manager

* Fix evm reverts

* PR feedback

* Update prepare test methods to add position in NFT if there is no position in it

---------

Co-authored-by: Ian Harvey <iharvey@comcast.net>
Co-authored-by: Prateek Gupta <prateek105@users.noreply.github.com>

* manually merged from private-contracts/immutable-kicks

* eliminated alreadyTaken (drawio needs updating)

* annotated failing unit tests

* new limit to induce testAccruePoolInterestRevertDueToExpLimit revert

* fixed testUpdateInterestTuLimit

* fixed testAccrueInterestNewInterestLimit

* removed alreadyTaken from drawios

* updated drawio-generated html

* merged Prateek's post-merge changes

---------

Co-authored-by: grandizzy <38490174+grandizzy@users.noreply.github.com>
Co-authored-by: Ian Harvey <ith.harvey@gmail.com>
Co-authored-by: Ian Harvey <iharvey@comcast.net>
Co-authored-by: Prateek Gupta <prateek105@users.noreply.github.com>

* Return amount repaid in repayDebt and amount take in take (#947)

* Remove multicall from position manager (#948)

* L2 license grant (#949)

* updated license

* adjustment for public chains

* Pool info utils multicall (#944)

* Add PoolInfoUtilsMulticall contract to call multiple PoolInfoUtils methods in a single call to reduce rpc calls from subgraph

* Add tests for PoolInfoutilsMulticall

* Added comments and code improvements

* altered license

---------

Co-authored-by: Ian Harvey <iharvey@comcast.net>

* removed mention of momp in testPoolInfoUtilsMulticall (#952)

Co-authored-by: Ian Harvey <iharvey@comcast.net>

* resolved compilation warnings and removed unused code (#953)

---------

Co-authored-by: Ian Harvey <iharvey@comcast.net>
Co-authored-by: Prateek Gupta <prateek105@users.noreply.github.com>
Co-authored-by: Ed Noepel <46749157+EdNoepel@users.noreply.github.com>
Co-authored-by: grandizzy <38490174+grandizzy@users.noreply.github.com>
Co-authored-by: Ed Noepel <ed@noepel.net>
@EdNoepel EdNoepel deleted the privatecontracts-merge-develop branch December 5, 2023 12:27
EdNoepel added a commit that referenced this pull request Jan 4, 2024
* Logging for RewardsManager and PositionManager invariants (#925)

* added logging for positionManager

* added rewards and position logging

* clean up

* updated rewards mapping back to public so tests pass

* how modifier was being called in rewardsPoolHandler

* revised so logging pools is not required when logging positions

* cleanup

* readme cleanup

---------

Co-authored-by: Ian Harvey <iharvey@comcast.net>

* Invariants Improvement: Add multiple pool support in position and rewards manager invariant testing (#927)

* Add multiple pools in position and rewards manager invariant testing

* Fix RW6 regression test

* Fix rewardsClaimed and updateRewardsClaimed in Rewards manager

* Fix compile error

* PR feedback

* Add configurable number of pools for position and rewards manager invariant testing

* Positions Invariants: Multiple positions, transfer positions (#926)

* added randomness

* added the ability to transfer positions

* increased chance of rewards being claimed in handlers

* cleanup

* responded to comments

---------

Co-authored-by: Ian Harvey <iharvey@comcast.net>

* Fuzz test additions (#924)

* Add fuzz test for borrower borrows fuzzed amount and getting kick after some time

* Add fuzz test for take fuzzed amount of collateral from auction

* Add fuzz test for settle with fuzzed pool deposit

* Add fuzz test for add and remove collateral in ERC721Pool

* Fuzzed buckets used in borrow and kick fuzz test

* PR feedback

* Invariant Improvements: Position rewards logging for multiple pools (#931)

* Update position and rewards manager invariant logging for multiple pools

* Fix regression test to run for any token precision and Quote token limits

* PR feedback

* Invariants Improvements: Add Multiple position in single handler in Position (#928)

* Update Position invariants handler to memorialize and redeem multiple positions

* PR feedback

* Add partial random positions redeem in redeem position handler

* Add random time skips between epochs in rewards manager

* Add bucket bankruptcy scenario for rewards manager (#930)

* Add bucket bankruptcy scenario for rewards manager

* Fix evm reverts

* PR feedback

* Update prepare test methods to add position in NFT if there is no position in it

* Fixed RewardsManager exchangeRate emit (#941)

* stopped updatedExchangeRates emit when the rates are not updated

* removed epoch check in _updateBucketExchangeRates

---------

Co-authored-by: Ian Harvey <iharvey@comcast.net>

* Invariant Improvements: Add settle invariant scenario (#933)

* Add settle invariant scenario

* Reduce Loans and skip time to make undercollateralize

* Reduce time to skip in bucket bankruptcy scenario setup to fix regression tests (#936)

* Update unit test to increase test coverage (#938)

* Add unit tests to check deposits and debt limits in pool (#939)

* Add unit test to check exp function limit

* Add unit tests to check pool deposit and debt limits

* PR cleanup

* Add missing external function calls (#946)

* Update Position Manager unit tests to test against both ERC721 subset Pool and Collection Pool (#945)

* Merge changes from private-contracts repo into develop (#950)

* Merge Develop into Master (#934)

* Logging for RewardsManager and PositionManager invariants (#925)

* added logging for positionManager

* added rewards and position logging

* clean up

* updated rewards mapping back to public so tests pass

* how modifier was being called in rewardsPoolHandler

* revised so logging pools is not required when logging positions

* cleanup

* readme cleanup

---------

Co-authored-by: Ian Harvey <iharvey@comcast.net>

* Invariants Improvement: Add multiple pool support in position and rewards manager invariant testing (#927)

* Add multiple pools in position and rewards manager invariant testing

* Fix RW6 regression test

* Fix rewardsClaimed and updateRewardsClaimed in Rewards manager

* Fix compile error

* PR feedback

* Add configurable number of pools for position and rewards manager invariant testing

* Positions Invariants: Multiple positions, transfer positions (#926)

* added randomness

* added the ability to transfer positions

* increased chance of rewards being claimed in handlers

* cleanup

* responded to comments

---------

Co-authored-by: Ian Harvey <iharvey@comcast.net>

* Fuzz test additions (#924)

* Add fuzz test for borrower borrows fuzzed amount and getting kick after some time

* Add fuzz test for take fuzzed amount of collateral from auction

* Add fuzz test for settle with fuzzed pool deposit

* Add fuzz test for add and remove collateral in ERC721Pool

* Fuzzed buckets used in borrow and kick fuzz test

* PR feedback

* Invariant Improvements: Position rewards logging for multiple pools (#931)

* Update position and rewards manager invariant logging for multiple pools

* Fix regression test to run for any token precision and Quote token limits

* PR feedback

* Invariants Improvements: Add Multiple position in single handler in Position (#928)

* Update Position invariants handler to memorialize and redeem multiple positions

* PR feedback

* Add partial random positions redeem in redeem position handler

* Add random time skips between epochs in rewards manager

* Add bucket bankruptcy scenario for rewards manager (#930)

* Add bucket bankruptcy scenario for rewards manager

* Fix evm reverts

* PR feedback

* Update prepare test methods to add position in NFT if there is no position in it

---------

Co-authored-by: Ian Harvey <iharvey@comcast.net>
Co-authored-by: Prateek Gupta <prateek105@users.noreply.github.com>

* manually merged from private-contracts/immutable-kicks

* eliminated alreadyTaken (drawio needs updating)

* annotated failing unit tests

* new limit to induce testAccruePoolInterestRevertDueToExpLimit revert

* fixed testUpdateInterestTuLimit

* fixed testAccrueInterestNewInterestLimit

* removed alreadyTaken from drawios

* updated drawio-generated html

* merged Prateek's post-merge changes

---------

Co-authored-by: grandizzy <38490174+grandizzy@users.noreply.github.com>
Co-authored-by: Ian Harvey <ith.harvey@gmail.com>
Co-authored-by: Ian Harvey <iharvey@comcast.net>
Co-authored-by: Prateek Gupta <prateek105@users.noreply.github.com>

* Return amount repaid in repayDebt and amount take in take (#947)

* Remove multicall from position manager (#948)

* L2 license grant (#949)

* updated license

* adjustment for public chains

* Pool info utils multicall (#944)

* Add PoolInfoUtilsMulticall contract to call multiple PoolInfoUtils methods in a single call to reduce rpc calls from subgraph

* Add tests for PoolInfoutilsMulticall

* Added comments and code improvements

* altered license

---------

Co-authored-by: Ian Harvey <iharvey@comcast.net>

* removed mention of momp in testPoolInfoUtilsMulticall (#952)

Co-authored-by: Ian Harvey <iharvey@comcast.net>

* resolved compilation warnings and removed unused code (#953)

* Reuse _isCollateralized method in repayment (#959)

* 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

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

This reverts commit f540c8a75fe58b9fdb8249da33f271a5f0ad335c.

* PR template (#963)

* changed PR template

* commented out example test, as requested in PR review

* Low-lying fruit (#967)

* added a fenwick OOB test

* unit test to prove 0 loan heap insertions don't break anythnig

* test harness for the auction queue and simple unit tests

* comment to resolve Kirill L-07

* removed redundant code per Kirill L-05

* added SafeCasts

* Fix incorrect lup is used to calculate new interest rate in lenderKick (#972)

* correct reserve auction kick timing logic (#974)

* Add debt and collateral settled returns in settle function (#960)

* Return debt and collateral settled from settle method

* Add isBorrowerSettled return in settle method

* Catch interest accrual and update interest overflow (#954)

* Add try catch for interest accrual and update interest method to avoid pool locking

* PR feedback

* Incorrect(Unscaled) deposits are used to check bucket bankruptcy in forgive bad debt (#971)

* Fix incorrect deposits used to check bucket bankruptcy in forgive bad debt

* PR feedback

* Use bucket price for BPF calculation (#970)

* use bucket price in BPF calc where applicable

* fixed unit tests

* revert CRA kick if a liquidation awaits settlement (#977)

* First borrower (#968)

* this did not work; cannot prevent rate from changing after 12 hours

* fixed issue with _updateInterestState

* fixed unit tests

* removed unused test utility

* Contract size mitigation (#979)

* moved inflator state update logic to PoolHelper

* moved flashLoan impl into PoolCommons

* Memorialize borrower threshold price on kick  (#976)

* Memorialize borrower threshold price at time of kick to calculate bpf on take

* Fix tests

* Record borrower threshold price inside _recordAuction method

* Remove redundant conversions

* Fix natspec

* Fix unit tests

* Remove redundant variable

* Borrower with threshold price less than `MIN_PRICE` cannot be kicked. (#973)

* Add test for borrower with tp less than min price cannot be kicked

* Update _isCollateralized method to return borrower is not collateralized if TP < MIN_PRICE and LUP = MIN_PRICE

* Set borrower to be undercollateralized if LUP = MIN_PRICE

* Fix unit tests

* Fix regression test

* Fix regression test

* Optimize stake cost by reducing calls to currentBurnEpoch (#940)

* reduce external calls to burn epoch

* Don't cast epoch

* further reduce gas in stake by casting curBurnEpoch on use

* moved changes off of kirill-L01-dust-test to a fresh branch (#980)

Co-authored-by: Ian Harvey <iharvey@comcast.net>

* Merge rc9 (#1010)

* 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 f540c8a75fe58b9fdb8249da33f271a5f0ad335c.

* added test testSpendOrigFeePushBadDebtToBorrowers test

* cleaned up testStealReservesWithMarginm to match minted balances

* responded to Matts comments

---------

Co-authored-by: Ian Harvey <iharvey@comcast.net>
Co-authored-by: Mike Hathaway <mahathaway93@gmail.com>

* Revert "Remove Settle debt with pool reserves"

This reverts commit 290d6cf6f7baa1fb17a66322faf755b78a4a379c.

* 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 <ed@noepel.net>
Co-authored-by: Ian Harvey <iharvey@comcast.net>
Co-authored-by: mwc <matt@ajna.finance>
Co-authored-by: Ian Harvey <ith.harvey@gmail.com>
Co-authored-by: Mike Hathaway <mahathaway93@gmail.com>

* 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 <mikehathaway@makerdao.com>
Co-authored-by: mwc <matt@ajna.finance>

* 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 <iharvey@comcast.net>

* fix ERC721PoolCollateral tests

* fix borrowRepayDebtFuzzy and additional PM tests

* cleaned up testBorrowAndRepayWith4DecimalQuote

---------

Co-authored-by: Mike <mikehathaway@makerdao.com>
Co-authored-by: Ian Harvey <ith.harvey@gmail.com>
Co-authored-by: Ian Harvey <iharvey@comcast.net>

* 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 <iharvey@comcast.net>

* 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 <iharvey@comcast.net>

* 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 <mikehathaway@makerdao.com>

---------

Co-authored-by: Mike <mikehathaway@makerdao.com>

* 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 <mikehathaway@makerdao.com>

* 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 <matt@ajna.finance>
Co-authored-by: Ed Noepel <46749157+EdNoepel@users.noreply.github.com>
Co-authored-by: Ed Noepel <ed@noepel.net>
Co-authored-by: Mike Hathaway <mahathaway93@gmail.com>
Co-authored-by: Mike <mikehathaway@makerdao.com>
Co-authored-by: Ian Harvey <iharvey@comcast.net>

* 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 <mikehathaway@makerdao.com>

* 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 <matt@ajna.finance>
Co-authored-by: Mike Hathaway <mahathaway93@gmail.com>
Co-authored-by: Mike <mikehathaway@makerdao.com>
Co-authored-by: Ian Harvey <iharvey@comcast.net>
Co-authored-by: grandizzy <grandizzy.the.egg@gmail.com>
Co-authored-by: grandizzy <38490174+grandizzy@users.noreply.github.com>

* 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)

* Pr feedback

* Fix failing unit tests

---------

Co-authored-by: Ed Noepel <46749157+EdNoepel@users.noreply.github.com>
Co-authored-by: Prateek Gupta <prateek105@users.noreply.github.com>
Co-authored-by: Ed Noepel <ed@noepel.net>
Co-authored-by: Ian Harvey <iharvey@comcast.net>
Co-authored-by: mwc <matt@ajna.finance>
Co-authored-by: Mike Hathaway <mahathaway93@gmail.com>
Co-authored-by: prateek105 <prateek@ajna.finance>
Co-authored-by: Mike <mikehathaway@makerdao.com>
Co-authored-by: mattcushman <36414299+mattcushman@users.noreply.github.com>
Co-authored-by: grandizzy <grandizzy.the.egg@gmail.com>
Co-authored-by: grandizzy <38490174+grandizzy@users.noreply.github.com>

* [L-02] Some unit tests are not properly executed
- split priceToIndex and indexToPrice revert tests

* removed several unused errors and one unused event, per Kirill I-03

* eliminated unused TakeLocalVars.factor

* removed unused KickResult.poolDebt

* Remove more unused vars (#1022)

* Remove DrawDebtLocalVars.compensatedCollateral and RepayDebtLocalVars.compensatedCollateral

* remove unused `ConstructTokenURIParams::pool` and `ConstructTokenURIParams::indexes`

* Include 1.04 COLLATERALIZATION_FACTOR (#1021)

* Include 1.04 COLLATERALIZATION_FACTOR
in neutral price used in kicks

* fixed `testDepositTakeAndSettleByBucketTakeSubsetPool`

* fixed testDepositTakeAndSettleByRegularTakeSubsetPool

* Moved `wmul` inside `mulDiv`

* fix position, rewards, and poolInfoUtils tests

* fix pool factory emit; fix borrowAndRepay tests

* updated ERC20PoolBorrowTest, ERC20PoolCollateralTest, and ERC20PoolDebtExceedsDepositTest

* rounding update

* updated ERC20PoolQuoteTokenTest and ERC20PoolPrecisionTest

* Fix ERC721 unit tests

* Fix ERC20PoolLiquidationsArbTakeTest and ERC20PoolLiquidationsDepositTakeTest

* Fix ERC20PoolFactory, ERC20PoolLenderKick and ERC20PoolKick

* Fix ERC20PoolLiquidationSettleFuzzyTest and ERC20PoolLiquidationTakeFuzzyTest

* Fix ERC20PoolLiquidationsMisc

* Fix ERC20PoolLiquidationsLowPriceCollateralTest, ERC20PoolLiquidationsTakeAndRepayAllDebtInPoolTest and PositionManagerERC20PoolTest

* Fix ERC20PoolLiquidationsSettle test

* Fix testTakeWithFlashLoan test

* Fix ERC20PoolLiquidationsTakeTest

* Include COLLATERALIZATION_FACTOR in loanInfo

* Remove redundant code from testTakeAndSettle that was already been tested in other tests

* Update testTakeAndSettle

---------

Co-authored-by: mwc <matt@ajna.finance>
Co-authored-by: Mike <mikehathaway@makerdao.com>
Co-authored-by: Ed Noepel <ed@noepel.net>
Co-authored-by: grandizzy <grandizzy.the.egg@gmail.com>
Co-authored-by: prateek105 <prateek@ajna.finance>

* Kirill [M-07] | Liquidation of positions with bad debt can cause losses for `HPB` depositors (#1024)

- Don’t allow calls to `kickReserveAuction` until all pending auctions are fully settled - revert with AuctionNotCleared if so
- update unit test to cover scenario
- apply consistent style for _revertIfAuctionPriceBelow helper (storage param first)

* Fixed Take event emit for ERC721 pools (#1026)

* fixed emit for take

* Fix testDepositTakeAndSettleByRegularTakeSubsetPool

---------

Co-authored-by: Ian Harvey <iharvey@comcast.net>
Co-authored-by: prateek105 <prateek@ajna.finance>

* removed COLLATERALIZATION_FACTOR where it was not used (#1018)

* removed collateralization_factor where it was not used

* Import missing COLLATERALIZATION_FACTOR

---------

Co-authored-by: Ian Harvey <iharvey@comcast.net>
Co-authored-by: prateek105 <prateek@ajna.finance>

* Address merge-rc9 PR feedback (#1025)

* reuse pendingInflator logic

* better wording

---------

Co-authored-by: prateek105 <prateek@ajna.finance>

* Expand code coverage (#1013)

* 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 f540c8a75fe58b9fdb8249da33f271a5f0ad335c.

* added test testSpendOrigFeePushBadDebtToBorrowers test

* cleaned up testStealReservesWithMarginm to match minted balances

* responded to Matts comments

---------

Co-authored-by: Ian Harvey <iharvey@comcast.net>
Co-authored-by: Mike Hathaway <mahathaway93@gmail.com>

* Revert "Remove Settle debt with pool reserves"

This reverts commit 290d6cf6f7baa1fb17a66322faf755b78a4a379c.

* 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 <ed@noepel.net>
Co-authored-by: Ian Harvey <iharvey@comcast.net>
Co-authored-by: mwc <matt@ajna.finance>
Co-authored-by: Ian Harvey <ith.harvey@gmail.com>
Co-authored-by: Mike Hathaway <mahathaway93@gmail.com>

* 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 <mikehathaway@makerdao.com>
Co-authored-by: mwc <matt@ajna.finance>

* 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 <iharvey@comcast.net>

* fix ERC721PoolCollateral tests

* fix borrowRepayDebtFuzzy and additional PM tests

* cleaned up testBorrowAndRepayWith4DecimalQuote

---------

Co-authored-by: Mike <mikehathaway@makerdao.com>
Co-authored-by: Ian Harvey <ith.harvey@gmail.com>
Co-authored-by: Ian Harvey <iharvey@comcast.net>

* 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 <iharvey@comcast.net>

* 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 <iharvey@comcast.net>

* 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 <mikehathaway@makerdao.com>

---------

Co-authored-by: Mike <mikehathaway@makerdao.com>

* 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 <mikehathaway@makerdao.com>

* 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 <matt@ajna.finance>
Co-authored-by: Ed Noepel <46749157+EdNoepel@users.noreply.github.com>
Co-authored-by: Ed Noepel <ed@noepel.net>
Co-authored-by: Mike Hathaway <mahathaway93@gmail.com>
Co-authored-by: Mike <mikehathaway@makerdao.com>
Co-authored-by: Ian Harvey <iharvey@comcast.net>

* 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 <mikehathaway@makerdao.com>

* 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 <matt@ajna.finance>
Co-authored-by: Mike Hathaway <mahathaway93@gmail.com>
Co-authored-by: Mike <mikehathaway@makerdao.com>
Co-authored-by: Ian Harvey <iharvey@comcast.net>
Co-authored-by: grandizzy <grandizzy.the.egg@gmail.com>
Co-authored-by: grandizzy <38490174+grandizzy@users.noreply.github.com>

* 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)

* full coverage of PermitERC20 and poolInfoUtils

* create liquidation in PoolInfoUtils test (#1015)

---------

Co-authored-by: Ed Noepel <46749157+EdNoepel@users.noreply.github.com>
Co-authored-by: Prateek Gupta <prateek105@users.noreply.github.com>
Co-authored-by: Ed Noepel <ed@noepel.net>
Co-authored-by: Ian Harvey <iharvey@comcast.net>
Co-authored-by: mwc <matt@ajna.finance>
Co-authored-by: Ian Harvey <ith.harvey@gmail.com>
Co-authored-by: prateek105 <prateek@ajna.finance>
Co-authored-by: Mike <mikehathaway@makerdao.com>
Co-authored-by: mattcushman <36414299+mattcushman@users.noreply.github.com>
Co-authored-by: grandizzy <grandizzy.the.egg@gmail.com>
Co-authored-by: grandizzy <38490174+grandizzy@users.noreply.github.com>

* Take high price (#1016)

* 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 f540c8a75fe58b9fdb8249da33f271a5f0ad335c.

* added test testSpendOrigFeePushBadDebtToBorrowers test

* cleaned up testStealReservesWithMarginm to match minted balances

* responded to Matts comments

---------

Co-authored-by: Ian Harvey <iharvey@comcast.net>
Co-authored-by: Mike Hathaway <mahathaway93@gmail.com>

* Revert "Remove Settle debt with pool reserves"

This reverts commit 290d6cf6f7baa1fb17a66322faf755b78a4a379c.

* 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 <ed@noepel.net>
Co-authored-by: Ian Harvey <iharvey@comcast.net>
Co-authored-by: mwc <matt@ajna.finance>
Co-authored-by: Ian Harvey <ith.harvey@gmail.com>
Co-authored-by: Mike Hathaway <mahathaway93@gmail.com>

* 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 <mikehathaway@makerdao.com>
Co-authored-by: mwc <matt@ajna.finance>

* 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 <iharvey@comcast.net>

* fix ERC721PoolCollateral tests

* fix borrowRepayDebtFuzzy and additional PM tests

* cleaned up testBorrowAndRepayWith4DecimalQuote

---------

Co-authored-by: Mike <mikehathaway@makerdao.com>
Co-authored-by: Ian Harvey <ith.harvey@gmail.com>
Co-authored-by: Ian Harvey <iharvey@comcast.net>

* 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 <iharvey@comcast.net>

* 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 <iharvey@comcast.net>

* 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 <mikehathaway@makerdao.com>

---------

Co-authored-by: Mike <mikehathaway@makerdao.com>

* 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 <mikehathaway@makerdao.com>

* 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 <matt@ajna.finance>
Co-authored-by: Ed Noepel <46749157+EdNoepel@users.noreply.github.com>
Co-authored-by: Ed Noepel <ed@noepel.net>
Co-authored-by: Mike Hathaway <mahathaway93@gmail.com>
Co-authored-by: Mike <mikehathaway@makerdao.com>
Co-authored-by: Ian Harvey <iharvey@comcast.net>

* 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 <mikehathaway@makerdao.com>

* 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 <matt@ajna.finance>
Co-authored-by: Mike Hathaway <mahathaway93@gmail.com>
Co-authored-by: Mike <mikehathaway@makerdao.com>
Co-authored-by: Ian Harvey <iharvey@comcast.net>
Co-authored-by: grandizzy <grandizzy.the.egg@gmail.com>
Co-authored-by: grandizzy <38490174+grandizzy@users.noreply.github.com>

* 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)

* initial commit

* cleaned up, its executing

* updated

* rough draft of tests written

* cleaned up examples added collateral asserts

* borrower change not needed in PR

* added new class inside ERC721PoolLiquidationsTake.t.sol

* updated tests to adjust for take event

---------

Co-authored-by: Ed Noepel <46749157+EdNoepel@users.noreply.github.com>
Co-authored-by: Prateek Gupta <prateek105@users.noreply.github.com>
Co-authored-by: Ed Noepel <ed@noepel.net>
Co-authored-by: Ian Harvey <iharvey@comcast.net>
Co-authored-by: mwc <matt@ajna.finance>
Co-authored-by: Mike Hathaway <mahathaway93@gmail.com>
Co-authored-by: prateek105 <prateek@ajna.finance>
Co-authored-by: Mike <mikehathaway@makerdao.com>
Co-authored-by: mattcushman <36414299+mattcushman@users.noreply.github.com>
Co-authored-by: grandizzy <grandizzy.the.egg@gmail.com>
Co-authored-by: grandizzy <38490174+grandizzy@users.noreply.github.com>

* Emit subset hash on pool creation (#1029)

* updated unit tests following merge of PR#1013 (#1030)

* Continuation of #1021 - clear TP naming and improved code descriptions (#1027)

* Continuation of #1021 - better naming and improved code descriptions
- change Loan.thresholdPrice and Liquidation.thresholdPrice to unadjustedThresholdPrice naming in order to reflect Collateral factor not applied to these values
- reflect in var names where max unadjusted threshold price is used (Move/Remove param struct)
- natspec update

- rename MAX_NP_TP_RATIO to MAX_BOND_FACTOR

* clear Tp naming
        - t0DebtToCollateral : ( t0Debt / collateral )
        - debtToCollateral :   ( debt / collateral )
        - t0ThresholdPrice :   ( t0Debt / collateral ) * collateralization factor
        - thresholdPrice :     ( debt / collateral ) * collateralization factor

* Fix HeapTest

* Update LoansInfo and LoanInfo methods to return maxT0DebtToCollateral and t0DebtToCollateral

* Fix unit tests

* Update assertLoans in tests and fix htp in BaseHandler

* Update loansInfo and threshold Price in Loans library

* Rename thresholdPrice to debtToCollateral in assertAuction in tests

* updated zerothresholdprice error to zerodebttocollateral

* removed unused _htp import in pool.sol

* updated invariants to include ZeroDebtToCollateral

* Use SafeCast in Loans library

---------

Co-authored-by: prateek105 <prateek@ajna.finance>
Co-authored-by: Ian Harvey <iharvey@comcast.net>

* Fix unit test (#1034)

* `_revertIfActiveAuctions` helper should revert with `ActiveAuction` error (#1031)

* _revertIfActiveAuctions helper should revert with ActiveAuction error

* Fix comment

* added min protection to restrict underflow on `bucketTake` (#1033)

* added min protection to restrict ability to underflow

* updated repay

---------

Co-authored-by: Ian Harvey <iharvey@comcast.net>

* Calculate reserve auction price using kicked amount (#1032)

* implement reserve auction pricing as originally described in whitepaper

* bug fixes

* wip updating RewardsManager tests

* disable rewards unit tests

* handle 0 bids on reserve auctions

* updated erc721 reserve auction unit tests

* fixed issue bidding on more than the quote token trading increment

* updated new unit test

* added tearDown to testZeroBid

* removed rayToWad

---------

Co-authored-by: Ian Harvey <iharvey@comcast.net>

* Modify computation of quotetoken amount in TakerActions.sol (#1035)

* test_regression_exchange_rate_failure

* Modify computation of quotetoken amount in TakerActions.sol
to compute bond reward accurately for collateral constrained
takes with collateral tokens with decimals != 18.

* Fix tests (#1036)

* updated baseline

---------

Co-authored-by: Ed Noepel <ed@noepel.net>
Co-authored-by: mwc <matt@ajna.finance>
Co-authored-by: grandizzy <38490174+grandizzy@users.noreply.github.com>

* Invariants improvements (#955)

* 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 f540c8a75fe58b9fdb8249da33f271a5f0ad335c.

* added test testSpendOrigFeePushBadDebtToBorrowers test

* cleaned up testStealReservesWithMarginm to match minted balances

* responded to Matts comments

---------

Co-authored-by: Ian Harvey <iharvey@comcast.net>
Co-authored-by: Mike Hathaway <mahathaway93@gmail.com>

* Revert "Remove Settle debt with pool reserves"

This reverts commit 290d6cf6f7baa1fb17a66322faf755b78a4a379c.

* 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 <ed@noepel.net>
Co-authored-by: Ian Harvey <iharvey@comcast.net>
Co-authored-by: mwc <matt@ajna.finance>
Co-authored-by: Ian Harvey <ith.harvey@gmail.com>
Co-authored-by: Mike Hathaway <mahathaway93@gmail.com>

* 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 <mikehathaway@makerdao.com>
Co-authored-by: mwc <matt@ajna.finance>

* 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 <iharvey@comcast.net>

* fix ERC721PoolCollateral tests

* fix borrowRepayDebtFuzzy and additional PM tests

* cleaned up testBorrowAndRepayWith4DecimalQuote

---------

Co-authored-by: Mike <mikehathaway@makerdao.com>
Co-authored-by: Ian Harvey <ith.harvey@gmail.com>
Co-authored…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants