Skip to content

Commit 2d6bbcb

Browse files
EdNoepelith-harveyIan Harveyprateek105grandizzy
authored
Merge develop to master (#1047)
* 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…
1 parent 4313584 commit 2d6bbcb

File tree

163 files changed

+12857
-14532
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

163 files changed

+12857
-14532
lines changed

.github/pull_request_template.md

+17-30
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,24 @@
1+
## Description
12

2-
<!---
3-
No need to add special tag
4-
src/ & non src/ changes you need the following (that apply):
5-
-->
6-
# Description of change
7-
## High level
8-
* <DESCRIP_OF_CHANGE>
9-
* <DESCRIP_OF_SUBCHANGE>
3+
<!-- Explain what was changed. For example:
4+
_Updated rounding in `removeQuoteToken` to round to token precision._ -->
105

11-
<!---
12-
Add the `Status: Needs Auditor Approval` tags
13-
CHANGES IN /SRC DIR:
14-
- renaming (not retyping or resizing) of variables & methods
15-
- reordering and moving of functions in files
16-
- lite moving of functions accross files
17-
- comments
6+
## Purpose
187

19-
src/ changes you need the following (that apply):
20-
-->
8+
<!-- Explain why the change was made, citing any issues where appropriate. For example:
9+
_Resolves audit issue M-333: Removal of quote token may leave dust amounts._
10+
Or, if the change does not affect deployed contracts: _Resolve rounding issue with invariant E9 to handle tokens with less than 8 decimals._ -->
2111

22-
# Description of bug or vulnerability and solution
23-
* <PARAGRAPH_EXP_OF_VULN_BUG>
24-
* <PARAGRAPH_EXP_OF_HOW_CHANGE_SOLVES_VULN_OR_BUG>
12+
## Impact
2513

26-
# Contract size
27-
## Pre Change
28-
<PASTE_OUTPUT_HERE>
29-
## Post Change
30-
<PASTE_OUTPUT_HERE>
14+
<!-- State technical consequences of the change, whether beneficial or detrimental. For example:
15+
_Small increase in `removeQuoteToken` gas cost._
16+
If the change does not affect deployed contracts, feel free to leave _none_. -->
3117

32-
# Gas usage
33-
## Pre Change
34-
<PASTE_OUTPUT_HERE>
35-
## Post Change
36-
<PASTE_OUTPUT_HERE>
18+
## Tasks
3719

20+
- [ ] Changes to protocol contracts are covered by unit tests executed by CI.
21+
- [ ] Protocol contract size limits have not been exceeded.
22+
- [ ] Gas consumption for impacted transactions have been compared with the target branch, and nontrivial changes cited in the _Impact_ section above.
23+
- [ ] Scope labels have been assigned as appropriate.
24+
- [ ] Invariant tests have been manually executed as appropriate for the nature of the change.

.github/workflows/slither.yml

+6-7
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,11 @@ jobs:
88
with:
99
submodules: recursive
1010

11+
- name: Install Foundry
12+
uses: foundry-rs/foundry-toolchain@v1
13+
with:
14+
version: nightly
15+
1116
- name: Install and set solc version
1217
run: |
1318
pip install solc-select && solc-select install 0.8.18 && solc-select use 0.8.18
@@ -38,12 +43,6 @@ jobs:
3843
continue-on-error: true
3944
id: position-analyzer
4045

41-
- name: Analyze RewardsManager Contract
42-
run: |
43-
slither src/RewardsManager.sol
44-
continue-on-error: true
45-
id: rewards-analyzer
46-
4746
- name: Analyze PoolInfoUtils Contract
4847
run: |
4948
slither src/PoolInfoUtils.sol
@@ -52,7 +51,7 @@ jobs:
5251

5352
- name: Analyze Libraries
5453
run: |
55-
slither src/libraries/external/.
54+
slither src/libraries/external/
5655
continue-on-error: true
5756
id: libraries-analyzer
5857

Makefile

-3
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,6 @@ test-invariant-erc20 :; forge t --mt invariant --nmc ${CONTR
2929
test-invariant-erc721 :; forge t --mt invariant --nmc ${CONTRACT_EXCLUDES} --mc ERC721
3030
test-invariant-position-erc20 :; forge t --mt invariant --nmc ${CONTRACT_EXCLUDES} --mc ERC20PoolPosition
3131
test-invariant-position-erc721 :; forge t --mt invariant --nmc ${CONTRACT_EXCLUDES} --mc ERC721PoolPosition
32-
test-invariant-rewards-erc20 :; forge t --mt invariant --nmc ${CONTRACT_EXCLUDES} --mc ERC20PoolRewards
33-
test-invariant-rewards-erc721 :; forge t --mt invariant --nmc ${CONTRACT_EXCLUDES} --mc ERC721PoolRewards
3432
test-invariant :; forge t --mt ${MT} --nmc RegressionTest
3533
test-invariant-erc20-precision :; ./tests/forge/invariants/test-invariant-erc20-precision.sh
3634
test-invariant-erc721-precision :; ./tests/forge/invariants/test-invariant-erc721-precision.sh
@@ -54,7 +52,6 @@ test-swap-load-erc20 :; FOUNDRY_INVARIANT_SHRINK_SEQUENCE=false RUST
5452
test-regression-all : test-regression-erc20 test-regression-erc721 test-regression-prototech
5553
test-regression-erc20 :; forge t --mt test_regression --mc ERC20 --nmc "RealWorldRegression|Prototech"
5654
test-regression-erc721 :; forge t --mt test_regression --mc ERC721 --nmc "RealWorldRegression|Prototech"
57-
test-regression-rewards :; forge t --mt test_regression --mc Rewards --nmc "RealWorldRegression|Prototech"
5855
test-regression-position :; forge t --mt test_regression --mc Position --nmc "RealWorldRegression|Prototech"
5956
test-regression-prototech :; forge t --mt test_regression --mc Prototech
6057
test-regression-rw :; forge t --mt test_regression --mc RealWorldRegression

README.md

+4-4
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,7 @@ Record these addresses. If Etherscan verification fails on the first try, copy
203203
Failing that, manual verification is possible. Following steps show how to do this on Goerli (chainId 5), using addresses from the example output above.
204204
* Open `broadcast/5/run-latest.json` and find the _"libraries"_ section towards the end of the file.
205205
* Copy/paste the _libraries_ config into the _[profile.default]_ section of `foundry.toml`, replacing the `:` with an `=`.
206-
* Run the following commands, adjusting addresses as appropriate:
206+
* Run the following commands, adjusting addresses as appropriate. _PoolInfoUtilsMulticall_ constructor takes the address of _PoolInfoUtils_. _PositionManager_ constructor takes the factory addresses.
207207
```
208208
forge verify-contract --chain-id 5 --watch 0x14F2474fB5ea9DF82059053c4F85A8C803Ab10C9 ERC20PoolFactory --constructor-args $(cast abi-encode "constructor(address)" ${AJNA_TOKEN})
209209
forge verify-contract --chain-id 5 --watch 0xb0d1c875B240EE9f6C2c3284a31b10f1EC6De7d2 ERC721PoolFactory --constructor-args $(cast abi-encode "constructor(address)" ${AJNA_TOKEN})
@@ -221,15 +221,15 @@ Failing that, manual verification is possible. Following steps show how to do t
221221
222222
Validate the deployment by creating a pool. Set relevant environment variables, and run the following:
223223
```
224-
cast send ${ERC20_POOLFACTORY} "deployPool(address,address,uint256)(address)" \
224+
cast send ${AJNA_ERC20_POOLFACTORY} "deployPool(address,address,uint256)(address)" \
225225
${WBTC_TOKEN} ${DAI_TOKEN} 50000000000000000 \
226226
--from ${DEPLOY_ADDRESS} --keystore ${DEPLOY_KEY}
227227
```
228228
229229
Where did it deploy the pool? Let's find out:
230230
```
231231
export ERC20_NON_SUBSET_HASH=0x2263c4378b4920f0bef611a3ff22c506afa4745b3319c50b6d704a874990b8b2
232-
cast call ${ERC20_POOLFACTORY} "deployedPools(bytes32,address,address)(address)" \
232+
cast call ${AJNA_ERC20_POOLFACTORY} "deployedPools(bytes32,address,address)(address)" \
233233
${ERC20_NON_SUBSET_HASH} ${WBTC_TOKEN} ${DAI_TOKEN}
234234
```
235235
Record the pool address.
@@ -238,6 +238,6 @@ Run an approval to let the contract spend some of your quote token, and then add
238238
```
239239
cast send ${DAI_TOKEN} "approve(address,uint256)" ${WBTC_DAI_POOL} 50000ether \
240240
--from ${DEPLOY_ADDRESS} --keystore ${DEPLOY_KEY}
241-
cast send ${WBTC_DAI_POOL} "addQuoteToken(uint256,uint256)" 100ether 3232 \
241+
cast send ${WBTC_DAI_POOL} "addQuoteToken(uint256,uint256,uint256)" 100ether 3232 $(($(cast block -f timestamp) + 60)) \
242242
--from ${DEPLOY_ADDRESS} --keystore ${DEPLOY_KEY}
243243
```

src/ERC20Pool.sol

+13-11
Original file line numberDiff line numberDiff line change
@@ -221,13 +221,14 @@ contract ERC20Pool is FlashloanablePool, IERC20Pool {
221221
limitIndex_
222222
);
223223

224-
emit RepayDebt(borrowerAddress_, result.quoteTokenToRepay, collateralAmountToPull_, result.newLup);
225-
224+
amountRepaid_ = result.quoteTokenToRepay;
226225
// update in memory pool state struct
227226
poolState.debt = result.poolDebt;
228227
poolState.t0Debt = result.t0PoolDebt;
229228
poolState.collateral = result.poolCollateral;
230229

230+
emit RepayDebt(borrowerAddress_, amountRepaid_, collateralAmountToPull_, result.newLup);
231+
231232
// adjust t0Debt2ToCollateral ratio
232233
_updateT0Debt2ToCollateral(
233234
result.debtPreAction,
@@ -239,12 +240,12 @@ contract ERC20Pool is FlashloanablePool, IERC20Pool {
239240
// update pool interest rate state
240241
_updateInterestState(poolState, result.newLup);
241242

242-
if (result.quoteTokenToRepay != 0) {
243+
if (amountRepaid_ != 0) {
243244
// update pool balances t0 debt state
244245
poolBalances.t0Debt = poolState.t0Debt;
245246

246247
// move amount to repay from sender to pool
247-
_transferQuoteTokenFrom(msg.sender, result.quoteTokenToRepay);
248+
_transferQuoteTokenFrom(msg.sender, amountRepaid_);
248249
}
249250
if (collateralAmountToPull_ != 0) {
250251
// update pool balances pledged collateral state
@@ -253,8 +254,6 @@ contract ERC20Pool is FlashloanablePool, IERC20Pool {
253254
// move collateral from pool to address specified as collateral receiver
254255
_transferCollateral(collateralReceiver_, collateralAmountToPull_);
255256
}
256-
257-
amountRepaid_ = result.quoteTokenToRepay;
258257
}
259258

260259
/*********************************/
@@ -345,7 +344,7 @@ contract ERC20Pool is FlashloanablePool, IERC20Pool {
345344
function settle(
346345
address borrowerAddress_,
347346
uint256 maxDepth_
348-
) external override nonReentrant {
347+
) external override nonReentrant returns (uint256 collateralSettled_, bool isBorrowerSettled_) {
349348
PoolState memory poolState = _accruePoolInterest();
350349

351350
SettleResult memory result = SettlerActions.settlePoolDebt(
@@ -363,6 +362,9 @@ contract ERC20Pool is FlashloanablePool, IERC20Pool {
363362
);
364363

365364
_updatePostSettleState(result, poolState);
365+
366+
collateralSettled_ = result.collateralSettled;
367+
isBorrowerSettled_ = (result.debtPostAction == 0);
366368
}
367369

368370
/**
@@ -401,19 +403,19 @@ contract ERC20Pool is FlashloanablePool, IERC20Pool {
401403

402404
_updatePostTakeState(result, poolState);
403405

404-
_transferCollateral(callee_, result.collateralAmount);
406+
collateralTaken_ = result.collateralAmount;
407+
408+
_transferCollateral(callee_, collateralTaken_);
405409

406410
if (data_.length != 0) {
407411
IERC20Taker(callee_).atomicSwapCallback(
408-
result.collateralAmount / collateralTokenScale,
412+
collateralTaken_ / collateralTokenScale,
409413
result.quoteTokenAmount / poolState.quoteTokenScale,
410414
data_
411415
);
412416
}
413417

414418
_transferQuoteTokenFrom(msg.sender, result.quoteTokenAmount);
415-
416-
collateralTaken_ = result.collateralAmount;
417419
}
418420

419421
/**

src/ERC20PoolFactory.sol

+1-1
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ contract ERC20PoolFactory is PoolDeployer, IERC20PoolFactory {
7575
deployedPools[ERC20_NON_SUBSET_HASH][collateral_][quote_] = pool_;
7676
deployedPoolsList.push(pool_);
7777

78-
emit PoolCreated(pool_);
78+
emit PoolCreated(pool_, ERC20_NON_SUBSET_HASH);
7979

8080
pool.initialize(interestRate_);
8181
}

src/ERC721Pool.sol

+15-15
Original file line numberDiff line numberDiff line change
@@ -236,13 +236,14 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool {
236236
limitIndex_
237237
);
238238

239-
emit RepayDebt(borrowerAddress_, result.quoteTokenToRepay, noOfNFTsToPull_, result.newLup);
240-
239+
amountRepaid_ = result.quoteTokenToRepay;
241240
// update in memory pool state struct
242241
poolState.debt = result.poolDebt;
243242
poolState.t0Debt = result.t0PoolDebt;
244243
poolState.collateral = result.poolCollateral;
245244

245+
emit RepayDebt(borrowerAddress_, amountRepaid_, noOfNFTsToPull_, result.newLup);
246+
246247
// adjust t0Debt2ToCollateral ratio
247248
_updateT0Debt2ToCollateral(
248249
result.debtPreAction,
@@ -257,19 +258,17 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool {
257258
// update pool balances pledged collateral state
258259
poolBalances.pledgedCollateral = poolState.collateral;
259260

260-
if (result.quoteTokenToRepay != 0) {
261+
if (amountRepaid_ != 0) {
261262
// update pool balances t0 debt state
262263
poolBalances.t0Debt = poolState.t0Debt;
263264

264265
// move amount to repay from sender to pool
265-
_transferQuoteTokenFrom(msg.sender, result.quoteTokenToRepay);
266+
_transferQuoteTokenFrom(msg.sender, amountRepaid_);
266267
}
267268
if (noOfNFTsToPull_ != 0) {
268269
// move collateral from pool to address specified as collateral receiver
269270
_transferFromPoolToAddress(collateralReceiver_, borrowerTokenIds[msg.sender], noOfNFTsToPull_);
270271
}
271-
272-
amountRepaid_ = result.quoteTokenToRepay;
273272
}
274273

275274
/*********************************/
@@ -344,7 +343,6 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool {
344343
// Total collateral in buckets meets the requested removal amount, noOfNFTsToRemove_
345344
_transferFromPoolToAddress(msg.sender, bucketTokenIds, noOfNFTsToRemove_);
346345
}
347-
348346
}
349347

350348
/**
@@ -394,7 +392,7 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool {
394392
function settle(
395393
address borrowerAddress_,
396394
uint256 maxDepth_
397-
) external nonReentrant override {
395+
) external nonReentrant override returns (uint256 collateralSettled_, bool isBorrowerSettled_) {
398396
PoolState memory poolState = _accruePoolInterest();
399397

400398
SettleParams memory params = SettleParams({
@@ -417,6 +415,9 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool {
417415

418416
// move token ids from borrower array to pool claimable array if any collateral used to settle bad debt
419417
_rebalanceTokens(params.borrower, result.collateralRemaining);
418+
419+
collateralSettled_ = result.collateralSettled;
420+
isBorrowerSettled_ = (result.debtPostAction == 0);
420421
}
421422

422423
/**
@@ -449,10 +450,11 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool {
449450
_updatePostTakeState(result, poolState);
450451

451452
// transfer rounded collateral from pool to taker
453+
collateralTaken_ = result.collateralAmount / 1e18;
452454
uint256[] memory tokensTaken = _transferFromPoolToAddress(
453455
callee_,
454456
borrowerTokenIds[borrowerAddress_],
455-
result.collateralAmount / 1e18
457+
collateralTaken_
456458
);
457459

458460
uint256 totalQuoteTokenAmount = result.quoteTokenAmount + result.excessQuoteToken;
@@ -473,8 +475,6 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool {
473475

474476
// transfer from pool to borrower the excess of quote tokens after rounding collateral auctioned
475477
if (result.excessQuoteToken != 0) _transferQuoteToken(borrowerAddress_, result.excessQuoteToken);
476-
477-
collateralTaken_ = result.collateralAmount / 1e18;
478478
}
479479

480480
/**
@@ -615,13 +615,13 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool {
615615
/*******************************/
616616

617617
/// @inheritdoc IERC721PoolState
618-
function totalBorrowerTokens(address borrower_) external view override returns(uint256) {
619-
return borrowerTokenIds[borrower_].length;
618+
function getBorrowerTokenIds(address borrower_) external view override returns(uint256[] memory) {
619+
return borrowerTokenIds[borrower_];
620620
}
621621

622622
/// @inheritdoc IERC721PoolState
623-
function totalBucketTokens() external view override returns(uint256) {
624-
return bucketTokenIds.length;
623+
function getBucketTokenIds() external view override returns(uint256[] memory) {
624+
return bucketTokenIds;
625625
}
626626

627627
}

src/ERC721PoolFactory.sol

+1-1
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ contract ERC721PoolFactory is PoolDeployer, IERC721PoolFactory {
8585
deployedPools[subsetHash][collateral_][quote_] = pool_;
8686
deployedPoolsList.push(pool_);
8787

88-
emit PoolCreated(pool_);
88+
emit PoolCreated(pool_, subsetHash);
8989

9090
pool.initialize(tokenIds_, interestRate_);
9191
}

0 commit comments

Comments
 (0)