From b991b42c7f6c7cc127de07999cfad86a9a6ce685 Mon Sep 17 00:00:00 2001 From: grandizzy Date: Tue, 18 Apr 2023 12:26:07 +0300 Subject: [PATCH 01/11] Base contracts forge docs --- src/base/FlashloanablePool.sol | 20 +- src/base/PermitERC721.sol | 33 ++- src/base/Pool.sol | 137 +++++----- src/base/PoolDeployer.sol | 11 +- .../pool/commons/IPoolBorrowerActions.sol | 6 +- .../pool/commons/IPoolDerivedState.sol | 11 +- .../pool/commons/IPoolImmutables.sol | 8 +- .../pool/commons/IPoolKickerActions.sol | 24 +- .../pool/commons/IPoolLPActions.sol | 76 +++--- .../pool/commons/IPoolLenderActions.sol | 56 ++-- src/interfaces/pool/commons/IPoolState.sol | 242 +++++++++--------- .../pool/commons/IPoolTakerActions.sol | 10 +- 12 files changed, 333 insertions(+), 301 deletions(-) diff --git a/src/base/FlashloanablePool.sol b/src/base/FlashloanablePool.sol index 53a109a97..069784383 100644 --- a/src/base/FlashloanablePool.sol +++ b/src/base/FlashloanablePool.sol @@ -10,9 +10,9 @@ import { IERC3156FlashBorrower } from '../interfaces/pool/IERC3156FlashBorrower. /** * @title Flashloanable Pool Contract - * @notice Pool contract with IERC3156 flash loans capabilities. - * @notice No fee is charged for taking flash loans from pool. - * @notice Flash loans can be taking in ERC20 quote and ERC20 collateral tokens. + * @notice Pool contract with `IERC3156` flashloans capabilities. + * @notice No fee is charged for taking flashloans from pool. + * @notice Flashloans can be taking in `ERC20` quote and `ERC20` collateral tokens. */ abstract contract FlashloanablePool is Pool { using SafeERC20 for IERC20; @@ -20,10 +20,10 @@ abstract contract FlashloanablePool is Pool { /** * @notice Called by flashloan borrowers to borrow liquidity which must be repaid in the same transaction. * @param receiver_ Address of the contract which implements the appropriate interface to receive tokens. - * @param token_ Address of the ERC20 token caller wants to borrow. + * @param token_ Address of the `ERC20` token caller wants to borrow. * @param amount_ The denormalized amount (dependent upon token precision) of tokens to borrow. * @param data_ User-defined calldata passed to the receiver. - * @return success_ True if flashloan was successful. + * @return success_ `True` if flashloan was successful. */ function flashLoan( IERC3156FlashBorrower receiver_, @@ -59,7 +59,7 @@ abstract contract FlashloanablePool is Pool { } /** - * @notice Returns 0, as no fee is charged for flashloans. + * @notice Returns `0`, as no fee is charged for flashloans. */ function flashFee( address token_, @@ -71,7 +71,7 @@ abstract contract FlashloanablePool is Pool { /** * @notice Returns the amount of tokens available to be lent. - * @param token_ Address of the ERC20 token to be lent. + * @param token_ Address of the `ERC20` token to be lent. * @return maxLoan_ The amount of `token_` that can be lent. */ function maxFlashLoan( @@ -81,10 +81,10 @@ abstract contract FlashloanablePool is Pool { } /** - * @notice Returns true if pool allows flashloans for given token address, false otherwise. + * @notice Returns `true` if pool allows flashloans for given token address, `false` otherwise. * @dev Allows flashloans for quote token, overriden in pool implementation to allow flashloans for other tokens. - * @param token_ Address of the ERC20 token to be lent. - * @return True if token can be flashloaned, false otherwise. + * @param token_ Address of the `ERC20` token to be lent. + * @return `True` if token can be flashloaned, `false` otherwise. */ function _isFlashloanSupported( address token_ diff --git a/src/base/PermitERC721.sol b/src/base/PermitERC721.sol index 4d4c3acbe..a92acaf31 100644 --- a/src/base/PermitERC721.sol +++ b/src/base/PermitERC721.sol @@ -6,7 +6,14 @@ import { IERC1271 } from '@openzeppelin/contracts/interfaces/IERC1271.sol'; import { ERC721 } from '@openzeppelin/contracts/token/ERC721/ERC721.sol'; import { Address } from '@openzeppelin/contracts/utils/Address.sol'; + +/** + * @dev Interface for token permits for ERC-721 + */ interface IPermit { + /** + * @notice `EIP-4494` permit to approve by way of owner signature. + */ function permit( address spender_, uint256 tokenId_, uint256 deadline_, uint8 v_, bytes32 r_, bytes32 s_ ) external; @@ -14,7 +21,7 @@ interface IPermit { /** * @notice https://soliditydeveloper.com/erc721-permit - * @notice Functionality to enable EIP-4494 permit calls as part of interactions with Position NFTs + * @notice Functionality to enable `EIP-4494` permit calls as part of interactions with Position `NFT`s * @dev spender https://eips.ethereum.org/EIPS/eip-4494 */ abstract contract PermitERC721 is ERC721, IPermit { @@ -32,7 +39,7 @@ abstract contract PermitERC721 is ERC721, IPermit { bytes32 public constant PERMIT_TYPEHASH = 0x49ecf333e5b8c95c40fdafc95c1ad136e8914a8fb55e9dc8bb01eaa83a2df9ad; - /** @notice Computes the nameHash and versionHash based upon constructor input */ + /** @notice Computes the `nameHash` and `versionHash` based upon constructor input */ constructor( string memory name_, string memory symbol_, string memory version_ ) ERC721(name_, symbol_) { @@ -41,8 +48,8 @@ abstract contract PermitERC721 is ERC721, IPermit { } /** - * @notice Calculate the EIP-712 compliant DOMAIN_SEPERATOR for ledgible signature encoding - * @return The bytes32 domain separator of Position NFTs + * @notice Calculate the `EIP-712` compliant `DOMAIN_SEPERATOR` for ledgible signature encoding. + * @return The `bytes32` domain separator of Position `NFT`s. */ function DOMAIN_SEPARATOR() public view returns (bytes32) { return @@ -59,13 +66,13 @@ abstract contract PermitERC721 is ERC721, IPermit { } /** - * @notice Called by a NFT owner to enable a third party spender to interact with their NFT - * @param spender_ The address of the third party who will execute the transaction involving an owners NFT - * @param tokenId_ The id of the NFT being interacted with - * @param deadline_ The unix timestamp by which the permit must be called - * @param v_ Component of secp256k1 signature - * @param r_ Component of secp256k1 signature - * @param s_ Component of secp256k1 signature + * @notice Called by a `NFT` owner to enable a third party spender to interact with their `NFT`. + * @param spender_ The address of the third party who will execute the transaction involving an owners `NFT`. + * @param tokenId_ The id of the `NFT` being interacted with. + * @param deadline_ The unix timestamp by which the permit must be called. + * @param v_ Component of `secp256k1` signature. + * @param r_ Component of `secp256k1` signature. + * @param s_ Component of `secp256k1` signature. */ function permit( address spender_, uint256 tokenId_, uint256 deadline_, uint8 v_, bytes32 r_, bytes32 s_ @@ -106,8 +113,8 @@ abstract contract PermitERC721 is ERC721, IPermit { } /** - * @dev Gets the current chain ID - * @return chainId_ The current chain ID + * @dev Gets the current chain id + * @return chainId_ The current chain id */ function _chainId() internal view returns (uint256 chainId_) { assembly { diff --git a/src/base/Pool.sol b/src/base/Pool.sol index d07088c4e..a35da401d 100644 --- a/src/base/Pool.sol +++ b/src/base/Pool.sol @@ -67,7 +67,7 @@ import { PoolCommons } from '../libraries/external/PoolCommons.sol'; /** * @title Pool Contract - * @dev Base contract and entrypoint for commong logic of both ERC20 and ERC721 pools. + * @dev Base contract and entrypoint for commong logic of both `ERC20` and `ERC721` pools. */ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { @@ -97,13 +97,16 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { PoolBalancesState internal poolBalances; ReserveAuctionState internal reserveAuction; - mapping(uint256 => Bucket) internal buckets; // deposit index -> bucket + /// @dev deposit index -> bucket mapping + mapping(uint256 => Bucket) internal buckets; bool internal isPoolInitialized; - mapping(address => mapping(address => mapping(uint256 => uint256))) private _lpAllowances; // owner address -> new owner address -> deposit index -> allowed amount + /// @dev owner address -> new owner address -> deposit index -> allowed amount mapping + mapping(address => mapping(address => mapping(uint256 => uint256))) private _lpAllowances; - mapping(address => mapping(address => bool)) public override approvedTransferors; // owner address -> transferor address -> approved flag + /// @dev owner address -> transferor address -> approved flag mapping + mapping(address => mapping(address => bool)) public override approvedTransferors; /******************/ /*** Immutables ***/ @@ -140,23 +143,23 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { /// @inheritdoc IPoolLenderActions function addQuoteToken( - uint256 quoteTokenAmountToAdd_, + uint256 amount_, uint256 index_, uint256 expiry_ - ) external override nonReentrant returns (uint256 bucketLPs_) { + ) external override nonReentrant returns (uint256 bucketLP_) { _revertOnExpiry(expiry_); PoolState memory poolState = _accruePoolInterest(); // round to token precision - quoteTokenAmountToAdd_ = _roundToScale(quoteTokenAmountToAdd_, poolState.quoteDustLimit); + amount_ = _roundToScale(amount_, poolState.quoteDustLimit); uint256 newLup; - (bucketLPs_, newLup) = LenderActions.addQuoteToken( + (bucketLP_, newLup) = LenderActions.addQuoteToken( buckets, deposits, poolState, AddQuoteParams({ - amount: quoteTokenAmountToAdd_, + amount: amount_, index: index_ }) ); @@ -165,16 +168,16 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { _updateInterestState(poolState, newLup); // move quote token amount from lender to pool - _transferQuoteTokenFrom(msg.sender, quoteTokenAmountToAdd_); + _transferQuoteTokenFrom(msg.sender, amount_); } /// @inheritdoc IPoolLenderActions function moveQuoteToken( - uint256 maxAmountToMove_, + uint256 maxAmount_, uint256 fromIndex_, uint256 toIndex_, uint256 expiry_ - ) external override nonReentrant returns (uint256 fromBucketLPs_, uint256 toBucketLPs_, uint256 movedAmount_) { + ) external override nonReentrant returns (uint256 fromBucketLP_, uint256 toBucketLP_, uint256 movedAmount_) { _revertOnExpiry(expiry_); PoolState memory poolState = _accruePoolInterest(); @@ -182,8 +185,8 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { uint256 newLup; ( - fromBucketLPs_, - toBucketLPs_, + fromBucketLP_, + toBucketLP_, movedAmount_, newLup ) = LenderActions.moveQuoteToken( @@ -191,7 +194,7 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { deposits, poolState, MoveQuoteParams({ - maxAmountToMove: maxAmountToMove_, + maxAmountToMove: maxAmount_, fromIndex: fromIndex_, toIndex: toIndex_, thresholdPrice: Loans.getMax(loans).thresholdPrice @@ -206,7 +209,7 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { function removeQuoteToken( uint256 maxAmount_, uint256 index_ - ) external override nonReentrant returns (uint256 removedAmount_, uint256 redeemedLPs_) { + ) external override nonReentrant returns (uint256 removedAmount_, uint256 redeemedLP_) { _revertIfAuctionClearable(auctions, loans); PoolState memory poolState = _accruePoolInterest(); @@ -216,7 +219,7 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { uint256 newLup; ( removedAmount_, - redeemedLPs_, + redeemedLP_, newLup ) = LenderActions.removeQuoteToken( buckets, @@ -267,11 +270,11 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { /** * @inheritdoc IPoolKickerActions * @dev write state: - * - increment poolBalances.t0DebtInAuction and poolBalances.t0Debt accumulators + * - increment `poolBalances.t0DebtInAuction` and `poolBalances.t0Debt` accumulators */ function kick( - address borrowerAddress_, - uint256 limitIndex_ + address borrower_, + uint256 npLimitIndex_ ) external override nonReentrant { PoolState memory poolState = _accruePoolInterest(); @@ -281,8 +284,8 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { deposits, loans, poolState, - borrowerAddress_, - limitIndex_ + borrower_, + npLimitIndex_ ); // update pool balances state @@ -308,11 +311,11 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { /** * @inheritdoc IPoolKickerActions * @dev write state: - * - increment poolBalances.t0DebtInAuction and poolBalances.t0Debt accumulators + * - increment `poolBalances.t0DebtInAuction` and `poolBalances.t0Debt` accumulators */ function kickWithDeposit( uint256 index_, - uint256 limitIndex_ + uint256 npLimitIndex_ ) external override nonReentrant { PoolState memory poolState = _accruePoolInterest(); @@ -324,7 +327,7 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { loans, poolState, index_, - limitIndex_ + npLimitIndex_ ); // update pool balances state @@ -351,8 +354,8 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { /** * @inheritdoc IPoolKickerActions * @dev write state: - * - decrease kicker's claimable accumulator - * - decrease auctions totalBondEscrowed accumulator + * - decrease kicker's `claimable` accumulator + * - decrease auctions `totalBondEscrowed` accumulator */ function withdrawBonds( address recipient_, @@ -383,12 +386,12 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { /** * @inheritdoc IPoolKickerActions * @dev write state: - * - increment latestBurnEpoch counter - * - update reserveAuction.latestBurnEventEpoch and burn event timestamp state + * - increment `latestBurnEpoch` counter + * - update `reserveAuction.latestBurnEventEpoch` and burn event `timestamp` state * @dev reverts on: - * - 2 weeks not passed ReserveAuctionTooSoon() + * - 2 weeks not passed `ReserveAuctionTooSoon()` * @dev emit events: - * - KickReserveAuction + * - `KickReserveAuction` */ function kickReserveAuction() external override nonReentrant { // start a new claimable reserve auction, passing in relevant parameters such as the current pool size, debt, balance, and inflator value @@ -410,8 +413,8 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { /** * @inheritdoc IPoolTakerActions * @dev write state: - * - increment reserveAuction.totalAjnaBurned accumulator - * - update burn event totalInterest and totalBurned accumulators + * - increment `reserveAuction.totalAjnaBurned` accumulator + * - update burn event `totalInterest` and `totalBurned` accumulators */ function takeReserves( uint256 maxAmount_ @@ -485,11 +488,7 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { ); } - /** - * @inheritdoc IPoolLPActions - * @dev write state: - * - approvedTransferors mapping - */ + /// @inheritdoc IPoolLPActions function revokeLPTransferors( address[] calldata transferors_ ) external override { @@ -522,12 +521,12 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { /** * @notice Accrues pool interest in current block and returns pool details. * @dev external libraries call: - * - PoolCommons.accrueInterest + * - `PoolCommons.accrueInterest` * @dev write state: - * - PoolCommons.accrueInterest: - * - Deposits.mult (scale Fenwick tree with new interest accrued): + * - `PoolCommons.accrueInterest`: + * - `Deposits.mult` (scale `Fenwick` tree with new interest accrued): * - update scaling array state - * - increment reserveAuction.totalInterestEarned accumulator + * - increment `reserveAuction.totalInterestEarned` accumulator * @return poolState_ Struct containing pool details. */ function _accruePoolInterest() internal returns (PoolState memory poolState_) { @@ -569,10 +568,10 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { } /** - * @notice Adjusts the t0 Debt 2 to collateral ratio, interestState.t0Debt2ToCollateral. - * @dev Anytime a borrower's debt or collateral changes, the interestState.t0Debt2ToCollateral must be updated. + * @notice Adjusts the `t0` debt 2 to collateral ratio, `interestState.t0Debt2ToCollateral`. + * @dev Anytime a borrower's debt or collateral changes, the `interestState.t0Debt2ToCollateral` must be updated. * @dev write state: - * - update interestState.t0Debt2ToCollateral accumulator + * - update `interestState.t0Debt2ToCollateral` accumulator * @param debtPreAction_ Borrower's debt before the action * @param debtPostAction_ Borrower's debt after the action * @param colPreAction_ Borrower's collateral before the action @@ -599,17 +598,17 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { /** * @notice Update interest rate and inflator of the pool. * @dev external libraries call: - * - PoolCommons.updateInterestState + * - `PoolCommons.updateInterestState` * @dev write state: - * - PoolCommons.updateInterestState - * - interest debt and lup * collateral EMAs accumulators - * - interest rate accumulator and interestRateUpdate state - * - pool inflator and inflatorUpdate state + * - `PoolCommons.updateInterestState ` + * - `EMA`s accumulators + * - interest rate accumulator and `interestRateUpdate` state + * - pool inflator and `inflatorUpdate` state * @dev emit events: - * - PoolCommons.updateInterestState: - * - UpdateInterestRate + * - `PoolCommons.updateInterestState`: + * - `UpdateInterestRate` * @param poolState_ Struct containing pool details. - * @param lup_ Current LUP in pool. + * @param lup_ Current `LUP` in pool. */ function _updateInterestState( PoolState memory poolState_, @@ -630,16 +629,26 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { } } + /** + * @notice Helper function to transfer amount of quote tokens (in quote token precision) from sender to pool contract. + * @param from_ Sender address. + * @param amount_ Amount to transfer from sender. + */ function _transferQuoteTokenFrom(address from_, uint256 amount_) internal { IERC20(_getArgAddress(QUOTE_ADDRESS)).safeTransferFrom(from_, address(this), amount_ / _getArgUint256(QUOTE_SCALE)); } + /** + * @notice Helper function to transfer amount of quote tokens (in quote token precision) from pool contract. + * @param to_ Receiver address. + * @param amount_ Amount to transfer to receiver. + */ function _transferQuoteToken(address to_, uint256 amount_) internal { IERC20(_getArgAddress(QUOTE_ADDRESS)).safeTransfer(to_, amount_ / _getArgUint256(QUOTE_SCALE)); } /** - * @dev returns the pool quote token balance normalized to WAD to be used for calculating pool reserves + * @notice Returns the pool quote token balance normalized to `WAD` to be used for calculating pool reserves. */ function _getNormalizedPoolQuoteTokenBalance() internal view returns (uint256) { return IERC20(_getArgAddress(QUOTE_ADDRESS)).balanceOf(address(this)) * _getArgUint256(QUOTE_SCALE); @@ -654,16 +663,16 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { address borrower_ ) external view override returns ( - address kicker, - uint256 bondFactor, - uint256 bondSize, - uint256 kickTime, - uint256 kickMomp, - uint256 neutralPrice, - address head, - address next, - address prev, - bool alreadyTaken + address kicker_, + uint256 bondFactor_, + uint256 bondSize_, + uint256 kickTime_, + uint256 kickMomp_, + uint256 neutralPrice_, + address head_, + address next_, + address prev_, + bool alreadyTaken_ ) { Liquidation memory liquidation = auctions.liquidations[borrower_]; return ( diff --git a/src/base/PoolDeployer.sol b/src/base/PoolDeployer.sol index 977c04f7b..60372b29a 100644 --- a/src/base/PoolDeployer.sol +++ b/src/base/PoolDeployer.sol @@ -10,16 +10,19 @@ import { IPoolFactory } from '../interfaces/pool/IPoolFactory.sol'; */ abstract contract PoolDeployer { + /// @dev Min interest rate value allowed for deploying the pool (1%) uint256 public constant MIN_RATE = 0.01 * 1e18; + /// @dev Max interest rate value allowed for deploying the pool (10% uint256 public constant MAX_RATE = 0.1 * 1e18; + /// @dev `Ajna` token address address public ajna; // Ajna token contract address on a network. /***********************/ /*** State Variables ***/ /***********************/ - /// @dev SubsetHash => CollateralAddress => QuoteAddress => Pool Address + /// @dev SubsetHash => CollateralAddress => QuoteAddress => Pool Address mapping // slither-disable-next-line uninitialized-state mapping(bytes32 => mapping(address => mapping(address => address))) public deployedPools; @@ -33,7 +36,7 @@ abstract contract PoolDeployer { /** * @notice Ensures that pools are deployed according to specifications. - * @dev Used by both ERC20, and ERC721 pool factory types. + * @dev Used by both `ERC20` and `ERC721` pool factories. */ modifier canDeploy(address collateral_, address quote_, uint256 interestRate_) { if (collateral_ == quote_) revert IPoolFactory.DeployQuoteCollateralSameToken(); @@ -50,7 +53,7 @@ abstract contract PoolDeployer { * @notice Returns the list of all deployed pools. * @dev This function is used by integrations to access deployed pools. * @dev Each factory implementation maintains its own list of deployed pools. - * @return address[] memory List of all deployed pools. + * @return List of all deployed pools. */ function getDeployedPoolsList() external view returns (address[] memory) { return deployedPoolsList; @@ -58,7 +61,7 @@ abstract contract PoolDeployer { /** * @notice Returns the number of deployed pools that have been deployed by a factory. - * @return uint256 length of deployedPoolsList array. + * @return Length of `deployedPoolsList` array. */ function getNumberOfDeployedPools() external view returns (uint256) { return deployedPoolsList.length; diff --git a/src/interfaces/pool/commons/IPoolBorrowerActions.sol b/src/interfaces/pool/commons/IPoolBorrowerActions.sol index 141f085a9..35dec7bf0 100644 --- a/src/interfaces/pool/commons/IPoolBorrowerActions.sol +++ b/src/interfaces/pool/commons/IPoolBorrowerActions.sol @@ -8,9 +8,9 @@ pragma solidity 0.8.14; interface IPoolBorrowerActions { /** - * @notice Called by fully colalteralized borrowers to restamp the Neutral Price of the loan (only if loan is fully collateralized and not in auction). - * @notice The reason for stamping the neutral price on the loan is to provide some certainty to the borrower as to at what price they can expect to be liquidated. - * @notice This action can restamp only the loan of `msg.sender`. + * @notice Called by fully colalteralized borrowers to restamp the `Neutral Price` of the loan (only if loan is fully collateralized and not in auction). + * The reason for stamping the neutral price on the loan is to provide some certainty to the borrower as to at what price they can expect to be liquidated. + * This action can restamp only the loan of `msg.sender`. */ function stampLoan() external; diff --git a/src/interfaces/pool/commons/IPoolDerivedState.sol b/src/interfaces/pool/commons/IPoolDerivedState.sol index 07198be57..94294f83d 100644 --- a/src/interfaces/pool/commons/IPoolDerivedState.sol +++ b/src/interfaces/pool/commons/IPoolDerivedState.sol @@ -7,14 +7,19 @@ pragma solidity 0.8.14; */ interface IPoolDerivedState { + /** + * @notice Returns the exchange rate for a given bucket index. + * @param index_ The bucket index. + * @return exchangeRate_ Exchange rate of the bucket. + */ function bucketExchangeRate( uint256 index_ ) external view returns (uint256 exchangeRate_); /** - * @notice Returns the prefix sum of a given bucket - * @param index_ The target index - * @return Prefix sum + * @notice Returns the prefix sum of a given bucket. + * @param index_ The bucket index. + * @return The deposit up to given index. */ function depositUpToIndex( uint256 index_ diff --git a/src/interfaces/pool/commons/IPoolImmutables.sol b/src/interfaces/pool/commons/IPoolImmutables.sol index addf29a6b..96e0c915e 100644 --- a/src/interfaces/pool/commons/IPoolImmutables.sol +++ b/src/interfaces/pool/commons/IPoolImmutables.sol @@ -8,23 +8,23 @@ pragma solidity 0.8.14; interface IPoolImmutables { /** - * @notice Returns the type of the pool (0 for ERC20, 1 for ERC721) + * @notice Returns the type of the pool (`0` for `ERC20`, `1` for `ERC721`). */ function poolType() external pure returns (uint8); /** - * @notice Returns the address of the pool's collateral token + * @notice Returns the address of the pool's collateral token. */ function collateralAddress() external pure returns (address); /** - * @notice Returns the address of the pools quote token + * @notice Returns the address of the pool's quote token. */ function quoteTokenAddress() external pure returns (address); /** * @notice Returns the `quoteTokenScale` state variable. - * @return The precision of the quote ERC-20 token based on decimals. + * @return The precision of the quote `ERC20` token based on decimals. */ function quoteTokenScale() external pure returns (uint256); diff --git a/src/interfaces/pool/commons/IPoolKickerActions.sol b/src/interfaces/pool/commons/IPoolKickerActions.sol index 2b3e117a5..81e661433 100644 --- a/src/interfaces/pool/commons/IPoolKickerActions.sol +++ b/src/interfaces/pool/commons/IPoolKickerActions.sol @@ -13,32 +13,32 @@ interface IPoolKickerActions { /** * @notice Called by actors to initiate a liquidation. - * @param borrower Identifies the loan to liquidate. - * @param npLimitIndex Index of the lower bound of NP tolerated when kicking the auction. + * @param borrower_ Identifies the loan to liquidate. + * @param npLimitIndex_ Index of the lower bound of `NP` tolerated when kicking the auction. */ function kick( - address borrower, - uint256 npLimitIndex + address borrower_, + uint256 npLimitIndex_ ) external; /** * @notice Called by lenders to liquidate the top loan using their deposits. - * @param index The deposit index to use for kicking the top loan. - * @param npLimitIndex Index of the lower bound of NP tolerated when kicking the auction. + * @param index_ The deposit index to use for kicking the top loan. + * @param npLimitIndex_ Index of the lower bound of `NP` tolerated when kicking the auction. */ function kickWithDeposit( - uint256 index, - uint256 npLimitIndex + uint256 index_, + uint256 npLimitIndex_ ) external; /** * @notice Called by kickers to withdraw their auction bonds (the amount of quote tokens that are not locked in active auctions). - * @param recipient Address to receive claimed bonds amount. - * @param maxAmount The max amount to withdraw from auction bonds. Constrained by claimable amounts and liquidity + * @param recipient_ Address to receive claimed bonds amount. + * @param maxAmount_ The max amount to withdraw from auction bonds. Constrained by claimable amounts and liquidity */ function withdrawBonds( - address recipient, - uint256 maxAmount + address recipient_, + uint256 maxAmount_ ) external; /***********************/ diff --git a/src/interfaces/pool/commons/IPoolLPActions.sol b/src/interfaces/pool/commons/IPoolLPActions.sol index a50f5d8e1..370ee5f40 100644 --- a/src/interfaces/pool/commons/IPoolLPActions.sol +++ b/src/interfaces/pool/commons/IPoolLPActions.sol @@ -3,74 +3,74 @@ pragma solidity 0.8.14; /** - * @title Pool LP Actions + * @title Pool `LP` Actions */ interface IPoolLPActions { /** - * @notice Called by LP owners to approve transfer of an amount of LP to a new owner. - * @dev Intended for use by the PositionManager contract. - * @param spender The new owner of the LP. - * @param indexes Bucket indexes from where LP are transferred. - * @param amounts The amounts of LP approved to transfer. + * @notice Called by `LP` owners to approve transfer of an amount of `LP` to a new owner. + * @dev Intended for use by the `PositionManager` contract. + * @param spender_ The new owner of the `LP`. + * @param indexes_ Bucket indexes from where `LP` are transferred. + * @param amounts_ The amounts of `LP` approved to transfer. */ function increaseLPAllowance( - address spender, - uint256[] calldata indexes, - uint256[] calldata amounts + address spender_, + uint256[] calldata indexes_, + uint256[] calldata amounts_ ) external; /** - * @notice Called by LP owners to decrease the amount of LP that can be spend by a new owner. - * @dev Intended for use by the PositionManager contract. - * @param spender The new owner of the LP. - * @param indexes Bucket indexes from where LP are transferred. - * @param amounts The amounts of LP disapproved to transfer. + * @notice Called by `LP` owners to decrease the amount of `LP` that can be spend by a new owner. + * @dev Intended for use by the `PositionManager` contract. + * @param spender_ The new owner of the `LP`. + * @param indexes_ Bucket indexes from where `LP` are transferred. + * @param amounts_ The amounts of `LP` disapproved to transfer. */ function decreaseLPAllowance( - address spender, - uint256[] calldata indexes, - uint256[] calldata amounts + address spender_, + uint256[] calldata indexes_, + uint256[] calldata amounts_ ) external; /** - * @notice Called by LP owners to decrease the amount of LP that can be spend by a new owner. - * @param spender Address that is having it's allowance revoked. - * @param indexes List of bucket index to remove the allowance from. + * @notice Called by `LP` owners to decrease the amount of `LP` that can be spend by a new owner. + * @param spender_ Address that is having it's allowance revoked. + * @param indexes_ List of bucket index to remove the allowance from. */ function revokeLPAllowance( - address spender, - uint256[] calldata indexes + address spender_, + uint256[] calldata indexes_ ) external; /** - * @notice Called by LP owners to allow addresses that can transfer LP. - * @dev Intended for use by the PositionManager contract. - * @param transferors Addresses that are allowed to transfer LP to new owner. + * @notice Called by `LP` owners to allow addresses that can transfer LP. + * @dev Intended for use by the `PositionManager` contract. + * @param transferors_ Addresses that are allowed to transfer `LP` to new owner. */ function approveLPTransferors( - address[] calldata transferors + address[] calldata transferors_ ) external; /** - * @notice Called by LP owners to revoke addresses that can transfer LP. - * @dev Intended for use by the PositionManager contract. - * @param transferors Addresses that are revoked to transfer LP to new owner. + * @notice Called by `LP` owners to revoke addresses that can transfer `LP`. + * @dev Intended for use by the `PositionManager` contract. + * @param transferors_ Addresses that are revoked to transfer `LP` to new owner. */ function revokeLPTransferors( - address[] calldata transferors + address[] calldata transferors_ ) external; /** - * @notice Called by LP owners to transfers their LP to a different address. approveLpOwnership needs to be run first - * @dev Used by PositionManager.memorializePositions(). - * @param owner The original owner address of the position. - * @param newOwner The new owner address of the position. - * @param indexes Array of price buckets index at which LP were moved. + * @notice Called by `LP` owners to transfers their `LP` to a different address. `approveLpOwnership` needs to be run first. + * @dev Used by `PositionManager.memorializePositions()`. + * @param owner_ The original owner address of the position. + * @param newOwner_ The new owner address of the position. + * @param indexes_ Array of price buckets index at which `LP` were moved. */ function transferLP( - address owner, - address newOwner, - uint256[] calldata indexes + address owner_, + address newOwner_, + uint256[] calldata indexes_ ) external; } diff --git a/src/interfaces/pool/commons/IPoolLenderActions.sol b/src/interfaces/pool/commons/IPoolLenderActions.sol index 33fd237f8..598ae68bc 100644 --- a/src/interfaces/pool/commons/IPoolLenderActions.sol +++ b/src/interfaces/pool/commons/IPoolLenderActions.sol @@ -13,33 +13,33 @@ interface IPoolLenderActions { /** * @notice Called by lenders to add an amount of credit at a specified price bucket. - * @param amount The amount of quote token to be added by a lender. - * @param index The index of the bucket to which the quote tokens will be added. - * @param expiry Timestamp after which this TX will revert, preventing inclusion in a block with unfavorable price. - * @return lpbChange The amount of LP changed for the added quote tokens. + * @param amount_ The amount of quote token to be added by a lender. + * @param index_ The index of the bucket to which the quote tokens will be added. + * @param expiry_ Timestamp after which this transaction will revert, preventing inclusion in a block with unfavorable price. + * @return bucketLP_ The amount of `LP` changed for the added quote tokens. */ function addQuoteToken( - uint256 amount, - uint256 index, - uint256 expiry - ) external returns (uint256 lpbChange); + uint256 amount_, + uint256 index_, + uint256 expiry_ + ) external returns (uint256 bucketLP_); /** * @notice Called by lenders to move an amount of credit from a specified price bucket to another specified price bucket. - * @param maxAmount The maximum amount of quote token to be moved by a lender. - * @param fromIndex The bucket index from which the quote tokens will be removed. - * @param toIndex The bucket index to which the quote tokens will be added. - * @param expiry Timestamp after which this TX will revert, preventing inclusion in a block with unfavorable price. - * @return lpbAmountFrom The amount of LP moved out from bucket. - * @return lpbAmountTo The amount of LP moved to destination bucket. - * @return quoteTokenAmount The amount of quote token moved. + * @param maxAmount_ The maximum amount of quote token to be moved by a lender. + * @param fromIndex_ The bucket index from which the quote tokens will be removed. + * @param toIndex_ The bucket index to which the quote tokens will be added. + * @param expiry_ Timestamp after which this transaction will revert, preventing inclusion in a block with unfavorable price. + * @return fromBucketLP_ The amount of `LP` moved out from bucket. + * @return toBucketLP_ The amount of `LP` moved to destination bucket. + * @return movedAmount_ The amount of quote token moved. */ function moveQuoteToken( - uint256 maxAmount, - uint256 fromIndex, - uint256 toIndex, - uint256 expiry - ) external returns (uint256 lpbAmountFrom, uint256 lpbAmountTo, uint256 quoteTokenAmount); + uint256 maxAmount_, + uint256 fromIndex_, + uint256 toIndex_, + uint256 expiry_ + ) external returns (uint256 fromBucketLP_, uint256 toBucketLP_, uint256 movedAmount_); /** * @notice Called by lenders to claim collateral from a price bucket. @@ -55,22 +55,22 @@ interface IPoolLenderActions { /** * @notice Called by lenders to remove an amount of credit at a specified price bucket. - * @param maxAmount The max amount of quote token to be removed by a lender. - * @param index The bucket index from which quote tokens will be removed. - * @return quoteTokenAmount The amount of quote token removed. - * @return lpAmount The amount of LP used for removing quote tokens amount. + * @param maxAmount_ The max amount of quote token to be removed by a lender. + * @param index_ The bucket index from which quote tokens will be removed. + * @return removedAmount_ The amount of quote token removed. + * @return redeemedLP_ The amount of `LP` used for removing quote tokens amount. */ function removeQuoteToken( - uint256 maxAmount, - uint256 index - ) external returns (uint256 quoteTokenAmount, uint256 lpAmount); + uint256 maxAmount_, + uint256 index_ + ) external returns (uint256 removedAmount_, uint256 redeemedLP_); /********************************/ /*** Interest update function ***/ /********************************/ /** - * @notice Called by actors to update pool interest rate (can be updated only once in a 12 hours period of time). + * @notice Called by actors to update pool interest rate (can be updated only once in a `12` hours period of time). */ function updateInterest() external; diff --git a/src/interfaces/pool/commons/IPoolState.sol b/src/interfaces/pool/commons/IPoolState.sol index 04ebdabfb..96984ca6c 100644 --- a/src/interfaces/pool/commons/IPoolState.sol +++ b/src/interfaces/pool/commons/IPoolState.sol @@ -9,162 +9,170 @@ interface IPoolState { /** * @notice Returns details of an auction for a given borrower address. - * @param borrower Address of the borrower that is liquidated. - * @return kicker Address of the kicker that is kicking the auction. - * @return bondFactor The factor used for calculating bond size. - * @return bondSize The bond amount in quote token terms. - * @return kickTime Time the liquidation was initiated. - * @return kickMomp Price where the average loan utilizes deposit, at the time when the loan is liquidated (kicked). - * @return neutralPrice Neutral Price of auction. - * @return head Address of the head auction. - * @return next Address of the next auction in queue. - * @return prev Address of the prev auction in queue. - * @return alreadyTaken True if take has been called on auction + * @param borrower_ Address of the borrower that is liquidated. + * @return kicker_ Address of the kicker that is kicking the auction. + * @return bondFactor_ The factor used for calculating bond size. + * @return bondSize_ The bond amount in quote token terms. + * @return kickTime_ Time the liquidation was initiated. + * @return kickMomp_ Price where the average loan utilizes deposit, at the time when the loan is liquidated (kicked). + * @return neutralPrice_ `Neutral Price` of auction. + * @return head_ Address of the head auction. + * @return next_ Address of the next auction in queue. + * @return prev_ Address of the prev auction in queue. + * @return alreadyTaken_ True if take has been called on auction */ - function auctionInfo(address borrower) + function auctionInfo(address borrower_) external view returns ( - address kicker, - uint256 bondFactor, - uint256 bondSize, - uint256 kickTime, - uint256 kickMomp, - uint256 neutralPrice, - address head, - address next, - address prev, - bool alreadyTaken + address kicker_, + uint256 bondFactor_, + uint256 bondSize_, + uint256 kickTime_, + uint256 kickMomp_, + uint256 neutralPrice_, + address head_, + address next_, + address prev_, + bool alreadyTaken_ ); /** * @notice Returns pool related debt values. - * @return debt_ Current amount of debt owed by borrowers in pool. - * @return accruedDebt_ Debt owed by borrowers based on last inflator snapshot. + * @return debt_ Current amount of debt owed by borrowers in pool. + * @return accruedDebt_ Debt owed by borrowers based on last inflator snapshot. * @return debtInAuction_ Total amount of debt in auction. * @return t0Debt2ToCollateral_ t0debt accross all borrowers divided by their collateral, used in determining a collateralization weighted debt. */ - function debtInfo() external view returns (uint256 debt_, uint256 accruedDebt_, uint256 debtInAuction_, uint256 t0Debt2ToCollateral_); + function debtInfo() + external + view + returns ( + uint256 debt_, + uint256 accruedDebt_, + uint256 debtInAuction_, + uint256 t0Debt2ToCollateral_ + ); /** - * @notice Mapping of borrower addresses to {Borrower} structs. + * @notice Mapping of borrower addresses to `Borrower` structs. * @dev NOTE: Cannot use appended underscore syntax for return params since struct is used. - * @param borrower Address of the borrower. - * @return t0Debt Amount of debt borrower would have had if their loan was the first debt drawn from the pool - * @return collateral Amount of collateral that the borrower has deposited, in collateral token. - * @return t0Np t0 Neutral Price + * @param borrower_ Address of the borrower. + * @return t0Debt_ Amount of debt borrower would have had if their loan was the first debt drawn from the pool. + * @return collateral_ Amount of collateral that the borrower has deposited, in collateral token. + * @return t0Np_ t0 `Neutral Price` */ - function borrowerInfo(address borrower) + function borrowerInfo(address borrower_) external view returns ( - uint256 t0Debt, - uint256 collateral, - uint256 t0Np + uint256 t0Debt_, + uint256 collateral_, + uint256 t0Np_ ); /** - * @notice Mapping of buckets indexes to {Bucket} structs. + * @notice Mapping of buckets indexes to `Bucket` structs. * @dev NOTE: Cannot use appended underscore syntax for return params since struct is used. - * @param index Bucket index. - * @return lpAccumulator Amount of LP accumulated in current bucket. - * @return availableCollateral Amount of collateral available in current bucket. - * @return bankruptcyTime Timestamp when bucket become insolvent, 0 if healthy. - * @return bucketDeposit Amount of quote tokens in bucket. - * @return bucketScale Bucket multiplier. + * @param index_ Bucket index. + * @return lpAccumulator_ Amount of `LP` accumulated in current bucket. + * @return availableCollateral_ Amount of collateral available in current bucket. + * @return bankruptcyTime_ Timestamp when bucket become insolvent, `0` if healthy. + * @return bucketDeposit_ Amount of quote tokens in bucket. + * @return bucketScale_ Bucket multiplier. */ - function bucketInfo(uint256 index) + function bucketInfo(uint256 index_) external view returns ( - uint256 lpAccumulator, - uint256 availableCollateral, - uint256 bankruptcyTime, - uint256 bucketDeposit, - uint256 bucketScale + uint256 lpAccumulator_, + uint256 availableCollateral_, + uint256 bankruptcyTime_, + uint256 bucketDeposit_, + uint256 bucketScale_ ); /** * @notice Mapping of burnEventEpoch to {BurnEvent} structs. * @dev Reserve auctions correspond to burn events. * @param burnEventEpoch_ Id of the current reserve auction. - * @return burnBlock Block in which a reserve auction started. - * @return totalInterest Total interest as of the reserve auction. - * @return totalBurned Total ajna tokens burned as of the reserve auction. + * @return burnBlock_ Block in which a reserve auction started. + * @return totalInterest_ Total interest as of the reserve auction. + * @return totalBurned_ Total ajna tokens burned as of the reserve auction. */ function burnInfo(uint256 burnEventEpoch_) external view returns (uint256, uint256, uint256); /** - * @notice Returns the latest burnEventEpoch of reserve auctions. + * @notice Returns the latest `burnEventEpoch` of reserve auctions. * @dev If a reserve auction is active, it refers to the current reserve auction. If no reserve auction is active, it refers to the last reserve auction. - * @return burnEventEpoch Current burnEventEpoch. + * @return Current `burnEventEpoch`. */ function currentBurnEpoch() external view returns (uint256); /** - * @notice Returns information about the pool EMA (Exponential Moving Average) variables. - * @return debtColEma Debt squared to collateral Exponential, numerator to TU calculation - * @return lupt0DebtEma Exponential of LUP * t0 debt, denominator to TU calculation - * @return debtEma Exponential debt moving average. - * @return depositEma sample of meaningful deposit Exponential, denominator to MAU calculation. + * @notice Returns information about the pool `EMA (Exponential Moving Average)` variables. + * @return debtColEma_ Debt squared to collateral Exponential, numerator to `TU` calculation. + * @return lupt0DebtEma_ Exponential of `LUP * t0 debt`, denominator to `TU` calculation + * @return debtEma_ Exponential debt moving average. + * @return depositEma_ sample of meaningful deposit Exponential, denominator to `MAU` calculation. */ function emasInfo() external view returns ( - uint256 debtColEma, - uint256 lupt0DebtEma, - uint256 debtEma, - uint256 depositEma + uint256 debtColEma_, + uint256 lupt0DebtEma_, + uint256 debtEma_, + uint256 depositEma_ ); /** * @notice Returns information about pool inflator. - * @return inflator Pool inflator value. - * @return lastUpdate The timestamp of the last `inflator` update. + * @return inflator_ Pool inflator value. + * @return lastUpdate_ The timestamp of the last `inflator` update. */ function inflatorInfo() external view returns ( - uint256 inflator, - uint256 lastUpdate + uint256 inflator_, + uint256 lastUpdate_ ); /** * @notice Returns information about pool interest rate. - * @return interestRate Current interest rate in pool. - * @return interestRateUpdate The timestamp of the last interest rate update. + * @return interestRate_ Current interest rate in pool. + * @return interestRateUpdate_ The timestamp of the last interest rate update. */ function interestRateInfo() external view returns ( - uint256 interestRate, - uint256 interestRateUpdate + uint256 interestRate_, + uint256 interestRateUpdate_ ); /** * @notice Returns details about kicker balances. - * @param kicker The address of the kicker to retrieved info for. - * @return claimable Amount of quote token kicker can claim / withdraw from pool at any time. - * @return locked Amount of quote token kicker locked in auctions (as bonds). + * @param kicker_ The address of the kicker to retrieved info for. + * @return claimable_ Amount of quote token kicker can claim / withdraw from pool at any time. + * @return locked_ Amount of quote token kicker locked in auctions (as bonds). */ - function kickerInfo(address kicker) + function kickerInfo(address kicker_) external view returns ( - uint256 claimable, - uint256 locked + uint256 claimable_, + uint256 locked_ ); /** - * @notice Mapping of buckets indexes and owner addresses to {Lender} structs. - * @param index Bucket index. - * @param lp Address of the liquidity provider. - * @return lpBalance Amount of LP owner has in current bucket. - * @return lastQuoteDeposit Time the user last deposited quote token. + * @notice Mapping of buckets indexes and owner addresses to `Lender` structs. + * @param index_ Bucket index. + * @param lender_ Address of the liquidity provider. + * @return lpBalance_ Amount of `LP` owner has in current bucket. + * @return depositTime_ Time the user last deposited quote token. */ function lenderInfo( uint256 index, @@ -173,69 +181,69 @@ interface IPoolState { external view returns ( - uint256 lpBalance, - uint256 lastQuoteDeposit + uint256 lpBalance_, + uint256 depositTime_ ); /** - * @notice Return the LPB allowance a LP owner provided to a spender. - * @param index Bucket index. - * @param spender Address of the LPB spender. - * @param owner The initial owner of the LP. - * @return allowance_ Amount of LP spender can utilize. + * @notice Return the `LP` allowance a `LP` owner provided to a spender. + * @param index_ Bucket index. + * @param spender_ Address of the `LP` spender. + * @param owner_ The initial owner of the `LP`. + * @return allowance_ Amount of `LP` spender can utilize. */ function lpAllowance( - uint256 index, - address spender, - address owner + uint256 index_, + address spender_, + address owner_ ) external view returns (uint256 allowance_); /** * @notice Returns information about a loan in the pool. - * @param loanId Loan's id within loan heap. Max loan is position 1. - * @return borrower Borrower address at the given position. - * @return thresholdPrice Borrower threshold price in pool. + * @param loanId_ Loan's id within loan heap. Max loan is position `1`. + * @return borrower_ Borrower address at the given position. + * @return thresholdPrice_ Borrower threshold price in pool. */ function loanInfo( - uint256 loanId + uint256 loanId_ ) external view returns ( - address borrower, - uint256 thresholdPrice + address borrower_, + uint256 thresholdPrice_ ); /** * @notice Returns information about pool loans. - * @return maxBorrower Borrower address with highest threshold price. - * @return maxThresholdPrice Highest threshold price in pool. - * @return noOfLoans Total number of loans. + * @return maxBorrower_ Borrower address with highest threshold price. + * @return maxThresholdPrice_ Highest threshold price in pool. + * @return noOfLoans_ Total number of loans. */ function loansInfo() external view returns ( - address maxBorrower, - uint256 maxThresholdPrice, - uint256 noOfLoans + address maxBorrower_, + uint256 maxThresholdPrice_, + uint256 noOfLoans_ ); /** * @notice Returns information about pool reserves. - * @return liquidationBondEscrowed Amount of liquidation bond across all liquidators. - * @return reserveAuctionUnclaimed Amount of claimable reserves which has not been taken in the Claimable Reserve Auction. - * @return reserveAuctionKicked Time a Claimable Reserve Auction was last kicked. - * @return totalInterestEarned Total interest earned by all lenders in the pool + * @return liquidationBondEscrowed_ Amount of liquidation bond across all liquidators. + * @return reserveAuctionUnclaimed_ Amount of claimable reserves which has not been taken in the `Claimable Reserve Auction`. + * @return reserveAuctionKicked_ Time a `Claimable Reserve Auction` was last kicked. + * @return totalInterestEarned_ Total interest earned by all lenders in the pool */ function reservesInfo() external view returns ( - uint256 liquidationBondEscrowed, - uint256 reserveAuctionUnclaimed, - uint256 reserveAuctionKicked, - uint256 totalInterestEarned + uint256 liquidationBondEscrowed_, + uint256 reserveAuctionUnclaimed_, + uint256 reserveAuctionKicked_, + uint256 totalInterestEarned_ ); /** @@ -245,29 +253,29 @@ interface IPoolState { function pledgedCollateral() external view returns (uint256); /** - * @notice Returns the total number of active auctions in pool - * @return totalAuctions_ number of active auctions. + * @notice Returns the total number of active auctions in pool. + * @return totalAuctions_ Number of active auctions. */ function totalAuctionsInPool() external view returns (uint256); /** * @notice Returns the `t0Debt` state variable. * @dev This value should be multiplied by inflator in order to calculate current debt of the pool. - * @return The total t0Debt in the system, in WAD units. + * @return The total `t0Debt` in the system, in `WAD` units. */ function totalT0Debt() external view returns (uint256); /** * @notice Returns the `t0DebtInAuction` state variable. * @dev This value should be multiplied by inflator in order to calculate current debt in auction of the pool. - * @return The total t0DebtInAuction in the system, in WAD units. + * @return The total `t0DebtInAuction` in the system, in `WAD` units. */ function totalT0DebtInAuction() external view returns (uint256); /** - * @notice Mapping of addresses that can transfer LP to a given lender. - * @param lender Lender that receives LP. - * @param transferor Transferor that transfers LP. + * @notice Mapping of addresses that can transfer `LP` to a given lender. + * @param lender_ Lender that receives `LP`. + * @param transferor_ Transferor that transfers `LP`. * @return True if the transferor is approved by lender. */ function approvedTransferors( diff --git a/src/interfaces/pool/commons/IPoolTakerActions.sol b/src/interfaces/pool/commons/IPoolTakerActions.sol index 627cacabf..620e5a7c3 100644 --- a/src/interfaces/pool/commons/IPoolTakerActions.sol +++ b/src/interfaces/pool/commons/IPoolTakerActions.sol @@ -40,12 +40,12 @@ interface IPoolTakerActions { /***********************/ /** - * @notice Purchases claimable reserves during a CRA using Ajna token. - * @param maxAmount Maximum amount of quote token to purchase at the current auction price. - * @return amount Actual amount of reserves taken. + * @notice Purchases claimable reserves during a `CRA` using `Ajna` token. + * @param maxAmount_ Maximum amount of quote token to purchase at the current auction price. + * @return amount_ Actual amount of reserves taken. */ function takeReserves( - uint256 maxAmount - ) external returns (uint256 amount); + uint256 maxAmount_ + ) external returns (uint256 amount_); } \ No newline at end of file From c2c9bbf05f78808bc6c9f0b96e6ae08048971043 Mon Sep 17 00:00:00 2001 From: grandizzy Date: Tue, 18 Apr 2023 14:26:24 +0300 Subject: [PATCH 02/11] Pool contracts and interfaces forge docs --- src/ERC20Pool.sol | 107 +++++++------ src/ERC20PoolFactory.sol | 18 +-- src/ERC721Pool.sol | 146 +++++++++--------- src/ERC721PoolFactory.sol | 33 ++-- src/base/Pool.sol | 8 +- src/interfaces/pool/IERC3156FlashBorrower.sol | 2 +- src/interfaces/pool/IERC3156FlashLender.sol | 1 + src/interfaces/pool/IPool.sol | 5 +- src/interfaces/pool/IPoolFactory.sol | 2 +- src/interfaces/pool/commons/IPoolErrors.sol | 40 ++--- src/interfaces/pool/commons/IPoolEvents.sol | 108 ++++++------- .../pool/commons/IPoolInternals.sol | 11 ++ .../pool/commons/IPoolKickerActions.sol | 2 +- .../pool/commons/IPoolLenderActions.sol | 14 +- .../pool/commons/IPoolSettlerActions.sol | 10 +- src/interfaces/pool/commons/IPoolState.sol | 38 ++++- .../pool/commons/IPoolTakerActions.sol | 32 ++-- src/interfaces/pool/erc20/IERC20Pool.sol | 10 +- .../pool/erc20/IERC20PoolBorrowerActions.sol | 13 +- .../pool/erc20/IERC20PoolEvents.sol | 4 +- .../pool/erc20/IERC20PoolFactory.sol | 20 +-- .../pool/erc20/IERC20PoolImmutables.sol | 2 +- .../pool/erc20/IERC20PoolLenderActions.sol | 16 +- src/interfaces/pool/erc20/IERC20Taker.sol | 4 +- src/interfaces/pool/erc721/IERC721Pool.sol | 8 +- .../erc721/IERC721PoolBorrowerActions.sol | 15 +- .../pool/erc721/IERC721PoolErrors.sol | 2 +- .../pool/erc721/IERC721PoolEvents.sol | 2 +- .../pool/erc721/IERC721PoolFactory.sol | 26 ++-- .../pool/erc721/IERC721PoolImmutables.sol | 4 +- .../pool/erc721/IERC721PoolLenderActions.sol | 32 ++-- .../pool/erc721/IERC721PoolState.sol | 32 ++-- src/interfaces/pool/erc721/IERC721Taker.sol | 6 +- 33 files changed, 419 insertions(+), 354 deletions(-) diff --git a/src/ERC20Pool.sol b/src/ERC20Pool.sol index eaad51730..048870fa9 100644 --- a/src/ERC20Pool.sol +++ b/src/ERC20Pool.sol @@ -57,17 +57,17 @@ import { TakerActions } from './libraries/external/TakerActions.sol'; /** * @title ERC20 Pool contract - * @notice Entrypoint of ERC20 Pool actions for pool actors: - * - Lenders: add, remove and move quote tokens; transfer LP - * - Borrowers: draw and repay debt - * - Traders: add, remove and move quote tokens; add and remove collateral - * - Kickers: kick undercollateralized loans; settle auctions; claim bond rewards - * - Bidders: take auctioned collateral - * - Reserve purchasers: start auctions; take reserves - * - Flash borrowers: initiate flash loans on quote tokens and collateral - * @dev Contract is FlashloanablePool with flash loan logic. - * @dev Contract is base Pool with logic to handle ERC20 collateral. - * @dev Calls logic from external PoolCommons, LenderActions, BorrowerActions and auction actions libraries. + * @notice Entrypoint of `ERC20` Pool actions for pool actors: + * - `Lenders`: add, remove and move quote tokens; transfer `LP` + * - `Borrowers`: draw and repay debt + * - `Traders`: add, remove and move quote tokens; add and remove collateral + * - `Kickers`: kick undercollateralized loans; settle auctions; claim bond rewards + * - `Bidders`: take auctioned collateral + * - `Reserve purchasers`: start auctions; take reserves + * - `Flash borrowers`: initiate flash loans on quote tokens and collateral + * @dev Contract is `FlashloanablePool` with flash loan logic. + * @dev Contract is base `Pool` with logic to handle `ERC20` collateral. + * @dev Calls logic from external `PoolCommons`, `LenderActions`, `BorrowerActions` and `Auction` actions libraries. */ contract ERC20Pool is FlashloanablePool, IERC20Pool { using SafeERC20 for IERC20; @@ -76,7 +76,7 @@ contract ERC20Pool is FlashloanablePool, IERC20Pool { /*** Constants ***/ /*****************/ - // immutable args offset + /// @dev Immutable collateral scale arg offset. uint256 internal constant COLLATERAL_SCALE = 93; /****************************/ @@ -111,8 +111,8 @@ contract ERC20Pool is FlashloanablePool, IERC20Pool { } /// @inheritdoc IERC20Pool - function bucketCollateralDust(uint256 bucketIndex) external pure override returns (uint256) { - return _bucketCollateralDust(bucketIndex); + function bucketCollateralDust(uint256 bucketIndex_) external pure override returns (uint256) { + return _bucketCollateralDust(bucketIndex_); } /***********************************/ @@ -122,11 +122,11 @@ contract ERC20Pool is FlashloanablePool, IERC20Pool { /** * @inheritdoc IERC20PoolBorrowerActions * @dev write state: - * - decrement poolBalances.t0DebtInAuction accumulator - * - increment poolBalances.pledgedCollateral accumulator - * - increment poolBalances.t0Debt accumulator + * - decrement `poolBalances.t0DebtInAuction` accumulator + * - increment `poolBalances.pledgedCollateral` accumulator + * - increment `poolBalances.t0Debt` accumulator * @dev emit events: - * - DrawDebt + * - `DrawDebt` */ function drawDebt( address borrowerAddress_, @@ -190,11 +190,11 @@ contract ERC20Pool is FlashloanablePool, IERC20Pool { /** * @inheritdoc IERC20PoolBorrowerActions * @dev write state: - * - decrement poolBalances.t0Debt accumulator - * - decrement poolBalances.t0DebtInAuction accumulator - * - decrement poolBalances.pledgedCollateral accumulator + * - decrement `poolBalances.t0Debt accumulator` + * - decrement `poolBalances.t0DebtInAuction accumulator` + * - decrement `poolBalances.pledgedCollateral accumulator` * @dev emit events: - * - RepayDebt + * - `RepayDebt` */ function repayDebt( address borrowerAddress_, @@ -263,15 +263,15 @@ contract ERC20Pool is FlashloanablePool, IERC20Pool { /** * @inheritdoc IERC20PoolLenderActions * @dev reverts on: - * - DustAmountNotExceeded() + * - `DustAmountNotExceeded()` * @dev emit events: - * - AddCollateral + * - `AddCollateral` */ function addCollateral( uint256 amountToAdd_, uint256 index_, uint256 expiry_ - ) external override nonReentrant returns (uint256 bucketLPs_) { + ) external override nonReentrant returns (uint256 bucketLP_) { _revertOnExpiry(expiry_); PoolState memory poolState = _accruePoolInterest(); @@ -279,14 +279,14 @@ contract ERC20Pool is FlashloanablePool, IERC20Pool { if (amountToAdd_ != 0 && amountToAdd_ < _bucketCollateralDust(index_)) revert DustAmountNotExceeded(); amountToAdd_ = _roundToScale(amountToAdd_, _getArgUint256(COLLATERAL_SCALE)); - bucketLPs_ = LenderActions.addCollateral( + bucketLP_ = LenderActions.addCollateral( buckets, deposits, amountToAdd_, index_ ); - emit AddCollateral(msg.sender, index_, amountToAdd_, bucketLPs_); + emit AddCollateral(msg.sender, index_, amountToAdd_, bucketLP_); // update pool interest rate state _updateInterestState(poolState, Deposits.getLup(deposits, poolState.debt)); @@ -298,12 +298,12 @@ contract ERC20Pool is FlashloanablePool, IERC20Pool { /** * @inheritdoc IPoolLenderActions * @dev emit events: - * - RemoveCollateral + * - `RemoveCollateral` */ function removeCollateral( uint256 maxAmount_, uint256 index_ - ) external override nonReentrant returns (uint256 collateralAmount_, uint256 lpAmount_) { + ) external override nonReentrant returns (uint256 removedAmount_, uint256 redeemedLP_) { _revertIfAuctionClearable(auctions, loans); PoolState memory poolState = _accruePoolInterest(); @@ -311,20 +311,20 @@ contract ERC20Pool is FlashloanablePool, IERC20Pool { // round the collateral amount appropriately based on token precision maxAmount_ = _roundToScale(maxAmount_, _getArgUint256(COLLATERAL_SCALE)); - (collateralAmount_, lpAmount_) = LenderActions.removeMaxCollateral( + (removedAmount_, redeemedLP_) = LenderActions.removeMaxCollateral( buckets, deposits, maxAmount_, index_ ); - emit RemoveCollateral(msg.sender, index_, collateralAmount_, lpAmount_); + emit RemoveCollateral(msg.sender, index_, removedAmount_, redeemedLP_); // update pool interest rate state _updateInterestState(poolState, Deposits.getLup(deposits, poolState.debt)); // move collateral from pool to lender - _transferCollateral(msg.sender, collateralAmount_); + _transferCollateral(msg.sender, removedAmount_); } /*******************************/ @@ -334,9 +334,9 @@ contract ERC20Pool is FlashloanablePool, IERC20Pool { /** * @inheritdoc IPoolSettlerActions * @dev write state: - * - decrement poolBalances.t0Debt accumulator - * - decrement poolBalances.t0DebtInAuction accumulator - * - decrement poolBalances.pledgedCollateral accumulator + * - decrement `poolBalances.t0Debt` accumulator + * - decrement `poolBalances.t0DebtInAuction` accumulator + * - decrement `poolBalances.pledgedCollateral` accumulator */ function settle( address borrowerAddress_, @@ -381,13 +381,13 @@ contract ERC20Pool is FlashloanablePool, IERC20Pool { /** * @inheritdoc IPoolTakerActions * @dev write state: - * - decrement poolBalances.t0Debt accumulator - * - decrement poolBalances.t0DebtInAuction accumulator - * - decrement poolBalances.pledgedCollateral accumulator + * - decrement `poolBalances.t0Debt` accumulator + * - decrement `poolBalances.t0DebtInAuction` accumulator + * - decrement `poolBalances.pledgedCollateral` accumulator */ function take( address borrowerAddress_, - uint256 collateral_, + uint256 maxAmount_, address callee_, bytes calldata data_ ) external override nonReentrant { @@ -396,7 +396,7 @@ contract ERC20Pool is FlashloanablePool, IERC20Pool { uint256 collateralDust = _bucketCollateralDust(0); // round requested collateral to an amount which can actually be transferred - collateral_ = _roundToScale(collateral_, collateralDust); + maxAmount_ = _roundToScale(maxAmount_, collateralDust); TakeResult memory result = TakerActions.take( auctions, @@ -405,7 +405,7 @@ contract ERC20Pool is FlashloanablePool, IERC20Pool { loans, poolState, borrowerAddress_, - collateral_, + maxAmount_, collateralDust ); // round quote token up to cover the cost of purchasing the collateral @@ -450,9 +450,9 @@ contract ERC20Pool is FlashloanablePool, IERC20Pool { /** * @inheritdoc IPoolTakerActions * @dev write state: - * - decrement poolBalances.t0Debt accumulator - * - decrement poolBalances.t0DebtInAuction accumulator - * - decrement poolBalances.pledgedCollateral accumulator + * - decrement `poolBalances.t0Debt` accumulator + * - decrement `poolBalances.t0DebtInAuction` accumulator + * - decrement `poolBalances.pledgedCollateral` accumulator */ function bucketTake( address borrowerAddress_, @@ -516,17 +516,32 @@ contract ERC20Pool is FlashloanablePool, IERC20Pool { /*** Helper Functions ***/ /************************/ + /** + * @notice Helper function to transfer amount of collateral tokens (in collateral token precision) from sender to pool contract. + * @param from_ Sender address. + * @param amount_ Amount to transfer from sender. + */ function _transferCollateralFrom(address from_, uint256 amount_) internal { IERC20(_getArgAddress(COLLATERAL_ADDRESS)).safeTransferFrom(from_, address(this), amount_ / _getArgUint256(COLLATERAL_SCALE)); } + /** + * @notice Helper function to transfer amount of collateral tokens (in collateral token precision) from pool contract. + * @param to_ Receiver address. + * @param amount_ Amount to transfer to receiver. + */ function _transferCollateral(address to_, uint256 amount_) internal { IERC20(_getArgAddress(COLLATERAL_ADDRESS)).safeTransfer(to_, amount_ / _getArgUint256(COLLATERAL_SCALE)); } - function _bucketCollateralDust(uint256 bucketIndex) internal pure returns (uint256) { + /** + * @notice Helper function to calculate the minimum amount of collateral an actor may have in a bucket. + * @param bucketIndex_ Bucket index. + * @return Amount of collateral dust amount of the bucket. + */ + function _bucketCollateralDust(uint256 bucketIndex_) internal pure returns (uint256) { // price precision adjustment will always be 0 for encumbered collateral - uint256 pricePrecisionAdjustment = _getCollateralDustPricePrecisionAdjustment(bucketIndex); + uint256 pricePrecisionAdjustment = _getCollateralDustPricePrecisionAdjustment(bucketIndex_); // difference between the normalized scale and the collateral token's scale return Maths.max(_getArgUint256(COLLATERAL_SCALE), 10 ** pricePrecisionAdjustment); } diff --git a/src/ERC20PoolFactory.sol b/src/ERC20PoolFactory.sol index 6098ea682..615c904fd 100644 --- a/src/ERC20PoolFactory.sol +++ b/src/ERC20PoolFactory.sol @@ -13,8 +13,8 @@ import { PoolDeployer } from './base/PoolDeployer.sol'; /** * @title ERC20 Pool Factory - * @notice Pool factory contract for creating ERC20 pools. Actors actions: - * - Pool creators: create pool by providing a fungible token for quote and collateral and an interest rate between 1-10% + * @notice Pool factory contract for creating `ERC20` pools. Actors actions: + * - `Pool creators`: create pool by providing a fungible token for quote and collateral and an interest rate between `1%-10%` * @dev Reverts if pool is already created or if params to deploy new pool are invalid. */ contract ERC20PoolFactory is PoolDeployer, IERC20PoolFactory { @@ -23,7 +23,7 @@ contract ERC20PoolFactory is PoolDeployer, IERC20PoolFactory { ERC20Pool public implementation; - /// @dev Default bytes32 hash used by ERC20 Non-NFTSubset pool types + /// @dev Default `bytes32` hash used by `ERC20` `Non-NFTSubset` pool types bytes32 public constant ERC20_NON_SUBSET_HASH = keccak256("ERC20_NON_SUBSET_HASH"); constructor(address ajna_) { @@ -38,14 +38,14 @@ contract ERC20PoolFactory is PoolDeployer, IERC20PoolFactory { * @inheritdoc IERC20PoolFactory * @dev immutable args: pool type; ajna, collateral and quote address; quote and collateral scale * @dev write state: - * - deployedPools mapping - * - deployedPoolsList array + * - `deployedPools` mapping + * - `deployedPoolsList` array * @dev reverts on: - * - 0x address provided as quote or collateral DeployWithZeroAddress() - * - pool with provided quote / collateral pair already exists PoolAlreadyExists() - * - invalid interest rate provided PoolInterestRateInvalid() + * - `0x` address provided as quote or collateral `DeployWithZeroAddress()` + * - pool with provided quote / collateral pair already exists `PoolAlreadyExists()` + * - invalid interest rate provided `PoolInterestRateInvalid()` * @dev emit events: - * - PoolCreated + * - `PoolCreated` */ function deployPool( address collateral_, address quote_, uint256 interestRate_ diff --git a/src/ERC721Pool.sol b/src/ERC721Pool.sol index 24432fc2f..1f16c7569 100644 --- a/src/ERC721Pool.sol +++ b/src/ERC721Pool.sol @@ -47,17 +47,17 @@ import { TakerActions } from './libraries/external/TakerActions.sol'; /** * @title ERC721 Pool contract - * @notice Entrypoint of ERC721 Pool actions for pool actors: - * - Lenders: add, remove and move quote tokens; transfer LP - * - Borrowers: draw and repay debt - * - Traders: add, remove and move quote tokens; add and remove collateral - * - Kickers: auction undercollateralized loans; settle auctions; claim bond rewards - * - Bidders: take auctioned collateral - * - Reserve purchasers: start auctions; take reserves - * - Flash borrowers: initiate flash loans on ERC20 quote tokens - * @dev Contract is FlashloanablePool with flash loan logic. - * @dev Contract is base Pool with logic to handle ERC721 collateral. - * @dev Calls logic from external PoolCommons, LenderActions, BorrowerActions and auction actions libraries. + * @notice Entrypoint of `ERC721` Pool actions for pool actors: + * - `Lenders`: add, remove and move quote tokens; transfer `LP` + * - `Borrowers`: draw and repay debt + * - `Traders`: add, remove and move quote tokens; add and remove collateral + * - `Kickers`: auction undercollateralized loans; settle auctions; claim bond rewards + * - `Bidders`: take auctioned collateral + * - `Reserve purchasers`: start auctions; take reserves + * - `Flash borrowers`: initiate flash loans on ERC20 quote tokens + * @dev Contract is `FlashloanablePool` with flashloan logic. + * @dev Contract is base `Pool` with logic to handle `ERC721` collateral. + * @dev Calls logic from external `PoolCommons`, `LenderActions`, `BorrowerActions` and `Auction` actions libraries. */ contract ERC721Pool is FlashloanablePool, IERC721Pool { @@ -65,16 +65,19 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool { /*** Constants ***/ /*****************/ - // immutable args offset - uint256 internal constant SUBSET = 93; + /// @dev Immutable NFT subset pool arg offset. + uint256 internal constant SUBSET = 93; /***********************/ /*** State Variables ***/ /***********************/ - mapping(uint256 => bool) public tokenIdsAllowed; // set of tokenIds that can be used for a given NFT Subset type pool - mapping(address => uint256[]) public borrowerTokenIds; // borrower address => array of tokenIds pledged by borrower - uint256[] public bucketTokenIds; // array of tokenIds added in pool buckets + /// @dev Mapping of `tokenIds` allowed in `NFT` Subset type pool. + mapping(uint256 => bool) public tokenIdsAllowed; + /// @dev Borrower `address => array` of tokenIds pledged by borrower mapping. + mapping(address => uint256[]) public borrowerTokenIds; + /// @dev Array of `tokenIds` in pool buckets (claimable from pool). + uint256[] public bucketTokenIds; /****************************/ /*** Initialize Functions ***/ @@ -126,12 +129,12 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool { /** * @inheritdoc IERC721PoolBorrowerActions * @dev write state: - * - decrement poolBalances.t0DebtInAuction accumulator - * - increment poolBalances.pledgedCollateral accumulator - * - increment poolBalances.t0Debt accumulator - * - update borrowerTokenIds and bucketTokenIds arrays + * - decrement `poolBalances.t0DebtInAuction` accumulator + * - increment `poolBalances.pledgedCollateral` accumulator + * - increment `poolBalances.t0Debt` accumulator + * - update `borrowerTokenIds` and `bucketTokenIds` arrays * @dev emit events: - * - DrawDebtNFT + * - `DrawDebtNFT` */ function drawDebt( address borrowerAddress_, @@ -195,12 +198,12 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool { /** * @inheritdoc IERC721PoolBorrowerActions * @dev write state: - * - decrement poolBalances.t0Debt accumulator - * - decrement poolBalances.t0DebtInAuction accumulator - * - decrement poolBalances.pledgedCollateral accumulator - * - update borrowerTokenIds and bucketTokenIds arrays + * - decrement `poolBalances.t0Debt` accumulator + * - decrement `poolBalances.t0DebtInAuction` accumulator + * - decrement `poolBalances.pledgedCollateral` accumulator + * - update `borrowerTokenIds` and bucketTokenIds` arrays * @dev emit events: - * - RepayDebt + * - `RepayDebt` */ function repayDebt( address borrowerAddress_, @@ -267,46 +270,46 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool { /** * @inheritdoc IERC721PoolLenderActions * @dev write state: - * - update bucketTokenIds arrays + * - update `bucketTokenIds` arrays * @dev emit events: - * - AddCollateralNFT + * - `AddCollateralNFT` */ function addCollateral( - uint256[] calldata tokenIdsToAdd_, + uint256[] calldata tokenIds_, uint256 index_, uint256 expiry_ - ) external override nonReentrant returns (uint256 bucketLPs_) { + ) external override nonReentrant returns (uint256 bucketLP_) { _revertOnExpiry(expiry_); PoolState memory poolState = _accruePoolInterest(); - bucketLPs_ = LenderActions.addCollateral( + bucketLP_ = LenderActions.addCollateral( buckets, deposits, - Maths.wad(tokenIdsToAdd_.length), + Maths.wad(tokenIds_.length), index_ ); - emit AddCollateralNFT(msg.sender, index_, tokenIdsToAdd_, bucketLPs_); + emit AddCollateralNFT(msg.sender, index_, tokenIds_, bucketLP_); // update pool interest rate state _updateInterestState(poolState, Deposits.getLup(deposits, poolState.debt)); // move required collateral from sender to pool - _transferFromSenderToPool(bucketTokenIds, tokenIdsToAdd_); + _transferFromSenderToPool(bucketTokenIds, tokenIds_); } /** * @inheritdoc IERC721PoolLenderActions * @dev write state: - * - update bucketTokenIds arrays + * - update `bucketTokenIds` arrays * @dev emit events: - * - MergeOrRemoveCollateralNFT + * - `MergeOrRemoveCollateralNFT` */ function mergeOrRemoveCollateral( uint256[] calldata removalIndexes_, uint256 noOfNFTsToRemove_, uint256 toIndex_ - ) external override nonReentrant returns (uint256 collateralMerged_, uint256 bucketLPs_) { + ) external override nonReentrant returns (uint256 collateralMerged_, uint256 bucketLP_) { _revertIfAuctionClearable(auctions, loans); PoolState memory poolState = _accruePoolInterest(); @@ -314,7 +317,7 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool { ( collateralMerged_, - bucketLPs_ + bucketLP_ ) = LenderActions.mergeOrRemoveCollateral( buckets, deposits, @@ -323,7 +326,7 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool { toIndex_ ); - emit MergeOrRemoveCollateralNFT(msg.sender, collateralMerged_, bucketLPs_); + emit MergeOrRemoveCollateralNFT(msg.sender, collateralMerged_, bucketLP_); // update pool interest rate state _updateInterestState(poolState, Deposits.getLup(deposits, poolState.debt)); @@ -338,27 +341,28 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool { /** * @inheritdoc IPoolLenderActions * @dev write state: - * - update bucketTokenIds arrays + * - update `bucketTokenIds` arrays * @dev emit events: - * - RemoveCollateral + * - `RemoveCollateral` + * @param noOfNFTsToRemove_ Number of `NFT` tokens to remove. */ function removeCollateral( uint256 noOfNFTsToRemove_, uint256 index_ - ) external override nonReentrant returns (uint256 collateralAmount_, uint256 lpAmount_) { + ) external override nonReentrant returns (uint256 removedAmount_, uint256 redeemedLP_) { _revertIfAuctionClearable(auctions, loans); PoolState memory poolState = _accruePoolInterest(); - collateralAmount_ = Maths.wad(noOfNFTsToRemove_); - lpAmount_ = LenderActions.removeCollateral( + removedAmount_ = Maths.wad(noOfNFTsToRemove_); + redeemedLP_ = LenderActions.removeCollateral( buckets, deposits, - collateralAmount_, + removedAmount_, index_ ); - emit RemoveCollateral(msg.sender, index_, noOfNFTsToRemove_, lpAmount_); + emit RemoveCollateral(msg.sender, index_, noOfNFTsToRemove_, redeemedLP_); // update pool interest rate state _updateInterestState(poolState, Deposits.getLup(deposits, poolState.debt)); @@ -373,9 +377,9 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool { /** * @inheritdoc IPoolSettlerActions * @dev write state: - * - decrement poolBalances.t0Debt accumulator - * - decrement poolBalances.t0DebtInAuction accumulator - * - decrement poolBalances.pledgedCollateral accumulator + * - decrement `poolBalances.t0Debt` accumulator + * - decrement `poolBalances.t0DebtInAuction` accumulator + * - decrement `poolBalances.pledgedCollateral` accumulator */ function settle( address borrowerAddress_, @@ -425,9 +429,9 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool { /** * @inheritdoc IPoolTakerActions * @dev write state: - * - decrement poolBalances.t0Debt accumulator - * - decrement poolBalances.t0DebtInAuction accumulator - * - decrement poolBalances.pledgedCollateral accumulator + * - decrement `poolBalances.t0Debt` accumulator + * - decrement `poolBalances.t0DebtInAuction` accumulator + * - decrement `poolBalances.pledgedCollateral` accumulator */ function take( address borrowerAddress_, @@ -503,9 +507,9 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool { /** * @inheritdoc IPoolTakerActions * @dev write state: - * - decrement poolBalances.t0Debt accumulator - * - decrement poolBalances.t0DebtInAuction accumulator - * - decrement poolBalances.pledgedCollateral accumulator + * - decrement `poolBalances.t0Debt` accumulator + * - decrement `poolBalances.t0DebtInAuction` accumulator + * - decrement `poolBalances.pledgedCollateral` accumulator */ function bucketTake( address borrowerAddress_, @@ -561,11 +565,11 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool { /**************************/ /** - * @notice Rebalance NFT token and transfer difference to floor collateral from borrower to pool claimable array + * @notice Rebalance `NFT` token and transfer difference to floor collateral from borrower to pool claimable array. * @dev write state: - * - update borrowerTokens and bucketTokenIds arrays + * - update `borrowerTokens` and `bucketTokenIds` arrays * @dev emit events: - * - RemoveCollateral + * - `RemoveCollateral` * @param borrowerAddress_ Address of borrower. * @param borrowerCollateral_ Current borrower collateral to be rebalanced. */ @@ -594,10 +598,10 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool { } /** - * @notice Helper function for transferring multiple NFT tokens from msg.sender to pool. - * @notice Reverts in case token id is not supported by subset pool. - * @param poolTokens_ Array in pool that tracks NFT ids (could be tracking NFTs pledged by borrower or NFTs added by a lender in a specific bucket). - * @param tokenIds_ Array of NFT token ids to transfer from msg.sender to pool. + * @notice Helper function for transferring multiple `NFT` tokens from msg.sender to pool. + * @dev Reverts in case token id is not supported by subset pool. + * @param poolTokens_ Array in pool that tracks `NFT` ids (could be tracking `NFT`s pledged by borrower or `NFT`s added by a lender in a specific bucket). + * @param tokenIds_ Array of `NFT` token ids to transfer from `msg.sender` to pool. */ function _transferFromSenderToPool( uint256[] storage poolTokens_, @@ -617,11 +621,11 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool { } /** - * @notice Helper function for transferring multiple NFT tokens from pool to given address. - * @notice It transfers NFTs from the most recent one added into the pool (pop from array tracking NFTs in pool). + * @notice Helper function for transferring multiple `NFT` tokens from pool to given address. + * @dev It transfers `NFT`s from the most recent one added into the pool (pop from array tracking `NFT`s in pool). * @param toAddress_ Address where pool should transfer tokens to. - * @param poolTokens_ Array in pool that tracks NFT ids (could be tracking NFTs pledged by borrower or NFTs added by a lender in a specific bucket). - * @param amountToRemove_ Number of NFT tokens to transfer from pool to given address. + * @param poolTokens_ Array in pool that tracks `NFT` ids (could be tracking `NFT`s pledged by borrower or `NFT`s added by a lender in a specific bucket). + * @param amountToRemove_ Number of `NFT` tokens to transfer from pool to given address. * @return Array containing token ids that were transferred from pool to address. */ function _transferFromPoolToAddress( @@ -648,11 +652,11 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool { } /** - * @dev Helper function to transfer an NFT from owner to target address (reused in code to reduce contract deployment bytecode size). - * @dev Since transferFrom is used instead of safeTransferFrom, calling smart contracts must be careful to check that they support any received NFTs. - * @param from_ NFT owner address. - * @param to_ New NFT owner address. - * @param tokenId_ NFT token id to be transferred. + * @notice Helper function to transfer an `NFT` from owner to target address (reused in code to reduce contract deployment bytecode size). + * @dev Since `transferFrom` is used instead of `safeTransferFrom`, calling smart contracts must be careful to check that they support any received `NFT`s. + * @param from_ `NFT` owner address. + * @param to_ New `NFT` owner address. + * @param tokenId_ `NFT` token id to be transferred. */ function _transferNFT(address from_, address to_, uint256 tokenId_) internal { // slither-disable-next-line calls-loop diff --git a/src/ERC721PoolFactory.sol b/src/ERC721PoolFactory.sol index ef1da0440..4f57f95a1 100644 --- a/src/ERC721PoolFactory.sol +++ b/src/ERC721PoolFactory.sol @@ -14,8 +14,9 @@ import { PoolDeployer } from './base/PoolDeployer.sol'; /** * @title ERC721 Pool Factory - * @notice Pool factory contract for creating ERC721 pools. If a list with token ids is provided then a subset ERC721 pool is created for the NFT. - * @notice Pool creators can: create pool by providing a fungible token for quote, a non fungible token for collateral and an interest rate between 1-10% + * @notice Pool factory contract for creating `ERC721` pools. If a list with token ids is provided then a subset `ERC721` pool is created for the `NFT`. + * @notice Pool factory contract for creating `ERC20` pools. If a list with token ids is provided then a subset `ERC721` pool is created for the `NFT`. Actors actions: + * - `Pool creators`: create pool by providing a fungible token for quote, a non fungible token for collateral and an interest rate between `1%-10%`. * @dev Reverts if pool is already created or if params to deploy new pool are invalid. */ contract ERC721PoolFactory is PoolDeployer, IERC721PoolFactory { @@ -24,7 +25,7 @@ contract ERC721PoolFactory is PoolDeployer, IERC721PoolFactory { ERC721Pool public implementation; - /// @dev Default bytes32 hash used by ERC721 Non-NFTSubset pool types + /// @dev Default `bytes32` hash used by `ERC721` `Non-NFTSubset` pool types bytes32 public constant ERC721_NON_SUBSET_HASH = keccak256("ERC721_NON_SUBSET_HASH"); constructor(address ajna_) { @@ -40,15 +41,15 @@ contract ERC721PoolFactory is PoolDeployer, IERC721PoolFactory { * @dev immutable args: * - pool type; ajna, collateral and quote address; quote scale; number of token ids in subset; NFT type * @dev write state: - * - deployedPools mapping - * - deployedPoolsList array + * - `deployedPools` mapping + * - `deployedPoolsList` array * @dev reverts on: - * - 0x address provided as quote or collateral DeployWithZeroAddress() - * - pool with provided quote / collateral pair already exists PoolAlreadyExists() - * - invalid interest rate provided PoolInterestRateInvalid() - * - not supported NFT provided NFTNotSupported() + * - `0x` address provided as quote or collateral `DeployWithZeroAddress()` + * - pool with provided quote / collateral pair already exists `PoolAlreadyExists()` + * - invalid interest rate provided `PoolInterestRateInvalid()` + * - not supported `NFT` provided `NFTNotSupported()` * @dev emit events: - * - PoolCreated + * - `PoolCreated` */ function deployPool( address collateral_, address quote_, uint256[] memory tokenIds_, uint256 interestRate_ @@ -91,10 +92,10 @@ contract ERC721PoolFactory is PoolDeployer, IERC721PoolFactory { /*******************************/ /** - * @notice Get the hash of the subset of NFTs that will be used to create the pool - * @dev If no tokenIds are provided, the default ERC721_NON_SUBSET_HASH is returned - * @param tokenIds_ The array of token ids that will be used to create the pool - * @return bytes32 The hash of the subset of NFTs that will be used to create the pool + * @notice Get the hash of the subset of `NFT`s that will be used to create the pool. + * @dev If no `tokenIds` are provided, the default `ERC721_NON_SUBSET_HASH` is returned. + * @param tokenIds_ The array of token ids that will be used to create the pool. + * @return The hash of the subset of `NFT`s that will be used to create the pool. */ function getNFTSubsetHash(uint256[] memory tokenIds_) public pure returns (bytes32) { if (tokenIds_.length == 0) return ERC721_NON_SUBSET_HASH; @@ -110,8 +111,8 @@ contract ERC721PoolFactory is PoolDeployer, IERC721PoolFactory { /** * @notice Check that the array of token ids is sorted in ascending order, else revert. - * @dev The counters are modified in unchecked blocks due to being bounded by array length - * @param tokenIds_ The array of token ids to check for sorting + * @dev The counters are modified in unchecked blocks due to being bounded by array length. + * @param tokenIds_ The array of token ids to check for sorting. */ function _checkTokenIdSortOrder(uint256[] memory tokenIds_) internal pure { for (uint256 i = 0; i < tokenIds_.length - 1; ) { diff --git a/src/base/Pool.sol b/src/base/Pool.sol index a35da401d..135471bf4 100644 --- a/src/base/Pool.sol +++ b/src/base/Pool.sol @@ -77,11 +77,15 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { /*** Constants ***/ /*****************/ - // immutable args offset + /// @dev Immutable pool type arg offset. uint256 internal constant POOL_TYPE = 0; + /// @dev Immutable `Ajna` token address arg offset. uint256 internal constant AJNA_ADDRESS = 1; + /// @dev Immutable collateral token address arg offset. uint256 internal constant COLLATERAL_ADDRESS = 21; + /// @dev Immutable quote token address arg offset. uint256 internal constant QUOTE_ADDRESS = 41; + /// @dev Immutable quote token scale arg offset. uint256 internal constant QUOTE_SCALE = 61; /***********************/ @@ -97,7 +101,7 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { PoolBalancesState internal poolBalances; ReserveAuctionState internal reserveAuction; - /// @dev deposit index -> bucket mapping + /// @dev deposit index -> bucket mapping mapping(uint256 => Bucket) internal buckets; bool internal isPoolInitialized; diff --git a/src/interfaces/pool/IERC3156FlashBorrower.sol b/src/interfaces/pool/IERC3156FlashBorrower.sol index 8e23435e7..8f009d100 100644 --- a/src/interfaces/pool/IERC3156FlashBorrower.sol +++ b/src/interfaces/pool/IERC3156FlashBorrower.sol @@ -11,7 +11,7 @@ interface IERC3156FlashBorrower { * @param amount The amount of tokens lent. * @param fee The additional amount of tokens to repay. * @param data Arbitrary data structure, intended to contain user-defined parameters. - * @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan" + * @return The `keccak256` hash of `ERC3156FlashBorrower.onFlashLoan` */ function onFlashLoan( address initiator, diff --git a/src/interfaces/pool/IERC3156FlashLender.sol b/src/interfaces/pool/IERC3156FlashLender.sol index 84f0b8ecd..a301305f9 100644 --- a/src/interfaces/pool/IERC3156FlashLender.sol +++ b/src/interfaces/pool/IERC3156FlashLender.sol @@ -32,6 +32,7 @@ interface IERC3156FlashLender { * @param token_ The loan currency. * @param amount_ The amount of tokens lent. * @param data_ Arbitrary data structure, intended to contain user-defined parameters. + * @return `True` when successful flashloan, `false` otherwise. */ function flashLoan( IERC3156FlashBorrower receiver_, diff --git a/src/interfaces/pool/IPool.sol b/src/interfaces/pool/IPool.sol index 63ad3b669..f3e77ea35 100644 --- a/src/interfaces/pool/IPool.sol +++ b/src/interfaces/pool/IPool.sol @@ -17,7 +17,7 @@ import { IPoolErrors } from './commons/IPoolErrors.sol'; import { IERC3156FlashLender } from './IERC3156FlashLender.sol'; /** - * @title Base Pool + * @title Base Pool Interface */ interface IPool is IPoolBorrowerActions, @@ -36,8 +36,10 @@ interface IPool is } +/// @dev Pool type enum - `ERC20` and `ERC721` enum PoolType { ERC20, ERC721 } +/// @dev `ERC20` token interface. interface IERC20Token { function balanceOf(address account) external view returns (uint256); function burn(uint256 amount) external; @@ -50,6 +52,7 @@ interface IERC20Token { ) external returns (bool); } +/// @dev `ERC721` token interface. interface IERC721Token { function transferFrom( address from, diff --git a/src/interfaces/pool/IPoolFactory.sol b/src/interfaces/pool/IPoolFactory.sol index bcf64a367..83cdacc64 100644 --- a/src/interfaces/pool/IPoolFactory.sol +++ b/src/interfaces/pool/IPoolFactory.sol @@ -3,7 +3,7 @@ pragma solidity 0.8.14; /** - * @title Pool Factory Interface + * @title Pool Factory Interface. * @dev Used to deploy both funigible and non fungible pools. */ interface IPoolFactory { diff --git a/src/interfaces/pool/commons/IPoolErrors.sol b/src/interfaces/pool/commons/IPoolErrors.sol index 3a9351f3b..440fb7c91 100644 --- a/src/interfaces/pool/commons/IPoolErrors.sol +++ b/src/interfaces/pool/commons/IPoolErrors.sol @@ -3,7 +3,7 @@ pragma solidity 0.8.14; /** - * @title Pool Errors + * @title Pool Errors. */ interface IPoolErrors { /**************************/ @@ -11,7 +11,7 @@ interface IPoolErrors { /**************************/ /** - * @notice LP allowance is already set by the owner. + * @notice `LP` allowance is already set by the owner. */ error AllowanceAlreadySet(); @@ -46,7 +46,7 @@ interface IPoolErrors { error AmountLTMinDebt(); /** - * @notice Recipient of borrowed quote tokens doesn't match the caller of the drawDebt function. + * @notice Recipient of borrowed quote tokens doesn't match the caller of the `drawDebt` function. */ error BorrowerNotSender(); @@ -76,12 +76,12 @@ interface IPoolErrors { error DustAmountNotExceeded(); /** - * @notice Callback invoked by flashLoan function did not return the expected hash (see ERC-3156 spec). + * @notice Callback invoked by `flashLoan` function did not return the expected hash (see `ERC-3156` spec). */ error FlashloanCallbackFailed(); /** - * @notice Balance of pool contract before flash loan is different than the balance after flash loan. + * @notice Balance of pool contract before flashloan is different than the balance after flashloan. */ error FlashloanIncorrectBalance(); @@ -98,7 +98,7 @@ interface IPoolErrors { /** * @notice Lender is attempting to move or remove more collateral they have claim to in the bucket. * @notice Lender is attempting to remove more collateral they have claim to in the bucket. - * @notice Lender must have enough LP to claim the desired amount of quote from the bucket. + * @notice Lender must have enough `LP` to claim the desired amount of quote from the bucket. */ error InsufficientLP(); @@ -108,33 +108,33 @@ interface IPoolErrors { error InsufficientLiquidity(); /** - * @notice When increasing / decreasing LP allowances indexes and amounts arrays parameters should have same length. + * @notice When increasing / decreasing `LP` allowances indexes and amounts arrays parameters should have same length. */ error InvalidAllowancesInput(); /** - * @notice When transferring LP between indices, the new index must be a valid index. + * @notice When transferring `LP` between indices, the new index must be a valid index. */ error InvalidIndex(); /** - * @notice The amount used for performed action should be greater than 0. + * @notice The amount used for performed action should be greater than `0`. */ error InvalidAmount(); /** - * @notice Borrower is attempting to borrow more quote token than is available before the supplied limitIndex. + * @notice Borrower is attempting to borrow more quote token than is available before the supplied `limitIndex`. */ error LimitIndexExceeded(); /** - * @notice When moving quote token HTP must stay below LUP. - * @notice When removing quote token HTP must stay below LUP. + * @notice When moving quote token `HTP` must stay below `LUP`. + * @notice When removing quote token `HTP` must stay below `LUP`. */ error LUPBelowHTP(); /** - * @notice Liquidation must result in LUP below the borrowers threshold price. + * @notice Liquidation must result in `LUP` below the borrowers threshold price. */ error LUPGreaterThanTP(); @@ -144,7 +144,7 @@ interface IPoolErrors { error MoveToSameIndex(); /** - * @notice Owner of the LP must have approved the new owner prior to transfer. + * @notice Owner of the `LP` must have approved the new owner prior to transfer. */ error NoAllowance(); @@ -164,7 +164,7 @@ interface IPoolErrors { error NoReservesAuction(); /** - * @notice Lender must have non-zero LPB when attemptign to remove quote token from the pool. + * @notice Lender must have non-zero `LP` when attemptign to remove quote token from the pool. */ error NoClaim(); @@ -180,7 +180,7 @@ interface IPoolErrors { error PoolUnderCollateralized(); /** - * @notice Actor is attempting to remove using a bucket with price below the LUP. + * @notice Actor is attempting to remove using a bucket with price below the `LUP`. */ error PriceBelowLUP(); @@ -190,12 +190,12 @@ interface IPoolErrors { error RemoveDepositLockedByAuctionDebt(); /** - * @notice User attempted to kick off a new auction less than 2 weeks since the last auction completed. + * @notice User attempted to kick off a new auction less than `2` weeks since the last auction completed. */ error ReserveAuctionTooSoon(); /** - * @notice Take was called before 1 hour had passed from kick time. + * @notice Take was called before `1` hour had passed from kick time. */ error TakeNotPastCooldown(); @@ -205,12 +205,12 @@ interface IPoolErrors { error TransactionExpired(); /** - * @notice The address that transfer LP is not approved by the LP receiving address. + * @notice The address that transfer `LP` is not approved by the `LP` receiving address. */ error TransferorNotApproved(); /** - * @notice Owner of the LP attemps to transfer LP to same address. + * @notice Owner of the `LP` attemps to transfer `LP` to same address. */ error TransferToSameOwner(); diff --git a/src/interfaces/pool/commons/IPoolEvents.sol b/src/interfaces/pool/commons/IPoolEvents.sol index adcaa6321..1f8ef2061 100644 --- a/src/interfaces/pool/commons/IPoolEvents.sol +++ b/src/interfaces/pool/commons/IPoolEvents.sol @@ -16,8 +16,8 @@ interface IPoolEvents { * @param lender Recipient that added quote tokens. * @param index Index at which quote tokens were added. * @param amount Amount of quote tokens added to the pool. - * @param lpAwarded Amount of LP awarded for the deposit. - * @param lup LUP calculated after deposit. + * @param lpAwarded Amount of `LP` awarded for the deposit. + * @param lup `LUP` calculated after deposit. */ event AddQuoteToken( address indexed lender, @@ -33,9 +33,9 @@ interface IPoolEvents { * @param from Price bucket from which quote tokens were moved. * @param to Price bucket where quote tokens were moved. * @param amount Amount of quote tokens moved. - * @param lpRedeemedFrom Amount of LP removed from the `from` bucket. - * @param lpAwardedTo Amount of LP credited to the `to` bucket. - * @param lup LUP calculated after removal. + * @param lpRedeemedFrom Amount of `LP` removed from the `from` bucket. + * @param lpAwardedTo Amount of `LP` credited to the `to` bucket. + * @param lup `LUP` calculated after removal. */ event MoveQuoteToken( address indexed lender, @@ -52,8 +52,8 @@ interface IPoolEvents { * @param lender Recipient that removed quote tokens. * @param index Index at which quote tokens were removed. * @param amount Amount of quote tokens removed from the pool. - * @param lpRedeemed Amount of LP exchanged for quote token. - * @param lup LUP calculated after removal. + * @param lpRedeemed Amount of `LP` exchanged for quote token. + * @param lup `LUP` calculated after removal. */ event RemoveQuoteToken( address indexed lender, @@ -67,8 +67,8 @@ interface IPoolEvents { * @notice Emitted when lender claims collateral from a bucket. * @param claimer Recipient that claimed collateral. * @param index Index at which collateral was claimed. - * @param amount The amount of collateral (or number of NFT tokens) transferred to the claimer. - * @param lpRedeemed Amount of LP exchanged for quote token. + * @param amount The amount of collateral (or number of `NFT` tokens) transferred to the claimer. + * @param lpRedeemed Amount of `LP` exchanged for quote token. */ event RemoveCollateral( address indexed claimer, @@ -82,11 +82,11 @@ interface IPoolEvents { /***********************/ /** - * @notice Emitted when borrower repays quote tokens to the pool, and/or pulls collateral from the pool. + * @notice Emitted when borrower repays quote tokens to the pool and/or pulls collateral from the pool. * @param borrower `msg.sender` or on behalf of sender. * @param quoteRepaid Amount of quote tokens repaid to the pool. - * @param collateralPulled The amount of collateral (or number of NFT tokens) transferred to the claimer. - * @param lup LUP after repay. + * @param collateralPulled The amount of collateral (or number of `NFT` tokens) transferred to the claimer. + * @param lup `LUP` after repay. */ event RepayDebt( address indexed borrower, @@ -128,11 +128,11 @@ interface IPoolEvents { /** * @notice Emitted when an actor uses quote token to arb higher-priced deposit off the book. * @param borrower Identifies the loan being liquidated. - * @param index The index of the Highest Price Bucket used for this take. + * @param index The index of the `Highest Price Bucket` used for this take. * @param amount Amount of quote token used to purchase collateral. * @param collateral Amount of collateral purchased with quote token. * @param bondChange Impact of this take to the liquidation bond. - * @param isReward True if kicker was rewarded with `bondChange` amount, false if kicker was penalized. + * @param isReward `True` if kicker was rewarded with `bondChange` amount, `false` if kicker was penalized. * @dev amount / collateral implies the auction price. */ event BucketTake( @@ -145,11 +145,11 @@ interface IPoolEvents { ); /** - * @notice Emitted when LP are awarded to a taker or kicker in a bucket take. + * @notice Emitted when `LP` are awarded to a taker or kicker in a bucket take. * @param taker Actor who invoked the bucket take. * @param kicker Actor who started the auction. - * @param lpAwardedTaker Amount of LP awarded to the taker. - * @param lpAwardedKicker Amount of LP awarded to the actor who started the auction. + * @param lpAwardedTaker Amount of `LP` awarded to the taker. + * @param lpAwardedKicker Amount of `LP` awarded to the actor who started the auction. */ event BucketTakeLPAwarded( address indexed taker, @@ -162,9 +162,9 @@ interface IPoolEvents { * @notice Emitted when an actor uses quote token outside of the book to purchase collateral under liquidation. * @param borrower Identifies the loan being liquidated. * @param amount Amount of quote token used to purchase collateral. - * @param collateral Amount of collateral purchased with quote token (ERC20 pool) or number of NFTs purchased (ERC721 pool). + * @param collateral Amount of collateral purchased with quote token (`ERC20` pool) or number of `NFT`s purchased (`ERC721` pool). * @param bondChange Impact of this take to the liquidation bond. - * @param isReward True if kicker was rewarded with `bondChange` amount, false if kicker was penalized. + * @param isReward `True` if kicker was rewarded with `bondChange` amount, `false` if kicker was penalized. * @dev amount / collateral implies the auction price. */ event Take( @@ -179,7 +179,7 @@ interface IPoolEvents { * @notice Emitted when an actor settles debt in a completed liquidation * @param borrower Identifies the loan under liquidation. * @param settledDebt Amount of pool debt settled in this transaction. - * @dev When amountRemaining_ == 0, the auction has been completed cleared and removed from the queue. + * @dev When `amountRemaining_ == 0`, the auction has been completed cleared and removed from the queue. */ event Settle( address indexed borrower, @@ -197,11 +197,11 @@ interface IPoolEvents { ); /** - * @notice Emitted when NFT auction is completed. + * @notice Emitted when `NFT` auction is completed. * @param borrower Address of borrower that exits auction. * @param collateral Borrower's remaining collateral when auction completed. - * @param lps Amount of LP given to the borrower to compensate fractional collateral (if any). - * @param index Index of the bucket with LP to compensate fractional collateral. + * @param lps Amount of `LP` given to the borrower to compensate fractional collateral (if any). + * @param index Index of the bucket with `LP` to compensate fractional collateral. */ event AuctionNFTSettle( address indexed borrower, @@ -211,9 +211,9 @@ interface IPoolEvents { ); /** - * @notice Emitted when a Claimaible Reserve Auction is started. + * @notice Emitted when a `Claimaible Reserve Auction` is started. * @return claimableReservesRemaining Amount of claimable reserves which has not yet been taken. - * @return auctionPrice Current price at which 1 quote token may be purchased, denominated in Ajna. + * @return auctionPrice Current price at which `1` quote token may be purchased, denominated in `Ajna`. * @return currentBurnEpoch Current burn epoch. */ event KickReserveAuction( @@ -223,9 +223,9 @@ interface IPoolEvents { ); /** - * @notice Emitted when a Claimaible Reserve Auction is taken. + * @notice Emitted when a `Claimaible Reserve Auction` is taken. * @return claimableReservesRemaining Amount of claimable reserves which has not yet been taken. - * @return auctionPrice Current price at which 1 quote token may be purchased, denominated in Ajna. + * @return auctionPrice Current price at which `1` quote token may be purchased, denominated in `Ajna`. * @return currentBurnEpoch Current burn epoch. */ event ReserveAuction( @@ -239,11 +239,11 @@ interface IPoolEvents { /**************************/ /** - * @notice Emitted when owner increase the LP allowance of a spender at specified indexes with specified amounts. - * @param owner LP owner. - * @param spender Address approved to transfer LP. - * @param indexes Bucket indexes of LP approved. - * @param amounts LP amounts added (ordered by indexes). + * @notice Emitted when owner increase the `LP` allowance of a spender at specified indexes with specified amounts. + * @param owner `LP` owner. + * @param spender Address approved to transfer `LP`. + * @param indexes Bucket indexes of `LP` approved. + * @param amounts `LP` amounts added (ordered by indexes). */ event IncreaseLPAllowance( address indexed owner, @@ -253,11 +253,11 @@ interface IPoolEvents { ); /** - * @notice Emitted when owner decrease the LP allowance of a spender at specified indexes with specified amounts. - * @param owner LP owner. - * @param spender Address approved to transfer LP. - * @param indexes Bucket indexes of LP approved. - * @param amounts LP amounts removed (ordered by indexes). + * @notice Emitted when owner decrease the `LP` allowance of a spender at specified indexes with specified amounts. + * @param owner `LP` owner. + * @param spender Address approved to transfer `LP`. + * @param indexes Bucket indexes of `LP` approved. + * @param amounts `LP` amounts removed (ordered by indexes). */ event DecreaseLPAllowance( address indexed owner, @@ -267,8 +267,8 @@ interface IPoolEvents { ); /** - * @notice Emitted when lender removes the allowance of a spender for their LP. - * @param owner LP owner. + * @notice Emitted when lender removes the allowance of a spender for their `LP`. + * @param owner `LP` owner. * @param spender Address that is having it's allowance revoked. * @param indexes List of bucket index to remove the allowance from. */ @@ -279,9 +279,9 @@ interface IPoolEvents { ); /** - * @notice Emitted when lender whitelists addresses to accept LP from. - * @param lender Recipient that approves new owner for LP. - * @param transferors List of addresses that can transfer LP to lender. + * @notice Emitted when lender whitelists addresses to accept `LP` from. + * @param lender Recipient that approves new owner for `LP`. + * @param transferors List of addresses that can transfer `LP` to lender. */ event ApproveLPTransferors( address indexed lender, @@ -289,9 +289,9 @@ interface IPoolEvents { ); /** - * @notice Emitted when lender removes addresses from the LP transferors whitelist. - * @param lender Recipient that approves new owner for LP. - * @param transferors List of addresses that won't be able to transfer LP to lender anymore. + * @notice Emitted when lender removes addresses from the `LP` transferors whitelist. + * @param lender Recipient that approves new owner for `LP`. + * @param transferors List of addresses that won't be able to transfer `LP` to lender anymore. */ event RevokeLPTransferors( address indexed lender, @@ -299,12 +299,12 @@ interface IPoolEvents { ); /** - * @notice Emitted when a lender transfers their LP to a different address. - * @dev Used by PositionManager.memorializePositions(). + * @notice Emitted when a lender transfers their `LP` to a different address. + * @dev Used by `PositionManager.memorializePositions()`. * @param owner The original owner address of the position. * @param newOwner The new owner address of the position. - * @param indexes Array of price bucket indexes at which LP were transferred. - * @param lps Amount of LP transferred. + * @param indexes Array of price bucket indexes at which `LP` were transferred. + * @param lps Amount of `LP` transferred. */ event TransferLP( address owner, @@ -318,9 +318,9 @@ interface IPoolEvents { /**************************/ /** - * @notice Emitted when LP are forfeited as a result of the bucket losing all assets. + * @notice Emitted when `LP` are forfeited as a result of the bucket losing all assets. * @param index The index of the bucket. - * @param lpForfeited Amount of LP forfeited by lenders. + * @param lpForfeited Amount of `LP` forfeited by lenders. */ event BucketBankruptcy( uint256 indexed index, @@ -340,15 +340,15 @@ interface IPoolEvents { ); /** - * @notice Emitted when a loan Neutral Price is restamped. - * @param borrower Identifies the loan to update the Neutral Price. + * @notice Emitted when a loan `Neutral Price` is restamped. + * @param borrower Identifies the loan to update the `Neutral Price`. */ event LoanStamped( address indexed borrower ); /** - * @notice Emitted when pool interest rate is reset. This happens when interest rate > 10% and debtEma < 5% of depositEma + * @notice Emitted when pool interest rate is reset. This happens when `interest rate > 10%` and `debtEma < 5%` of `depositEma` * @param oldRate Old pool interest rate. * @param newRate New pool interest rate. */ diff --git a/src/interfaces/pool/commons/IPoolInternals.sol b/src/interfaces/pool/commons/IPoolInternals.sol index 002ca9f2e..8a82801db 100644 --- a/src/interfaces/pool/commons/IPoolInternals.sol +++ b/src/interfaces/pool/commons/IPoolInternals.sol @@ -10,6 +10,7 @@ pragma solidity 0.8.14; /*** Auction Param Structs ***/ /*****************************/ +/// @dev Struct used to return result of `TakerAction.bucketTake` action. struct BucketTakeResult { uint256 collateralAmount; // [WAD] amount of collateral taken uint256 compensatedCollateral; // [WAD] amount of borrower collateral that is compensated with LP @@ -26,6 +27,7 @@ struct BucketTakeResult { uint256 collateralPostAction; // [WAD] The amount of borrower collateral after take } +/// @dev Struct used to return result of `KickerAction.kick` action. struct KickResult { uint256 amountToCoverBond; // [WAD] amount of bond that needs to be covered uint256 t0PoolDebt; // [WAD] t0 debt in pool after kick @@ -35,12 +37,14 @@ struct KickResult { uint256 collateralPreAction; // [WAD] The amount of borrower collateral before kick, same as the one after kick } +/// @dev Struct used to hold parameters for `SettlerAction.settlePoolDebt` action. struct SettleParams { address borrower; // borrower address to settle uint256 bucketDepth; // number of buckets to use when settle debt uint256 poolBalance; // current pool quote token balance } +/// @dev Struct used to return result of `SettlerAction.settlePoolDebt` action. struct SettleResult { uint256 debtPreAction; // [WAD] The amount of borrower t0 debt before settle uint256 debtPostAction; // [WAD] The amount of borrower t0 debt remaining after settle @@ -50,6 +54,7 @@ struct SettleResult { uint256 t0DebtSettled; // [WAD] The amount of t0 debt settled } +/// @dev Struct used to return result of `TakerAction.take` action. struct TakeResult { uint256 collateralAmount; // [WAD] amount of collateral taken uint256 compensatedCollateral; // [WAD] amount of borrower collateral that is compensated with LP @@ -68,6 +73,7 @@ struct TakeResult { uint256 collateralPostAction; // [WAD] The amount of borrower collateral after take } +/// @dev Struct used to hold parameters for `KickerAction.kickReserveAuction` action. struct KickReserveAuctionParams { uint256 poolSize; // [WAD] total deposits in pool (with accrued debt) uint256 t0PoolDebt; // [WAD] current t0 pool debt @@ -79,11 +85,13 @@ struct KickReserveAuctionParams { /*** Liquidity Management Param Structs ***/ /******************************************/ +/// @dev Struct used to hold parameters for `LenderAction.addQuoteToken` action. struct AddQuoteParams { uint256 amount; // [WAD] amount to be added uint256 index; // the index in which to deposit } +/// @dev Struct used to hold parameters for `LenderAction.moveQuoteToken` action. struct MoveQuoteParams { uint256 fromIndex; // the deposit index from where amount is moved uint256 maxAmountToMove; // [WAD] max amount to move between deposits @@ -91,6 +99,7 @@ struct MoveQuoteParams { uint256 thresholdPrice; // [WAD] max threshold price in pool } +/// @dev Struct used to hold parameters for `LenderAction.removeQuoteToken` action. struct RemoveQuoteParams { uint256 index; // the deposit index from where amount is removed uint256 maxAmount; // [WAD] max amount to be removed @@ -101,6 +110,7 @@ struct RemoveQuoteParams { /*** Loan Management Param Structs ***/ /*************************************/ +/// @dev Struct used to return result of `BorrowerActions.drawDebt` action. struct DrawDebtResult { uint256 newLup; // [WAD] new pool LUP after draw debt uint256 poolCollateral; // [WAD] total amount of collateral in pool after pledge collateral @@ -115,6 +125,7 @@ struct DrawDebtResult { uint256 collateralPostAction; // [WAD] The amount of borrower collateral after draw debt } +/// @dev Struct used to return result of `BorrowerActions.repayDebt` action. struct RepayDebtResult { uint256 newLup; // [WAD] new pool LUP after draw debt uint256 poolCollateral; // [WAD] total amount of collateral in pool after pull collateral diff --git a/src/interfaces/pool/commons/IPoolKickerActions.sol b/src/interfaces/pool/commons/IPoolKickerActions.sol index 81e661433..b55e27d39 100644 --- a/src/interfaces/pool/commons/IPoolKickerActions.sol +++ b/src/interfaces/pool/commons/IPoolKickerActions.sol @@ -46,7 +46,7 @@ interface IPoolKickerActions { /***********************/ /** - * @notice Called by actor to start a Claimable Reserve Auction (CRA). + * @notice Called by actor to start a `Claimable Reserve Auction` (`CRA`). */ function kickReserveAuction() external; } \ No newline at end of file diff --git a/src/interfaces/pool/commons/IPoolLenderActions.sol b/src/interfaces/pool/commons/IPoolLenderActions.sol index 598ae68bc..8ea6e23a3 100644 --- a/src/interfaces/pool/commons/IPoolLenderActions.sol +++ b/src/interfaces/pool/commons/IPoolLenderActions.sol @@ -43,15 +43,15 @@ interface IPoolLenderActions { /** * @notice Called by lenders to claim collateral from a price bucket. - * @param maxAmount The amount of collateral (or the number of NFT tokens) to claim. - * @param index The bucket index from which collateral will be removed. - * @return collateralAmount The amount of collateral removed. - * @return lpAmount The amount of LP used for removing collateral amount. + * @param maxAmount_ The amount of collateral (or the number of `NFT` tokens) to claim. + * @param index_ The bucket index from which collateral will be removed. + * @return removedAmount_ The amount of collateral removed. + * @return redeemedLP_ The amount of `LP` used for removing collateral amount. */ function removeCollateral( - uint256 maxAmount, - uint256 index - ) external returns (uint256 collateralAmount, uint256 lpAmount); + uint256 maxAmount_, + uint256 index_ + ) external returns (uint256 removedAmount_, uint256 redeemedLP_); /** * @notice Called by lenders to remove an amount of credit at a specified price bucket. diff --git a/src/interfaces/pool/commons/IPoolSettlerActions.sol b/src/interfaces/pool/commons/IPoolSettlerActions.sol index 180ecad7a..7973545e2 100644 --- a/src/interfaces/pool/commons/IPoolSettlerActions.sol +++ b/src/interfaces/pool/commons/IPoolSettlerActions.sol @@ -9,13 +9,13 @@ interface IPoolSettlerActions { /** * @notice Called by actors to settle an amount of debt in a completed liquidation. - * @param borrowerAddress Address of the auctioned borrower. - * @param maxDepth Measured from HPB, maximum number of buckets deep to settle debt. - * @dev maxDepth is used to prevent unbounded iteration clearing large liquidations. + * @param borrowerAddress_ Address of the auctioned borrower. + * @param maxDepth_ Measured from `HPB`, maximum number of buckets deep to settle debt. + * @dev `maxDepth_` is used to prevent unbounded iteration clearing large liquidations. */ function settle( - address borrowerAddress, - uint256 maxDepth + address borrowerAddress_, + uint256 maxDepth_ ) external; } \ No newline at end of file diff --git a/src/interfaces/pool/commons/IPoolState.sol b/src/interfaces/pool/commons/IPoolState.sol index 96984ca6c..c862c5fc3 100644 --- a/src/interfaces/pool/commons/IPoolState.sol +++ b/src/interfaces/pool/commons/IPoolState.sol @@ -175,8 +175,8 @@ interface IPoolState { * @return depositTime_ Time the user last deposited quote token. */ function lenderInfo( - uint256 index, - address lp + uint256 index_, + address lender_ ) external view @@ -279,8 +279,8 @@ interface IPoolState { * @return True if the transferor is approved by lender. */ function approvedTransferors( - address lender, - address transferor + address lender_, + address transferor_ ) external view returns (bool); } @@ -289,13 +289,17 @@ interface IPoolState { /*** State Structs ***/ /*********************/ +/******************/ /*** Pool State ***/ +/******************/ +/// @dev Struct holding inflator state. struct InflatorState { uint208 inflator; // [WAD] pool's inflator uint48 inflatorUpdate; // [SEC] last time pool's inflator was updated } +/// @dev Struct holding pool interest state. struct InterestState { uint208 interestRate; // [WAD] pool's interest rate uint48 interestRateUpdate; // [SEC] last time pool's interest rate was updated (not before 12 hours passed) @@ -306,6 +310,7 @@ struct InterestState { uint256 lupt0Debt; // [WAD] previous LUP * t0 debt } +/// @dev Struct holding pool EMAs state. struct EmaState { uint256 debtEma; // [WAD] sample of debt EMA, numerator to MAU calculation uint256 depositEma; // [WAD] sample of meaningful deposit EMA, denominator to MAU calculation @@ -314,12 +319,14 @@ struct EmaState { uint256 emaUpdate; // [SEC] last time pool's EMAs were updated } +/// @dev Struct holding pool balances state. struct PoolBalancesState { uint256 pledgedCollateral; // [WAD] total collateral pledged in pool uint256 t0DebtInAuction; // [WAD] Total debt in auction used to restrict LPB holder from withdrawing uint256 t0Debt; // [WAD] Pool debt as if the whole amount was incurred upon the first loan } +/// @dev Struct holding pool params (in memory only). struct PoolState { uint8 poolType; // pool type, can be ERC20 or ERC721 uint256 t0Debt; // [WAD] t0 debt in pool @@ -331,13 +338,17 @@ struct PoolState { uint256 quoteDustLimit; // [WAD] quote token dust limit of the pool } +/*********************/ /*** Buckets State ***/ +/*********************/ +/// @dev Struct holding lender state. struct Lender { uint256 lps; // [WAD] Lender LP accumulator uint256 depositTime; // timestamp of last deposit } +/// @dev Struct holding bucket state. struct Bucket { uint256 lps; // [WAD] Bucket LP accumulator uint256 collateral; // [WAD] Available collateral tokens deposited in the bucket @@ -345,34 +356,45 @@ struct Bucket { mapping(address => Lender) lenders; // lender address to Lender struct mapping } +/**********************/ /*** Deposits State ***/ +/**********************/ +/// @dev Struct holding deposits (Fenwick) values and scaling. struct DepositsState { uint256[8193] values; // Array of values in the FenwickTree. uint256[8193] scaling; // Array of values which scale (multiply) the FenwickTree accross indexes. } +/*******************/ /*** Loans State ***/ +/*******************/ +/// @dev Struct holding loans state. struct LoansState { Loan[] loans; mapping (address => uint) indices; // borrower address => loan index mapping mapping (address => Borrower) borrowers; // borrower address => Borrower struct mapping } +/// @dev Struct holding loan state. struct Loan { address borrower; // borrower address uint96 thresholdPrice; // [WAD] Loan's threshold price. } +/// @dev Struct holding borrower state. struct Borrower { uint256 t0Debt; // [WAD] Borrower debt time-adjusted as if it was incurred upon first loan of pool. uint256 collateral; // [WAD] Collateral deposited by borrower. uint256 t0Np; // [WAD] Neutral Price time-adjusted as if it was incurred upon first loan of pool. } +/**********************/ /*** Auctions State ***/ +/**********************/ +/// @dev Struct holding pool auctions state. struct AuctionsState { uint96 noOfAuctions; // total number of auctions in pool address head; // first address in auction queue @@ -382,6 +404,7 @@ struct AuctionsState { mapping(address => Kicker) kickers; // mapping of kicker address and kicker balances } +/// @dev Struct holding liquidation state. struct Liquidation { address kicker; // address that initiated liquidation uint96 bondFactor; // [WAD] bond factor used to start liquidation @@ -394,13 +417,17 @@ struct Liquidation { bool alreadyTaken; // true if take has been called on auction } +/// @dev Struct holding kicker state. struct Kicker { uint256 claimable; // [WAD] kicker's claimable balance uint256 locked; // [WAD] kicker's balance of tokens locked in auction bonds } -/*** Reserve Auction State ***/ +/******************************/ +/*** Reserve Auctions State ***/ +/******************************/ +/// @dev Struct holding reserve auction state. struct ReserveAuctionState { uint256 kicked; // Time a Claimable Reserve Auction was last kicked. uint256 unclaimed; // [WAD] Amount of claimable reserves which has not been taken in the Claimable Reserve Auction. @@ -410,6 +437,7 @@ struct ReserveAuctionState { mapping (uint256 => BurnEvent) burnEvents; // Mapping burnEventEpoch => BurnEvent. } +/// @dev Struct holding burn event state. struct BurnEvent { uint256 timestamp; // time at which the burn event occured uint256 totalInterest; // [WAD] current pool interest accumulator `PoolCommons.accrueInterest().newInterest` diff --git a/src/interfaces/pool/commons/IPoolTakerActions.sol b/src/interfaces/pool/commons/IPoolTakerActions.sol index 620e5a7c3..f03c21056 100644 --- a/src/interfaces/pool/commons/IPoolTakerActions.sol +++ b/src/interfaces/pool/commons/IPoolTakerActions.sol @@ -9,30 +9,30 @@ interface IPoolTakerActions { /** * @notice Called by actors to use quote token to arb higher-priced deposit off the book. - * @param borrower Identifies the loan to liquidate. - * @param depositTake If true then the take will happen at an auction price equal with bucket price. Auction price is used otherwise. - * @param index Index of a bucket, likely the HPB, in which collateral will be deposited. + * @param borrowerAddress_ Identifies the loan to liquidate. + * @param depositTake_ If true then the take will happen at an auction price equal with bucket price. Auction price is used otherwise. + * @param index_ Index of a bucket, likely the `HPB`, in which collateral will be deposited. */ function bucketTake( - address borrower, - bool depositTake, - uint256 index + address borrowerAddress_, + bool depositTake_, + uint256 index_ ) external; /** * @notice Called by actors to purchase collateral from the auction in exchange for quote token. - * @param borrower Address of the borower take is being called upon. - * @param maxAmount Max amount of collateral that will be taken from the auction (max number of NFTs in case of ERC721 pool). - * @param callee Identifies where collateral should be sent and where quote token should be obtained. - * @param data If provided, take will assume the callee implements IERC*Taker. Take will send collateral to - * callee before passing this data to IERC*Taker.atomicSwapCallback. If not provided, - * the callback function will not be invoked. + * @param borrowerAddress_ Address of the borower take is being called upon. + * @param maxAmount_ Max amount of collateral that will be taken from the auction (max number of `NFT`s in case of `ERC721` pool). + * @param callee_ Identifies where collateral should be sent and where quote token should be obtained. + * @param data_ If provided, take will assume the callee implements `IERC*Taker`. Take will send collateral to + * callee before passing this data to `IERC*Taker.atomicSwapCallback`. If not provided, + * the callback function will not be invoked. */ function take( - address borrower, - uint256 maxAmount, - address callee, - bytes calldata data + address borrowerAddress_, + uint256 maxAmount_, + address callee_, + bytes calldata data_ ) external; /***********************/ diff --git a/src/interfaces/pool/erc20/IERC20Pool.sol b/src/interfaces/pool/erc20/IERC20Pool.sol index 76b945e54..b3ddba077 100644 --- a/src/interfaces/pool/erc20/IERC20Pool.sol +++ b/src/interfaces/pool/erc20/IERC20Pool.sol @@ -21,17 +21,17 @@ interface IERC20Pool is /** * @notice Initializes a new pool, setting initial state variables. - * @param rate Initial interest rate of the pool. + * @param rate_ Initial interest rate of the pool (min accepted value 1%, max accepted value 10%). */ - function initialize(uint256 rate) external; + function initialize(uint256 rate_) external; /** * @notice Returns the minimum amount of collateral an actor may have in a bucket. - * @param bucketIndex The bucket index for which the dust limit is desired, or 0 for pledged collateral. - * @return The dust limit for `bucketIndex`. + * @param bucketIndex_ The bucket index for which the dust limit is desired, or `0` for pledged collateral. + * @return The dust limit for `bucketIndex_`. */ function bucketCollateralDust( - uint256 bucketIndex + uint256 bucketIndex_ ) external pure returns (uint256); } diff --git a/src/interfaces/pool/erc20/IERC20PoolBorrowerActions.sol b/src/interfaces/pool/erc20/IERC20PoolBorrowerActions.sol index d92a95712..2d5252102 100644 --- a/src/interfaces/pool/erc20/IERC20PoolBorrowerActions.sol +++ b/src/interfaces/pool/erc20/IERC20PoolBorrowerActions.sol @@ -9,11 +9,10 @@ interface IERC20PoolBorrowerActions { /** * @notice Called by borrowers to add collateral to the pool and/or borrow quote from the pool. - * @dev Can be called by borrowers with either 0 amountToBorrow_ or 0 collateralToPledge_, if borrower only wants to take a single action. - * Call with 0 amountToBorrow_, and non-0 limitIndex_ to restamp loan's neutral price. + * @dev Can be called by borrowers with either `0` `amountToBorrow_` or `0` `collateralToPledge_`, if borrower only wants to take a single action. * @param borrowerAddress_ The borrower to whom collateral was pledged, and/or debt was drawn for. * @param amountToBorrow_ The amount of quote tokens to borrow. - * @param limitIndex_ Lower bound of LUP change (if any) that the borrower will tolerate from a creating or modifying position. + * @param limitIndex_ Lower bound of `LUP` change (if any) that the borrower will tolerate from a creating or modifying position. * @param collateralToPledge_ The amount of collateral to be added to the pool. */ function drawDebt( @@ -25,12 +24,12 @@ interface IERC20PoolBorrowerActions { /** * @notice Called by borrowers to repay borrowed quote to the pool, and/or pull collateral form the pool. - * @dev Can be called by borrowers with either 0 maxQuoteTokenAmountToRepay_ or 0 collateralAmountToPull_, if borrower only wants to take a single action. + * @dev Can be called by borrowers with either `0` `maxQuoteTokenAmountToRepay_` or `0` `collateralAmountToPull_`, if borrower only wants to take a single action. * @param borrowerAddress_ The borrower whose loan is being interacted with. - * @param maxQuoteTokenAmountToRepay_ The amount of quote tokens to repay. - * @param collateralAmountToPull_ The amount of collateral to be puled from the pool. + * @param maxQuoteTokenAmountToRepay_ The max amount of quote tokens to repay. + * @param collateralAmountToPull_ The max amount of collateral to be puled from the pool. * @param recipient_ The address to receive amount of pulled collateral. - * @param limitIndex_ Ensures LUP has not moved far from state when borrower pulls collateral. + * @param limitIndex_ Ensures `LUP` has not moved far from state when borrower pulls collateral. */ function repayDebt( address borrowerAddress_, diff --git a/src/interfaces/pool/erc20/IERC20PoolEvents.sol b/src/interfaces/pool/erc20/IERC20PoolEvents.sol index bcd448d63..2df85d23d 100644 --- a/src/interfaces/pool/erc20/IERC20PoolEvents.sol +++ b/src/interfaces/pool/erc20/IERC20PoolEvents.sol @@ -12,7 +12,7 @@ interface IERC20PoolEvents { * @param actor Recipient that added collateral. * @param index Index at which collateral were added. * @param amount Amount of collateral added to the pool. - * @param lpAwarded Amount of LP awarded for the deposit. + * @param lpAwarded Amount of `LP` awarded for the deposit. */ event AddCollateral( address indexed actor, @@ -26,7 +26,7 @@ interface IERC20PoolEvents { * @param borrower The borrower to whom collateral was pledged, and/or debt was drawn for. * @param amountBorrowed Amount of quote tokens borrowed from the pool. * @param collateralPledged Amount of collateral locked in the pool. - * @param lup LUP after borrow. + * @param lup `LUP` after borrow. */ event DrawDebt( address indexed borrower, diff --git a/src/interfaces/pool/erc20/IERC20PoolFactory.sol b/src/interfaces/pool/erc20/IERC20PoolFactory.sol index de3b49fea..9d2c8c802 100644 --- a/src/interfaces/pool/erc20/IERC20PoolFactory.sol +++ b/src/interfaces/pool/erc20/IERC20PoolFactory.sol @@ -6,7 +6,7 @@ import { IPoolFactory } from '../IPoolFactory.sol'; /** * @title ERC20 Pool Factory - * @dev Used to deploy ERC20 pools. + * @dev Used to deploy `ERC20` pools. */ interface IERC20PoolFactory is IPoolFactory { @@ -16,15 +16,15 @@ interface IERC20PoolFactory is IPoolFactory { /** * @notice Deploys a cloned pool for the given collateral and quote token. - * @dev Pool must not already exist, and must use WETH instead of ETH. - * @param collateral Address of ERC20 collateral token. - * @param quote Address of ERC20 quote token. - * @param interestRate Initial interest rate of the pool. - * @return pool Address of the newly created pool. + * @dev Pool must not already exist, and must use `WETH` instead of `ETH`. + * @param collateral_ Address of `ERC20` collateral token. + * @param quote_ Address of `ERC20` quote token. + * @param interestRate_ Initial interest rate of the pool. + * @return pool_ Address of the newly created pool. */ function deployPool( - address collateral, - address quote, - uint256 interestRate - ) external returns (address pool); + address collateral_, + address quote_, + uint256 interestRate_ + ) external returns (address pool_); } diff --git a/src/interfaces/pool/erc20/IERC20PoolImmutables.sol b/src/interfaces/pool/erc20/IERC20PoolImmutables.sol index d7aa20964..533cee50d 100644 --- a/src/interfaces/pool/erc20/IERC20PoolImmutables.sol +++ b/src/interfaces/pool/erc20/IERC20PoolImmutables.sol @@ -9,7 +9,7 @@ interface IERC20PoolImmutables { /** * @notice Returns the `collateralScale` immutable. - * @return The precision of the collateral ERC-20 token based on decimals. + * @return The precision of the collateral `ERC20` token based on decimals. */ function collateralScale() external view returns (uint256); diff --git a/src/interfaces/pool/erc20/IERC20PoolLenderActions.sol b/src/interfaces/pool/erc20/IERC20PoolLenderActions.sol index 3d43ea4e0..87f8a3ab6 100644 --- a/src/interfaces/pool/erc20/IERC20PoolLenderActions.sol +++ b/src/interfaces/pool/erc20/IERC20PoolLenderActions.sol @@ -9,14 +9,14 @@ interface IERC20PoolLenderActions { /** * @notice Deposit claimable collateral into a specified bucket. - * @param amount Amount of collateral to deposit. - * @param index The bucket index to which collateral will be deposited. - * @param expiry Timestamp after which this TX will revert, preventing inclusion in a block with unfavorable price. - * @return lpbChange The amount of LP changed for the added collateral. + * @param amountToAdd_ Amount of collateral to deposit. + * @param index_ The bucket index to which collateral will be deposited. + * @param expiry_ Timestamp after which this transaction will revert, preventing inclusion in a block with unfavorable price. + * @return bucketLP_ The amount of `LP` awarded for the added collateral. */ function addCollateral( - uint256 amount, - uint256 index, - uint256 expiry - ) external returns (uint256 lpbChange); + uint256 amountToAdd_, + uint256 index_, + uint256 expiry_ + ) external returns (uint256 bucketLP_); } \ No newline at end of file diff --git a/src/interfaces/pool/erc20/IERC20Taker.sol b/src/interfaces/pool/erc20/IERC20Taker.sol index fa60b2cb7..15826c0ff 100644 --- a/src/interfaces/pool/erc20/IERC20Taker.sol +++ b/src/interfaces/pool/erc20/IERC20Taker.sol @@ -4,9 +4,9 @@ pragma solidity 0.8.14; interface IERC20Taker { /** - * @notice Called by Pool.take allowing a taker to externally swap collateral for quote token. + * @notice Called by `Pool.take` allowing a taker to externally swap collateral for quote token. * @param collateralAmount The denormalized amount of collateral being taken. - * @param quoteAmountDue Denormalized amount of quote token required to purchase collateralAmount at the + * @param quoteAmountDue Denormalized amount of quote token required to purchase `collateralAmount` at the * current auction price. * @param data Taker-provided calldata passed from taker's invocation to their callback. */ diff --git a/src/interfaces/pool/erc721/IERC721Pool.sol b/src/interfaces/pool/erc721/IERC721Pool.sol index edc8721d6..dd4f9e7c4 100644 --- a/src/interfaces/pool/erc721/IERC721Pool.sol +++ b/src/interfaces/pool/erc721/IERC721Pool.sol @@ -26,12 +26,12 @@ interface IERC721Pool is /** * @notice Initializes a new pool, setting initial state variables. - * @param tokenIds Enumerates tokenIds to be allowed in the pool. - * @param rate Initial interest rate of the pool. + * @param tokenIds_ Enumerates `tokenIds_` to be allowed in the pool. + * @param rate_ Initial interest rate of the pool. */ function initialize( - uint256[] memory tokenIds, - uint256 rate + uint256[] memory tokenIds_, + uint256 rate_ ) external; } diff --git a/src/interfaces/pool/erc721/IERC721PoolBorrowerActions.sol b/src/interfaces/pool/erc721/IERC721PoolBorrowerActions.sol index 9206c9b5e..9d4e1ac1d 100644 --- a/src/interfaces/pool/erc721/IERC721PoolBorrowerActions.sol +++ b/src/interfaces/pool/erc721/IERC721PoolBorrowerActions.sol @@ -9,12 +9,11 @@ interface IERC721PoolBorrowerActions { /** * @notice Called by borrowers to add collateral to the pool and/or borrow quote from the pool. - * @dev Can be called by borrowers with either 0 amountToBorrow_ or 0 collateralToPledge_, if borrower only wants to take a single action. - * Call with 0 amountToBorrow_, and non-0 limitIndex_ to restamp loan's neutral price. + * @dev Can be called by borrowers with either `0` `amountToBorrow_` or `0` `collateralToPledge`_, if borrower only wants to take a single action. * @param borrower_ The address of borrower to drawDebt for. * @param amountToBorrow_ The amount of quote tokens to borrow. - * @param limitIndex_ Lower bound of LUP change (if any) that the borrower will tolerate from a creating or modifying position. - * @param tokenIdsToPledge_ Array of tokenIds to be pledged to the pool. + * @param limitIndex_ Lower bound of `LUP` change (if any) that the borrower will tolerate from a creating or modifying position. + * @param tokenIdsToPledge_ Array of token ids to be pledged to the pool. */ function drawDebt( address borrower_, @@ -25,12 +24,12 @@ interface IERC721PoolBorrowerActions { /** * @notice Called by borrowers to repay borrowed quote to the pool, and/or pull collateral form the pool. - * @dev Can be called by borrowers with either 0 maxQuoteTokenAmountToRepay_ or 0 collateralAmountToPull_, if borrower only wants to take a single action. + * @dev Can be called by borrowers with either `0` `maxQuoteTokenAmountToRepay_` or `0` `collateralAmountToPull_`, if borrower only wants to take a single action. * @param borrowerAddress_ The borrower whose loan is being interacted with. - * @param maxQuoteTokenAmountToRepay_ The amount of quote tokens to repay. - * @param noOfNFTsToPull_ The integer number of NFT collateral to be puled from the pool. + * @param maxQuoteTokenAmountToRepay_ The max amount of quote tokens to repay. + * @param noOfNFTsToPull_ The integer number of `NFT` collateral to be puled from the pool. * @param recipient_ The address to receive amount of pulled collateral. - * @param limitIndex_ Ensures LUP has not moved far from state when borrower pulls collateral. + * @param limitIndex_ Ensures `LUP` has not moved far from state when borrower pulls collateral. */ function repayDebt( address borrowerAddress_, diff --git a/src/interfaces/pool/erc721/IERC721PoolErrors.sol b/src/interfaces/pool/erc721/IERC721PoolErrors.sol index 5f9db4792..63ac82dd4 100644 --- a/src/interfaces/pool/erc721/IERC721PoolErrors.sol +++ b/src/interfaces/pool/erc721/IERC721PoolErrors.sol @@ -8,7 +8,7 @@ pragma solidity 0.8.14; interface IERC721PoolErrors { /** - * @notice User attempted to add an NFT to the pool with a tokenId outsde of the allowed subset. + * @notice User attempted to add an `NFT` to the pool with a `tokenId` outside of the allowed subset. */ error OnlySubset(); } \ No newline at end of file diff --git a/src/interfaces/pool/erc721/IERC721PoolEvents.sol b/src/interfaces/pool/erc721/IERC721PoolEvents.sol index 123e86a3c..f963650f4 100644 --- a/src/interfaces/pool/erc721/IERC721PoolEvents.sol +++ b/src/interfaces/pool/erc721/IERC721PoolEvents.sol @@ -34,7 +34,7 @@ interface IERC721PoolEvents { ); /** - * @notice Emitted when borrower draws debt from the pool, or adds collateral to the pool. + * @notice Emitted when borrower draws debt from the pool or adds collateral to the pool. * @param borrower `msg.sender`. * @param amountBorrowed Amount of quote tokens borrowed from the pool. * @param tokenIdsPledged Array of tokenIds to be added to the pool. diff --git a/src/interfaces/pool/erc721/IERC721PoolFactory.sol b/src/interfaces/pool/erc721/IERC721PoolFactory.sol index 30d842cbf..605ef9b85 100644 --- a/src/interfaces/pool/erc721/IERC721PoolFactory.sol +++ b/src/interfaces/pool/erc721/IERC721PoolFactory.sol @@ -15,7 +15,7 @@ interface IERC721PoolFactory is IPoolFactory { /**************/ /** - * @notice User tried to deploy a pool with an array of tokenIds that weren't sorted, or contained duplicates. + * @notice User tried to deploy a pool with an array of `tokenIds` that weren't sorted, or contained duplicates. */ error TokenIdSubsetInvalid(); @@ -25,22 +25,22 @@ interface IERC721PoolFactory is IPoolFactory { /** * @notice Deploys a cloned pool for the given collateral and quote token. - * @dev Pool must not already exist, and must use WETH instead of ETH. - * @param collateral Address of NFT collateral token. - * @param quote Address of NFT quote token. - * @param tokenIds Ids of subset NFT tokens. - * @param interestRate Initial interest rate of the pool. - * @return pool Address of the newly created pool. + * @dev Pool must not already exist, and must use `WETH` instead of `ETH`. + * @param collateral_ Address of `NFT` collateral token. + * @param quote_ Address of `NFT` quote token. + * @param tokenIds_ Ids of subset `NFT` tokens. + * @param interestRate_ Initial interest rate of the pool. + * @return pool_ Address of the newly created pool. */ function deployPool( - address collateral, - address quote, - uint256[] memory tokenIds, - uint256 interestRate - ) external returns (address pool); + address collateral_, + address quote_, + uint256[] memory tokenIds_, + uint256 interestRate_ + ) external returns (address pool_); /** - * @notice User attempted to make pool with non supported NFT contract as collateral. + * @notice User attempted to make pool with non supported `NFT` contract as collateral. */ error NFTNotSupported(); } diff --git a/src/interfaces/pool/erc721/IERC721PoolImmutables.sol b/src/interfaces/pool/erc721/IERC721PoolImmutables.sol index 53b74ae89..df91b9907 100644 --- a/src/interfaces/pool/erc721/IERC721PoolImmutables.sol +++ b/src/interfaces/pool/erc721/IERC721PoolImmutables.sol @@ -8,8 +8,8 @@ pragma solidity 0.8.14; interface IERC721PoolImmutables{ /** - * @notice Returns the type of NFT pool. - * @return True if NTF pool is a subset pool. + * @notice Returns the type of `NFT` pool. + * @return `True` if `NTF` pool is a subset pool. */ function isSubset() external view returns (bool); diff --git a/src/interfaces/pool/erc721/IERC721PoolLenderActions.sol b/src/interfaces/pool/erc721/IERC721PoolLenderActions.sol index c9f5119aa..260d3c680 100644 --- a/src/interfaces/pool/erc721/IERC721PoolLenderActions.sol +++ b/src/interfaces/pool/erc721/IERC721PoolLenderActions.sol @@ -9,28 +9,28 @@ interface IERC721PoolLenderActions { /** * @notice Deposit claimable collateral into a specified bucket. - * @param tokenIds Array of collateral to deposit. - * @param index The bucket index to which collateral will be deposited. - * @param expiry Timestamp after which this TX will revert, preventing inclusion in a block with unfavorable price. - * @return lpbChange The amount of LP changed for the added collateral. + * @param tokenIds_ Array of token ids to deposit. + * @param index_ The bucket index to which collateral will be deposited. + * @param expiry_ Timestamp after which this transaction will revert, preventing inclusion in a block with unfavorable price. + * @return bucketLP_ The amount of `LP `changed for the added collateral. */ function addCollateral( - uint256[] calldata tokenIds, - uint256 index, - uint256 expiry - ) external returns (uint256); + uint256[] calldata tokenIds_, + uint256 index_, + uint256 expiry_ + ) external returns (uint256 bucketLP_); /** - * @notice Merge collateral accross a number of buckets, removeAmountAtIndex_to reconstitute an NFT - * @param removeAmountAtIndex_ Array of bucket indexes to remove all collateral that the caller has ownership over. - * @param toIndex_ The bucket index to which merge collateral into. - * @param noOfNFTsToRemove_ Intergral number of NFTs to remove if collateral amount is met noOfNFTsToRemove_, else merge at bucket index, toIndex_. - * @return collateralMerged_ Amount of collateral merged into toIndex. - * @return bucketLPs_ If non-zero, amount of LP in toIndex when collateral is merged into bucket. If 0, no collateral is merged. + * @notice Merge collateral accross a number of buckets, `removalIndexes_` reconstitute an `NFT`. + * @param removalIndexes_ Array of bucket indexes to remove all collateral that the caller has ownership over. + * @param noOfNFTsToRemove_ Intergral number of `NFT`s to remove if collateral amount is met `noOfNFTsToRemove_`, else merge at bucket index, `toIndex_`. + * @param toIndex_ The bucket index to which merge collateral into. + * @return collateralMerged_ Amount of collateral merged into `toIndex_`. + * @return bucketLP_ If non-zero, amount of `LP` in `toIndex_` when collateral is merged into bucket. If `0`, no collateral is merged. */ function mergeOrRemoveCollateral( - uint256[] calldata removeAmountAtIndex_, + uint256[] calldata removalIndexes_, uint256 noOfNFTsToRemove_, uint256 toIndex_ - ) external returns (uint256 collateralMerged_, uint256 bucketLPs_); + ) external returns (uint256 collateralMerged_, uint256 bucketLP_); } \ No newline at end of file diff --git a/src/interfaces/pool/erc721/IERC721PoolState.sol b/src/interfaces/pool/erc721/IERC721PoolState.sol index 4bc028a82..fd174fff5 100644 --- a/src/interfaces/pool/erc721/IERC721PoolState.sol +++ b/src/interfaces/pool/erc721/IERC721PoolState.sol @@ -10,17 +10,17 @@ interface IERC721PoolState { /** * @notice Check if a token id is allowed as collateral in pool. * @param tokenId The token id to check. - * @return allowed True if token id is allowed in pool + * @return allowed `True` if token id is allowed in pool. */ function tokenIdsAllowed( uint256 tokenId ) external view returns (bool allowed); /** - * @notice Returns the token id of an NFT pledged by a borrower with a given index. - * @param borrower The address of borrower that pledged the NFT. - * @param nftIndex NFT index in borrower's pledged token ids array. - * @return tokenId Token id of the NFT. + * @notice Returns the token id of an `NFT` pledged by a borrower with a given index. + * @param borrower The address of borrower that pledged the `NFT`. + * @param nftIndex `NFT` index in borrower's pledged token ids array. + * @return tokenId Token id of the `NFT`. */ function borrowerTokenIds( address borrower, @@ -28,26 +28,26 @@ interface IERC721PoolState { ) external view returns (uint256 tokenId); /** - * @notice Returns the token id of an NFT added in pool bucket. - * @param nftIndex NFT index in bucket's token ids array. - * @return tokenId Token id of the NFT. + * @notice Returns the token id of an `NFT`added in pool bucket (claimable from pool). + * @param nftIndex `NFT` index in bucket's token ids array. + * @return tokenId Token id of the `NFT`. */ function bucketTokenIds( uint256 nftIndex ) external view returns (uint256 tokenId); /** - * @notice Returns the total NFT pledged by a borrower. - * @param borrower The address of borrower that pledged the NFT. - * @return tokens Total borrower NFTs. + * @notice Returns the total `NFT` pledged by a borrower. + * @param borrower_ The address of borrower that pledged the `NFT`. + * @return Total number of `NFT`s pledged by borrower. */ function totalBorrowerTokens( - address borrower - ) external view returns (uint256 tokens); + address borrower_ + ) external view returns (uint256); /** - * @notice Returns the total NFT added in pool bucket. - * @return tokens Total NFT in bucket. + * @notice Returns the total `NFT` added in pool bucket. + * @return Total number of `NFT`s in buckets (claimable from pool). */ - function totalBucketTokens() external view returns (uint256 tokens); + function totalBucketTokens() external view returns (uint256); } \ No newline at end of file diff --git a/src/interfaces/pool/erc721/IERC721Taker.sol b/src/interfaces/pool/erc721/IERC721Taker.sol index 486684116..9e1a68090 100644 --- a/src/interfaces/pool/erc721/IERC721Taker.sol +++ b/src/interfaces/pool/erc721/IERC721Taker.sol @@ -4,9 +4,9 @@ pragma solidity 0.8.14; interface IERC721Taker { /** - * @notice Called by Pool.take allowing a taker to externally swap collateral for quote token. - * @param tokenIds Identifies the NFTs being taken. - * @param quoteAmountDue Denormalized amount of quote token required to purchase collateralAmount at the + * @notice Called by `Pool.take` allowing a taker to externally swap collateral for quote token. + * @param tokenIds Identifies the `NFT`s being taken. + * @param quoteAmountDue Denormalized amount of quote token required to purchase `collateralAmount` at the * current auction price. * @param data Taker-provided calldata passed from taker's invocation to their callback. */ From b762a4eb2267da14a537a1e3f5b1b64d3fbab2ea Mon Sep 17 00:00:00 2001 From: grandizzy Date: Tue, 18 Apr 2023 20:58:18 +0300 Subject: [PATCH 03/11] Libraries forge doc --- src/ERC20Pool.sol | 60 +++---- src/ERC20PoolFactory.sol | 19 ++- src/ERC721Pool.sol | 84 ++++----- src/ERC721PoolFactory.sol | 24 +-- src/base/Pool.sol | 68 ++++---- src/interfaces/pool/IPoolFactory.sol | 2 +- src/interfaces/pool/commons/IPoolState.sol | 2 +- .../pool/commons/IPoolTakerActions.sol | 4 +- src/libraries/external/BorrowerActions.sol | 112 ++++++------ src/libraries/external/KickerActions.sol | 102 +++++------ src/libraries/external/LPActions.sol | 70 ++++---- src/libraries/external/LenderActions.sol | 159 +++++++++--------- src/libraries/external/PoolCommons.sol | 26 +-- src/libraries/external/PositionNFTSVG.sol | 2 +- src/libraries/external/SettlerActions.sol | 61 +++---- src/libraries/external/TakerActions.sol | 111 ++++++------ src/libraries/helpers/PoolHelper.sol | 131 ++++++++------- src/libraries/helpers/RevertsHelper.sol | 30 ++-- src/libraries/internal/Buckets.sol | 80 ++++----- src/libraries/internal/Deposits.sol | 44 ++--- src/libraries/internal/Loans.sol | 92 +++++----- 21 files changed, 655 insertions(+), 628 deletions(-) diff --git a/src/ERC20Pool.sol b/src/ERC20Pool.sol index 048870fa9..02c397431 100644 --- a/src/ERC20Pool.sol +++ b/src/ERC20Pool.sol @@ -121,12 +121,12 @@ contract ERC20Pool is FlashloanablePool, IERC20Pool { /** * @inheritdoc IERC20PoolBorrowerActions - * @dev write state: - * - decrement `poolBalances.t0DebtInAuction` accumulator - * - increment `poolBalances.pledgedCollateral` accumulator - * - increment `poolBalances.t0Debt` accumulator - * @dev emit events: - * - `DrawDebt` + * @dev === Write state === + * @dev - decrement `poolBalances.t0DebtInAuction` accumulator + * @dev - increment `poolBalances.pledgedCollateral` accumulator + * @dev - increment `poolBalances.t0Debt` accumulator + * @dev === Emit events === + * @dev - `DrawDebt` */ function drawDebt( address borrowerAddress_, @@ -189,12 +189,12 @@ contract ERC20Pool is FlashloanablePool, IERC20Pool { /** * @inheritdoc IERC20PoolBorrowerActions - * @dev write state: - * - decrement `poolBalances.t0Debt accumulator` - * - decrement `poolBalances.t0DebtInAuction accumulator` - * - decrement `poolBalances.pledgedCollateral accumulator` - * @dev emit events: - * - `RepayDebt` + * @dev === Write state === + * @dev - decrement `poolBalances.t0Debt accumulator` + * @dev - decrement `poolBalances.t0DebtInAuction accumulator` + * @dev - decrement `poolBalances.pledgedCollateral accumulator` + * @dev === Emit events === + * @dev - `RepayDebt` */ function repayDebt( address borrowerAddress_, @@ -262,10 +262,10 @@ contract ERC20Pool is FlashloanablePool, IERC20Pool { /** * @inheritdoc IERC20PoolLenderActions - * @dev reverts on: - * - `DustAmountNotExceeded()` - * @dev emit events: - * - `AddCollateral` + * @dev === Reverts on === + * @dev - `DustAmountNotExceeded()` + * @dev === Emit events === + * @dev - `AddCollateral` */ function addCollateral( uint256 amountToAdd_, @@ -297,8 +297,8 @@ contract ERC20Pool is FlashloanablePool, IERC20Pool { /** * @inheritdoc IPoolLenderActions - * @dev emit events: - * - `RemoveCollateral` + * @dev === Emit events === + * @dev - `RemoveCollateral` */ function removeCollateral( uint256 maxAmount_, @@ -333,10 +333,10 @@ contract ERC20Pool is FlashloanablePool, IERC20Pool { /** * @inheritdoc IPoolSettlerActions - * @dev write state: - * - decrement `poolBalances.t0Debt` accumulator - * - decrement `poolBalances.t0DebtInAuction` accumulator - * - decrement `poolBalances.pledgedCollateral` accumulator + * @dev === Write state === + * @dev - decrement `poolBalances.t0Debt` accumulator + * @dev - decrement `poolBalances.t0DebtInAuction` accumulator + * @dev - decrement `poolBalances.pledgedCollateral` accumulator */ function settle( address borrowerAddress_, @@ -380,10 +380,10 @@ contract ERC20Pool is FlashloanablePool, IERC20Pool { /** * @inheritdoc IPoolTakerActions - * @dev write state: - * - decrement `poolBalances.t0Debt` accumulator - * - decrement `poolBalances.t0DebtInAuction` accumulator - * - decrement `poolBalances.pledgedCollateral` accumulator + * @dev === Write state === + * @dev - decrement `poolBalances.t0Debt` accumulator + * @dev - decrement `poolBalances.t0DebtInAuction` accumulator + * @dev - decrement `poolBalances.pledgedCollateral` accumulator */ function take( address borrowerAddress_, @@ -449,10 +449,10 @@ contract ERC20Pool is FlashloanablePool, IERC20Pool { /** * @inheritdoc IPoolTakerActions - * @dev write state: - * - decrement `poolBalances.t0Debt` accumulator - * - decrement `poolBalances.t0DebtInAuction` accumulator - * - decrement `poolBalances.pledgedCollateral` accumulator + * @dev === Write state === + * @dev - decrement `poolBalances.t0Debt` accumulator + * @dev - decrement `poolBalances.t0DebtInAuction` accumulator + * @dev - decrement `poolBalances.pledgedCollateral` accumulator */ function bucketTake( address borrowerAddress_, diff --git a/src/ERC20PoolFactory.sol b/src/ERC20PoolFactory.sol index 615c904fd..cced2aeef 100644 --- a/src/ERC20PoolFactory.sol +++ b/src/ERC20PoolFactory.sol @@ -21,6 +21,7 @@ contract ERC20PoolFactory is PoolDeployer, IERC20PoolFactory { using ClonesWithImmutableArgs for address; + /// @dev `ERC20` clonable pool contract used to deploy the new pool. ERC20Pool public implementation; /// @dev Default `bytes32` hash used by `ERC20` `Non-NFTSubset` pool types @@ -37,15 +38,15 @@ contract ERC20PoolFactory is PoolDeployer, IERC20PoolFactory { /** * @inheritdoc IERC20PoolFactory * @dev immutable args: pool type; ajna, collateral and quote address; quote and collateral scale - * @dev write state: - * - `deployedPools` mapping - * - `deployedPoolsList` array - * @dev reverts on: - * - `0x` address provided as quote or collateral `DeployWithZeroAddress()` - * - pool with provided quote / collateral pair already exists `PoolAlreadyExists()` - * - invalid interest rate provided `PoolInterestRateInvalid()` - * @dev emit events: - * - `PoolCreated` + * @dev === Write state === + * @dev - `deployedPools` mapping + * @dev - `deployedPoolsList` array + * @dev === Reverts on === + * @dev - `0x` address provided as quote or collateral `DeployWithZeroAddress()` + * @dev - pool with provided quote / collateral pair already exists `PoolAlreadyExists()` + * @dev - invalid interest rate provided `PoolInterestRateInvalid()` + * @dev === Emit events === + * @dev - `PoolCreated` */ function deployPool( address collateral_, address quote_, uint256 interestRate_ diff --git a/src/ERC721Pool.sol b/src/ERC721Pool.sol index 1f16c7569..1f5b2264d 100644 --- a/src/ERC721Pool.sol +++ b/src/ERC721Pool.sol @@ -128,13 +128,13 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool { /** * @inheritdoc IERC721PoolBorrowerActions - * @dev write state: - * - decrement `poolBalances.t0DebtInAuction` accumulator - * - increment `poolBalances.pledgedCollateral` accumulator - * - increment `poolBalances.t0Debt` accumulator - * - update `borrowerTokenIds` and `bucketTokenIds` arrays - * @dev emit events: - * - `DrawDebtNFT` + * @dev === Write state === + * @dev - decrement `poolBalances.t0DebtInAuction` accumulator + * @dev - increment `poolBalances.pledgedCollateral` accumulator + * @dev - increment `poolBalances.t0Debt` accumulator + * @dev - update `borrowerTokenIds` and `bucketTokenIds` arrays + * @dev === Emit events === + * @dev - `DrawDebtNFT` */ function drawDebt( address borrowerAddress_, @@ -197,13 +197,13 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool { /** * @inheritdoc IERC721PoolBorrowerActions - * @dev write state: - * - decrement `poolBalances.t0Debt` accumulator - * - decrement `poolBalances.t0DebtInAuction` accumulator - * - decrement `poolBalances.pledgedCollateral` accumulator - * - update `borrowerTokenIds` and bucketTokenIds` arrays - * @dev emit events: - * - `RepayDebt` + * @dev === Write state === + * @dev - decrement `poolBalances.t0Debt accumulator` + * @dev - decrement `poolBalances.t0DebtInAuction accumulator` + * @dev - decrement `poolBalances.pledgedCollateral accumulator` + * @dev - update `borrowerTokenIds` and `bucketTokenIds` arrays + * @dev === Emit events === + * @dev - `RepayDebt` */ function repayDebt( address borrowerAddress_, @@ -269,10 +269,10 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool { /** * @inheritdoc IERC721PoolLenderActions - * @dev write state: - * - update `bucketTokenIds` arrays - * @dev emit events: - * - `AddCollateralNFT` + * @dev === Write state === + * @dev - update `bucketTokenIds` arrays + * @dev === Emit events === + * @dev - `AddCollateralNFT` */ function addCollateral( uint256[] calldata tokenIds_, @@ -300,10 +300,10 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool { /** * @inheritdoc IERC721PoolLenderActions - * @dev write state: - * - update `bucketTokenIds` arrays - * @dev emit events: - * - `MergeOrRemoveCollateralNFT` + * @dev === Write state === + * @dev - update `bucketTokenIds` arrays + * @dev === Emit events === + * @dev - `MergeOrRemoveCollateralNFT` */ function mergeOrRemoveCollateral( uint256[] calldata removalIndexes_, @@ -340,10 +340,10 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool { /** * @inheritdoc IPoolLenderActions - * @dev write state: - * - update `bucketTokenIds` arrays - * @dev emit events: - * - `RemoveCollateral` + * @dev === Write state === + * @dev - update `bucketTokenIds` arrays + * @dev === Emit events === + * @dev - `RemoveCollateral` * @param noOfNFTsToRemove_ Number of `NFT` tokens to remove. */ function removeCollateral( @@ -376,10 +376,10 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool { /** * @inheritdoc IPoolSettlerActions - * @dev write state: - * - decrement `poolBalances.t0Debt` accumulator - * - decrement `poolBalances.t0DebtInAuction` accumulator - * - decrement `poolBalances.pledgedCollateral` accumulator + * @dev === Write state === + * @dev - decrement `poolBalances.t0Debt` accumulator + * @dev - decrement `poolBalances.t0DebtInAuction` accumulator + * @dev - decrement `poolBalances.pledgedCollateral` accumulator */ function settle( address borrowerAddress_, @@ -428,10 +428,10 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool { /** * @inheritdoc IPoolTakerActions - * @dev write state: - * - decrement `poolBalances.t0Debt` accumulator - * - decrement `poolBalances.t0DebtInAuction` accumulator - * - decrement `poolBalances.pledgedCollateral` accumulator + * @dev === Write state === + * @dev - decrement `poolBalances.t0Debt` accumulator + * @dev - decrement `poolBalances.t0DebtInAuction` accumulator + * @dev - decrement `poolBalances.pledgedCollateral` accumulator */ function take( address borrowerAddress_, @@ -506,10 +506,10 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool { /** * @inheritdoc IPoolTakerActions - * @dev write state: - * - decrement `poolBalances.t0Debt` accumulator - * - decrement `poolBalances.t0DebtInAuction` accumulator - * - decrement `poolBalances.pledgedCollateral` accumulator + * @dev === Write state === + * @dev - decrement `poolBalances.t0Debt` accumulator + * @dev - decrement `poolBalances.t0DebtInAuction` accumulator + * @dev - decrement `poolBalances.pledgedCollateral` accumulator */ function bucketTake( address borrowerAddress_, @@ -566,10 +566,10 @@ contract ERC721Pool is FlashloanablePool, IERC721Pool { /** * @notice Rebalance `NFT` token and transfer difference to floor collateral from borrower to pool claimable array. - * @dev write state: - * - update `borrowerTokens` and `bucketTokenIds` arrays - * @dev emit events: - * - `RemoveCollateral` + * @dev === Write state === + * @dev - update `borrowerTokens` and `bucketTokenIds` arrays + * @dev === Emit events === + * @dev - `RemoveCollateral` * @param borrowerAddress_ Address of borrower. * @param borrowerCollateral_ Current borrower collateral to be rebalanced. */ diff --git a/src/ERC721PoolFactory.sol b/src/ERC721PoolFactory.sol index 4f57f95a1..645d1490f 100644 --- a/src/ERC721PoolFactory.sol +++ b/src/ERC721PoolFactory.sol @@ -23,6 +23,7 @@ contract ERC721PoolFactory is PoolDeployer, IERC721PoolFactory { using ClonesWithImmutableArgs for address; + /// @dev `ERC721` clonable pool contract used to deploy the new pool. ERC721Pool public implementation; /// @dev Default `bytes32` hash used by `ERC721` `Non-NFTSubset` pool types @@ -38,18 +39,17 @@ contract ERC721PoolFactory is PoolDeployer, IERC721PoolFactory { /** * @inheritdoc IERC721PoolFactory - * @dev immutable args: - * - pool type; ajna, collateral and quote address; quote scale; number of token ids in subset; NFT type - * @dev write state: - * - `deployedPools` mapping - * - `deployedPoolsList` array - * @dev reverts on: - * - `0x` address provided as quote or collateral `DeployWithZeroAddress()` - * - pool with provided quote / collateral pair already exists `PoolAlreadyExists()` - * - invalid interest rate provided `PoolInterestRateInvalid()` - * - not supported `NFT` provided `NFTNotSupported()` - * @dev emit events: - * - `PoolCreated` + * @dev immutable args: pool type; ajna, collateral and quote address; quote scale; number of token ids in subset + * @dev === Write state === + * @dev - `deployedPools` mapping + * @dev - `deployedPoolsList` array + * @dev === Reverts on === + * @dev - `0x` address provided as quote or collateral `DeployWithZeroAddress()` + * @dev - pool with provided quote / collateral pair already exists `PoolAlreadyExists()` + * @dev - invalid interest rate provided `PoolInterestRateInvalid()` + * @dev - not supported `NFT` provided `NFTNotSupported()` + * @dev === Emit events === + * @dev - `PoolCreated` */ function deployPool( address collateral_, address quote_, uint256[] memory tokenIds_, uint256 interestRate_ diff --git a/src/base/Pool.sol b/src/base/Pool.sol index 135471bf4..c31728bc2 100644 --- a/src/base/Pool.sol +++ b/src/base/Pool.sol @@ -273,8 +273,8 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { /** * @inheritdoc IPoolKickerActions - * @dev write state: - * - increment `poolBalances.t0DebtInAuction` and `poolBalances.t0Debt` accumulators + * @dev === Write state === + * @dev increment `poolBalances.t0DebtInAuction` and `poolBalances.t0Debt` accumulators */ function kick( address borrower_, @@ -314,8 +314,8 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { /** * @inheritdoc IPoolKickerActions - * @dev write state: - * - increment `poolBalances.t0DebtInAuction` and `poolBalances.t0Debt` accumulators + * @dev === Write state === + * @dev increment `poolBalances.t0DebtInAuction` and `poolBalances.t0Debt` accumulators */ function kickWithDeposit( uint256 index_, @@ -357,9 +357,9 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { /** * @inheritdoc IPoolKickerActions - * @dev write state: - * - decrease kicker's `claimable` accumulator - * - decrease auctions `totalBondEscrowed` accumulator + * @dev === Write state === + * @dev decrease kicker's `claimable` accumulator + * @dev decrease auctions `totalBondEscrowed` accumulator */ function withdrawBonds( address recipient_, @@ -389,13 +389,13 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { /** * @inheritdoc IPoolKickerActions - * @dev write state: - * - increment `latestBurnEpoch` counter - * - update `reserveAuction.latestBurnEventEpoch` and burn event `timestamp` state - * @dev reverts on: - * - 2 weeks not passed `ReserveAuctionTooSoon()` - * @dev emit events: - * - `KickReserveAuction` + * @dev === Write state === + * @dev increment `latestBurnEpoch` counter + * @dev update `reserveAuction.latestBurnEventEpoch` and burn event `timestamp` state + * @dev === Reverts on === + * @dev 2 weeks not passed `ReserveAuctionTooSoon()` + * @dev === Emit events === + * @dev - `KickReserveAuction` */ function kickReserveAuction() external override nonReentrant { // start a new claimable reserve auction, passing in relevant parameters such as the current pool size, debt, balance, and inflator value @@ -416,9 +416,9 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { /** * @inheritdoc IPoolTakerActions - * @dev write state: - * - increment `reserveAuction.totalAjnaBurned` accumulator - * - update burn event `totalInterest` and `totalBurned` accumulators + * @dev === Write state === + * @dev increment `reserveAuction.totalAjnaBurned` accumulator + * @dev update burn event `totalInterest` and `totalBurned` accumulators */ function takeReserves( uint256 maxAmount_ @@ -524,13 +524,11 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { /** * @notice Accrues pool interest in current block and returns pool details. - * @dev external libraries call: - * - `PoolCommons.accrueInterest` - * @dev write state: - * - `PoolCommons.accrueInterest`: - * - `Deposits.mult` (scale `Fenwick` tree with new interest accrued): - * - update scaling array state - * - increment `reserveAuction.totalInterestEarned` accumulator + * @dev external libraries call: `PoolCommons.accrueInterest` + * @dev === Write state === + * @dev - `PoolCommons.accrueInterest` - `Deposits.mult` (scale `Fenwick` tree with new interest accrued): + * @dev update scaling array state + * @dev - increment `reserveAuction.totalInterestEarned` accumulator * @return poolState_ Struct containing pool details. */ function _accruePoolInterest() internal returns (PoolState memory poolState_) { @@ -574,8 +572,8 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { /** * @notice Adjusts the `t0` debt 2 to collateral ratio, `interestState.t0Debt2ToCollateral`. * @dev Anytime a borrower's debt or collateral changes, the `interestState.t0Debt2ToCollateral` must be updated. - * @dev write state: - * - update `interestState.t0Debt2ToCollateral` accumulator + * @dev === Write state === + * @dev update `interestState.t0Debt2ToCollateral` accumulator * @param debtPreAction_ Borrower's debt before the action * @param debtPostAction_ Borrower's debt after the action * @param colPreAction_ Borrower's collateral before the action @@ -601,16 +599,14 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { /** * @notice Update interest rate and inflator of the pool. - * @dev external libraries call: - * - `PoolCommons.updateInterestState` - * @dev write state: - * - `PoolCommons.updateInterestState ` - * - `EMA`s accumulators - * - interest rate accumulator and `interestRateUpdate` state - * - pool inflator and `inflatorUpdate` state - * @dev emit events: - * - `PoolCommons.updateInterestState`: - * - `UpdateInterestRate` + * @dev external libraries call: `PoolCommons.updateInterestState` + * @dev === Write state === + * @dev - `PoolCommons.updateInterestState` + * @dev `EMA`s accumulators + * @dev interest rate accumulator and `interestRateUpdate` state + * @dev pool inflator and `inflatorUpdate` state + * @dev === Emit events === + * @dev `PoolCommons.updateInterestState`: `UpdateInterestRate` * @param poolState_ Struct containing pool details. * @param lup_ Current `LUP` in pool. */ diff --git a/src/interfaces/pool/IPoolFactory.sol b/src/interfaces/pool/IPoolFactory.sol index 83cdacc64..c6ad8cad7 100644 --- a/src/interfaces/pool/IPoolFactory.sol +++ b/src/interfaces/pool/IPoolFactory.sol @@ -17,7 +17,7 @@ interface IPoolFactory { error DeployQuoteCollateralSameToken(); /** - * @notice Can't deploy with one of the args pointing to the 0x0 address. + * @notice Can't deploy with one of the args pointing to the `0x` address. */ error DeployWithZeroAddress(); diff --git a/src/interfaces/pool/commons/IPoolState.sol b/src/interfaces/pool/commons/IPoolState.sol index c862c5fc3..46356542c 100644 --- a/src/interfaces/pool/commons/IPoolState.sol +++ b/src/interfaces/pool/commons/IPoolState.sol @@ -93,7 +93,7 @@ interface IPoolState { ); /** - * @notice Mapping of burnEventEpoch to {BurnEvent} structs. + * @notice Mapping of burnEventEpoch to `BurnEvent` structs. * @dev Reserve auctions correspond to burn events. * @param burnEventEpoch_ Id of the current reserve auction. * @return burnBlock_ Block in which a reserve auction started. diff --git a/src/interfaces/pool/commons/IPoolTakerActions.sol b/src/interfaces/pool/commons/IPoolTakerActions.sol index f03c21056..543412e61 100644 --- a/src/interfaces/pool/commons/IPoolTakerActions.sol +++ b/src/interfaces/pool/commons/IPoolTakerActions.sol @@ -9,8 +9,8 @@ interface IPoolTakerActions { /** * @notice Called by actors to use quote token to arb higher-priced deposit off the book. - * @param borrowerAddress_ Identifies the loan to liquidate. - * @param depositTake_ If true then the take will happen at an auction price equal with bucket price. Auction price is used otherwise. + * @param borrowerAddress_ Address of the borower take is being called upon. + * @param depositTake_ If `true` then the take will happen at an auction price equal with bucket price. Auction price is used otherwise. * @param index_ Index of a bucket, likely the `HPB`, in which collateral will be deposited. */ function bucketTake( diff --git a/src/libraries/external/BorrowerActions.sol b/src/libraries/external/BorrowerActions.sol index 9c5c584ee..e0afd63c0 100644 --- a/src/libraries/external/BorrowerActions.sol +++ b/src/libraries/external/BorrowerActions.sol @@ -35,7 +35,7 @@ import { SettlerActions } from './SettlerActions.sol'; /** @title BorrowerActions library @notice External library containing logic for for pool actors: - - Borrowers: pledge collateral and draw debt; repay debt and pull collateral + - `Borrowers`: pledge collateral and draw debt; repay debt and pull collateral */ library BorrowerActions { @@ -43,6 +43,7 @@ library BorrowerActions { /*** Local Var Structs ***/ /*************************/ + /// @dev Struct used for `drawDebt` function local vars. struct DrawDebtLocalVars { bool borrow; // true if borrow action uint256 borrowerDebt; // [WAD] borrower's accrued debt @@ -53,6 +54,8 @@ library BorrowerActions { bool pledge; // true if pledge action bool stampT0Np; // true if loan's t0 neutral price should be restamped (when drawing debt or pledge settles auction) } + + /// @dev Struct used for `repayDebt` function local vars. struct RepayDebtLocalVars { uint256 borrowerDebt; // [WAD] borrower's accrued debt uint256 compensatedCollateral; // [WAD] amount of borrower collateral that is compensated with LP (NFTs only) @@ -90,27 +93,23 @@ library BorrowerActions { /** * @notice See `IERC20PoolBorrowerActions` and `IERC721PoolBorrowerActions` for descriptions - * @dev write state: - * - SettlerActions._settleAuction: - * - _removeAuction: - * - decrement kicker locked accumulator, increment kicker claimable accumumlator - * - decrement auctions count accumulator - * - decrement auctions.totalBondEscrowed accumulator - * - update auction queue state - * - Loans.update: - * - _upsert: - * - insert or update loan in loans array - * - remove: - * - remove loan from loans array - * - update borrower in address => borrower mapping - * @dev reverts on: - * - borrower not sender BorrowerNotSender() - * - borrower debt less than pool min debt AmountLTMinDebt() - * - limit price reached LimitIndexExceeded() - * - borrower cannot draw more debt BorrowerUnderCollateralized() - * @dev emit events: - * - SettlerActions._settleAuction: - * - AuctionNFTSettle or AuctionSettle + * @dev === Write state === + * @dev - `SettlerActions._settleAuction` (`_removeAuction`): + * @dev decrement kicker locked accumulator, increment kicker claimable accumumlator + * @dev decrement auctions count accumulator + * @dev decrement `auctions.totalBondEscrowed` accumulator + * @dev update auction queue state + * @dev - `Loans.update` (`_upsert`): + * @dev insert or update loan in loans array + * @dev remove loan from loans array + * @dev update borrower in `address => borrower` mapping + * @dev === Reverts on === + * @dev borrower not sender `BorrowerNotSender()` + * @dev borrower debt less than pool min debt `AmountLTMinDebt()` + * @dev limit price reached `LimitIndexExceeded()` + * @dev borrower cannot draw more debt `BorrowerUnderCollateralized()` + * @dev === Emit events === + * @dev - `SettlerActions._settleAuction`: `AuctionNFTSettle` or `AuctionSettle` */ function drawDebt( AuctionsState storage auctions_, @@ -249,28 +248,24 @@ library BorrowerActions { /** * @notice See `IERC20PoolBorrowerActions` and `IERC721PoolBorrowerActions` for descriptions - * @dev write state: - * - SettlerActions._settleAuction: - * - _removeAuction: - * - decrement kicker locked accumulator, increment kicker claimable accumumlator - * - decrement auctions count accumulator - * - decrement auctions.totalBondEscrowed accumulator - * - update auction queue state - * - Loans.update: - * - _upsert: - * - insert or update loan in loans array - * - remove: - * - remove loan from loans array - * - update borrower in address => borrower mapping - * @dev reverts on: - * - no debt to repay NoDebt() - * - borrower debt less than pool min debt AmountLTMinDebt() - * - borrower not sender BorrowerNotSender() - * - not enough collateral to pull InsufficientCollateral() - * - limit price reached LimitIndexExceeded() - * @dev emit events: - * - SettlerActions._settleAuction: - * - AuctionNFTSettle or AuctionSettle + * @dev === Write state === + * @dev - `SettlerActions._settleAuction` (`_removeAuction`): + * @dev decrement kicker locked accumulator, increment kicker claimable accumumlator + * @dev decrement auctions count accumulator + * @dev decrement `auctions.totalBondEscrowed` accumulator + * @dev update auction queue state + * @dev - `Loans.update` (`_upsert`): + * @dev insert or update loan in loans array + * @dev remove loan from loans array + * @dev update borrower in `address => borrower` mapping + * @dev === Reverts on === + * @dev no debt to repay `NoDebt()` + * @dev borrower debt less than pool min debt `AmountLTMinDebt()` + * @dev borrower not sender `BorrowerNotSender()` + * @dev not enough collateral to pull `InsufficientCollateral()` + * @dev limit price reached `LimitIndexExceeded()` + * @dev === Emit events === + * @dev - `SettlerActions._settleAuction`: `AuctionNFTSettle` or `AuctionSettle` */ function repayDebt( AuctionsState storage auctions_, @@ -415,18 +410,16 @@ library BorrowerActions { /** * @notice See `IPoolBorrowerActions` for descriptions - * @dev write state: - * - Loans.update: - * - _upsert: - * - insert or update loan in loans array - * - remove: - * - remove loan from loans array - * - update borrower in address => borrower mapping - * @dev reverts on: - * - auction active AuctionActive() - * - loan not fully collateralized BorrowerUnderCollateralized() - * @dev emit events: - * - LoanStamped + * @dev === Write state === + * @dev - `Loans.update` (`_upsert`): + * @dev insert or update loan in loans array + * @dev remove loan from loans array + * @dev update borrower in `address => borrower` mapping + * @dev === Reverts on === + * @dev auction active `AuctionActive()` + * @dev loan not fully collateralized `BorrowerUnderCollateralized()` + * @dev === Emit events === + * @dev - `LoanStamped` */ function stampLoan( AuctionsState storage auctions_, @@ -475,10 +468,11 @@ library BorrowerActions { /**********************/ /** - * @notice Returns true if borrower is in auction. - * @dev Used to accuratley increment and decrement t0DebtInAuction. + * @notice Returns `true` if borrower is in auction. + * @dev Used to accuratley increment and decrement `t0DebtInAuction` accumulator. + * @param auctions_ Struct for pool auctions state. * @param borrower_ Borrower address to check auction status for. - * @return active_ Boolean, based on if borrower is in auction. + * @return `True` if borrower is in auction. */ function _inAuction( AuctionsState storage auctions_, diff --git a/src/libraries/external/KickerActions.sol b/src/libraries/external/KickerActions.sol index 9a3708e8a..368fd50be 100644 --- a/src/libraries/external/KickerActions.sol +++ b/src/libraries/external/KickerActions.sol @@ -50,6 +50,7 @@ library KickerActions { /*** Local Var Structs ***/ /*************************/ + /// @dev Struct used for `kick` function local vars. struct KickLocalVars { uint256 borrowerDebt; // [WAD] the accrued debt of kicked borrower uint256 borrowerCollateral; // [WAD] amount of kicked borrower collateral @@ -61,6 +62,8 @@ library KickerActions { uint256 t0KickPenalty; // [WAD] t0 debt added as kick penalty uint256 kickPenalty; // [WAD] current debt added as kick penalty } + + /// @dev Struct used for `kickWithDeposit` function local vars. struct KickWithDepositLocalVars { uint256 amountToDebitFromDeposit; // [WAD] the amount of quote tokens used to kick and debited from lender deposit uint256 bucketCollateral; // [WAD] amount of collateral in bucket @@ -100,11 +103,8 @@ library KickerActions { /***************************/ /** - * @notice Called to start borrower liquidation and to update the auctions queue. - * @param poolState_ Current state of the pool. - * @param borrowerAddress_ Address of the borrower to kick. - * @param limitIndex_ Index of the lower bound of NP tolerated when kicking the auction. - * @return kickResult_ The result of the kick action. + * @notice See `IPoolKickerActions` for descriptions. + * @return The `KickResult` struct result of the kick action. */ function kick( AuctionsState storage auctions_, @@ -128,18 +128,14 @@ library KickerActions { } /** - * @notice Called by lenders to kick loans using their deposits. - * @dev write state: - * - Deposits.unscaledRemove (remove amount in Fenwick tree, from index): - * - update values array state - * - decrement lender.lps accumulator - * - decrement bucket.lps accumulator - * @dev emit events: - * - RemoveQuoteToken - * @param poolState_ Current state of the pool. - * @param index_ The deposit index from where lender removes liquidity. - * @param limitIndex_ Index of the lower bound of NP tolerated when kicking the auction. - * @return kickResult_ The result of the kick action. + * @notice See `IPoolKickerActions` for descriptions. + * @dev === Write state === + * @dev - `Deposits.unscaledRemove` (remove amount in `Fenwick` tree, from index): update `values` array state + * @dev - decrement `lender.lps` accumulator + * @dev - decrement `bucket.lps` accumulator + * @dev === Emit events === + * @dev - `RemoveQuoteToken` + * @return kickResult_ The `KickResult` struct result of the kick action. */ function kickWithDeposit( AuctionsState storage auctions_, @@ -240,14 +236,15 @@ library KickerActions { /*************************/ /** - * @notice See `IPoolReserveAuctionActions` for descriptions. - * @dev write state: - * - update reserveAuction.unclaimed accumulator - * - update reserveAuction.kicked timestamp state - * @dev reverts on: - * - no reserves to claim NoReserves() - * @dev emit events: - * - KickReserveAuction + * @notice See `IPoolKickerActions` for descriptions. + * @dev === Write state === + * @dev update `reserveAuction.unclaimed` accumulator + * @dev update `reserveAuction.kicked` timestamp state + * @dev === Reverts on === + * @dev no reserves to claim `NoReserves()` + * @dev === Emit events === + * @dev - `KickReserveAuction` + * @return kickerAward_ The `LP`s awarded to reserve auction kicker. */ function kickReserveAuction( AuctionsState storage auctions_, @@ -301,24 +298,27 @@ library KickerActions { /** * @notice Called to start borrower liquidation and to update the auctions queue. - * @dev write state: - * - _recordAuction: - * - borrower -> liquidation mapping update - * - increment auctions count accumulator - * - increment auctions.totalBondEscrowed accumulator - * - updates auction queue state - * - _updateKicker: - * - update locked and claimable kicker accumulators - * - Loans.remove: - * - delete borrower from indices => borrower address mapping - * - remove loan from loans array - * @dev emit events: - * - Kick + * @dev === Write state === + * @dev - `_recordAuction`: + * @dev `borrower -> liquidation` mapping update + * @dev increment `auctions count` accumulator + * @dev increment `auctions.totalBondEscrowed` accumulator + * @dev updates auction queue state + * @dev - `_updateKicker`: + * @dev update `locked` and `claimable` kicker accumulators + * @dev - `Loans.remove`: + * @dev delete borrower from `indices => borrower` address mapping + * @dev remove loan from loans array + * @dev === Emit events === + * @dev - `Kick` + * @param auctions_ Struct for pool auctions state. + * @param deposits_ Struct for pool deposits state. + * @param loans_ Struct for pool loans state. * @param poolState_ Current state of the pool. * @param borrowerAddress_ Address of the borrower to kick. - * @param limitIndex_ Index of the lower bound of NP tolerated when kicking the auction. - * @param additionalDebt_ Additional debt to be used when calculating proposed LUP. - * @return kickResult_ The result of the kick action. + * @param limitIndex_ Index of the lower bound of `NP` tolerated when kicking the auction. + * @param additionalDebt_ Additional debt to be used when calculating proposed `LUP`. + * @return kickResult_ The `KickResult` struct result of the kick action. */ function _kick( AuctionsState storage auctions_, @@ -405,8 +405,9 @@ library KickerActions { /** * @notice Updates kicker balances. - * @dev write state: - * - update locked and claimable kicker accumulators + * @dev === Write state === + * @dev update `locked` and `claimable` kicker accumulators + * @param auctions_ Struct for pool auctions state. * @param bondSize_ Bond size to cover newly kicked auction. * @return bondDifference_ The amount that kicker should send to pool to cover auction bond. */ @@ -435,16 +436,17 @@ library KickerActions { } /** - * @notice Saves a new liquidation that was kicked. - * @dev write state: - * - borrower -> liquidation mapping update - * - increment auctions count accumulator - * - updates auction queue state + * @notice Saves in storage a new liquidation that was kicked. + * @dev === Write state === + * @dev `borrower -> liquidation` mapping update + * @dev increment auctions count accumulator + * @dev updates auction queue state + * @param auctions_ Struct for pool auctions state. * @param borrowerAddress_ Address of the borrower that is kicked. * @param bondSize_ Bond size to cover newly kicked auction. * @param bondFactor_ Bond factor of the newly kicked auction. - * @param momp_ Current pool MOMP. - * @param neutralPrice_ Current pool Neutral Price. + * @param momp_ Current pool `MOMP`. + * @param neutralPrice_ Current pool `Neutral Price`. */ function _recordAuction( AuctionsState storage auctions_, diff --git a/src/libraries/external/LPActions.sol b/src/libraries/external/LPActions.sol index 951ece024..a0e523fc5 100644 --- a/src/libraries/external/LPActions.sol +++ b/src/libraries/external/LPActions.sol @@ -10,8 +10,8 @@ import { Maths } from '../internal/Maths.sol'; /** @title LPActions library - @notice External library containing logic for LP owners to: - - increase/decrease/revoke LP allowance; approve/revoke LP transferors; transfer LP + @notice External library containing logic for `LP` owners to: + - `increase`/`decrease`/`revoke` `LP` allowance; `approve`/`revoke` `LP` transferors; `transfer` `LP` */ library LPActions { @@ -45,12 +45,12 @@ library LPActions { /** * @notice See `IPoolLenderActions` for descriptions - * @dev write state: - * - increment LP allowances - * @dev reverts on: - * - invalid indexes and amounts input InvalidAllowancesInput() - * @dev emit events: - * - IncreaseLPAllowance + * @dev === Write state === + * @dev increment `LP` allowances + * @dev === Reverts on === + * @dev invalid indexes and amounts input `InvalidAllowancesInput()` + * @dev === Emit events === + * @dev - `IncreaseLPAllowance` */ function increaseLPAllowance( mapping(uint256 => uint256) storage allowances_, @@ -81,12 +81,12 @@ library LPActions { /** * @notice See `IPoolLenderActions` for descriptions - * @dev write state: - * - decrement LP allowances - * @dev reverts on: - * - invalid indexes and amounts input InvalidAllowancesInput() - * @dev emit events: - * - DecreaseLPAllowance + * @dev === Write state === + * @dev decrement `LP` allowances + * @dev === Reverts on === + * @dev invalid indexes and amounts input `InvalidAllowancesInput()` + * @dev === Emit events === + * @dev - `DecreaseLPAllowance` */ function decreaseLPAllowance( mapping(uint256 => uint256) storage allowances_, @@ -118,10 +118,10 @@ library LPActions { /** * @notice See `IPoolLenderActions` for descriptions - * @dev write state: - * - decrement LP allowances - * @dev emit events: - * - RevokeLPAllowance + * @dev === Write state === + * @dev decrement `LP` allowances + * @dev === Emit events === + * @dev - `RevokeLPAllowance` */ function revokeLPAllowance( mapping(uint256 => uint256) storage allowances_, @@ -148,10 +148,10 @@ library LPActions { /** * @notice See `IPoolLenderActions` for descriptions - * @dev write state: - * - approvedTransferors mapping - * @dev emit events: - * - ApproveLPTransferors + * @dev === Write state === + * @dev `approvedTransferors` mapping + * @dev === Emit events === + * @dev - `ApproveLPTransferors` */ function approveLPTransferors( mapping(address => bool) storage allowances_, @@ -172,10 +172,10 @@ library LPActions { /** * @notice See `IPoolLenderActions` for descriptions - * @dev write state: - * - approvedTransferors mapping - * @dev emit events: - * - RevokeLPTransferors + * @dev === Write state === + * @dev `approvedTransferors` mapping + * @dev === Emit events === + * @dev - `RevokeLPTransferors` */ function revokeLPTransferors( mapping(address => bool) storage allowances_, @@ -196,15 +196,15 @@ library LPActions { /** * @notice See `IPoolLenderActions` for descriptions - * @dev write state: - * - delete allowance mapping - * - increment new lender.lps accumulator and lender.depositTime state - * - delete old lender from bucket -> lender mapping - * @dev reverts on: - * - invalid index InvalidIndex() - * - no allowance NoAllowance() - * @dev emit events: - * - TransferLP + * @dev === Write state === + * @dev delete allowance mapping + * @dev increment new `lender.lps` accumulator and `lender.depositTime` state + * @dev delete old lender from `bucket -> lender` mapping + * @dev === Reverts on === + * @dev invalid index `InvalidIndex()` + * @dev no allowance `NoAllowance()` + * @dev === Emit events === + * @dev - `TransferLP` */ function transferLP( mapping(uint256 => Bucket) storage buckets_, diff --git a/src/libraries/external/LenderActions.sol b/src/libraries/external/LenderActions.sol index 06c0780f9..28a9b214c 100644 --- a/src/libraries/external/LenderActions.sol +++ b/src/libraries/external/LenderActions.sol @@ -23,8 +23,8 @@ import { Maths } from '../internal/Maths.sol'; /** @title LenderActions library @notice External library containing logic for lender actors: - - Lenders: add, remove and move quote tokens; - - Traders: add, remove and move quote tokens; add and remove collateral + - `Lenders`: add, remove and move quote tokens; + - `Traders`: add, remove and move quote tokens; add and remove collateral */ library LenderActions { @@ -32,6 +32,7 @@ library LenderActions { /*** Local Var Structs ***/ /*************************/ + /// @dev Struct used for `moveQuoteToken` function local vars. struct MoveQuoteLocalVars { uint256 fromBucketPrice; // [WAD] Price of the bucket to move amount from. uint256 fromBucketCollateral; // [WAD] Total amount of collateral in from bucket. @@ -49,6 +50,8 @@ library LenderActions { uint256 ptp; // [WAD] Pool Threshold Price. uint256 htp; // [WAD] Highest Threshold Price. } + + /// @dev Struct used for `removeQuoteToken` function local vars. struct RemoveDepositParams { uint256 depositConstraint; // [WAD] Constraint on deposit in quote token. uint256 lpConstraint; // [WAD] Constraint in LPB terms. @@ -92,13 +95,12 @@ library LenderActions { /** * @notice See `IERC20PoolLenderActions` and `IERC721PoolLenderActions` for descriptions - * @dev write state: - * - Buckets.addCollateral: - * - increment bucket.collateral and bucket.lps accumulator - * - addLenderLP: - * - increment lender.lps accumulator and lender.depositTime state - * @dev reverts on: - * - invalid bucket index InvalidIndex() + * @dev === Write state === + * @dev - `Buckets.addCollateral`: + * @dev increment `bucket.collateral` and `bucket.lps` accumulator + * @dev `addLenderLP`: increment `lender.lps` accumulator and `lender.depositTime `state + * @dev === Reverts on === + * @dev invalid bucket index `InvalidIndex()` */ function addCollateral( mapping(uint256 => Bucket) storage buckets_, @@ -125,16 +127,15 @@ library LenderActions { /** * @notice See `IPoolLenderActions` for descriptions - * @dev write state: - * - Deposits.unscaledAdd (add new amount in Fenwick tree): - * - update values array state - * - increment bucket.lps accumulator - * - increment lender.lps accumulator and lender.depositTime state - * @dev reverts on: - * - invalid bucket index InvalidIndex() - * - same block when bucket becomes insolvent BucketBankruptcyBlock() - * @dev emit events: - * - AddQuoteToken + * @dev === Write state === + * @dev - `Deposits.unscaledAdd` (add new amount in `Fenwick` tree): update `values` array state + * @dev - increment `bucket.lps` accumulator + * @dev - increment `lender.lps` accumulator and `lender.depositTime` state + * @dev === Reverts on === + * @dev invalid bucket index `InvalidIndex()` + * @dev same block when bucket becomes insolvent `BucketBankruptcyBlock()` + * @dev === Emit events === + * @dev - `AddQuoteToken` */ function addQuoteToken( mapping(uint256 => Bucket) storage buckets_, @@ -200,23 +201,21 @@ library LenderActions { /** * @notice See `IPoolLenderActions` for descriptions - * @dev write state: - * - _removeMaxDeposit: - * - Deposits.unscaledRemove (remove amount in Fenwick tree, from index): - * - update values array state - * - Deposits.unscaledAdd (add amount in Fenwick tree, to index): - * - update values array state - * - decrement lender.lps accumulator for from bucket - * - increment lender.lps accumulator and lender.depositTime state for to bucket - * - decrement bucket.lps accumulator for from bucket - * - increment bucket.lps accumulator for to bucket - * @dev reverts on: - * - same index MoveToSameIndex() - * - dust amount DustAmountNotExceeded() - * - invalid index InvalidIndex() - * @dev emit events: - * - BucketBankruptcy - * - MoveQuoteToken + * @dev === Write state === + * @dev - `_removeMaxDeposit`: + * @dev `Deposits.unscaledRemove` (remove amount in `Fenwick` tree, from index): update `values` array state + * @dev - `Deposits.unscaledAdd` (add amount in `Fenwick` tree, to index): update `values` array state + * @dev - decrement `lender.lps` accumulator for from bucket + * @dev - increment `lender.lps` accumulator and `lender.depositTime` state for to bucket + * @dev - decrement `bucket.lps` accumulator for from bucket + * @dev - increment `bucket.lps` accumulator for to bucket + * @dev === Reverts on === + * @dev same index `MoveToSameIndex()` + * @dev dust amount `DustAmountNotExceeded()` + * @dev invalid index `InvalidIndex()` + * @dev === Emit events === + * @dev - `BucketBankruptcy` + * @dev - `MoveQuoteToken` */ function moveQuoteToken( mapping(uint256 => Bucket) storage buckets_, @@ -343,18 +342,17 @@ library LenderActions { /** * @notice See `IPoolLenderActions` for descriptions - * @dev write state: - * - _removeMaxDeposit: - * - Deposits.unscaledRemove (remove amount in Fenwick tree): - * - update values array state - * - decrement lender.lps accumulator - * - decrement bucket.lps accumulator - * @dev reverts on: - * - no LP NoClaim() - * - LUP lower than HTP LUPBelowHTP() - * @dev emit events: - * - RemoveQuoteToken - * - BucketBankruptcy + * @dev === Write state === + * @dev - `_removeMaxDeposit`: + * @dev `Deposits.unscaledRemove` (remove amount in `Fenwick` tree, from index): update `values` array state + * @dev - decrement `lender.lps` accumulator + * @dev - decrement `bucket.lps` accumulator + * @dev === Reverts on === + * @dev no `LP` `NoClaim()`; + * @dev `LUP` lower than `HTP` `LUPBelowHTP()` + * @dev === Emit events === + * @dev - `RemoveQuoteToken` + * @dev - `BucketBankruptcy` */ function removeQuoteToken( mapping(uint256 => Bucket) storage buckets_, @@ -431,14 +429,14 @@ library LenderActions { /** * @notice See `IPoolLenderActions` for descriptions - * @dev write state: - * - decrement lender.lps accumulator - * - decrement bucket.collateral and bucket.lps accumulator - * @dev reverts on: - * - not enough collateral InsufficientCollateral() - * - insufficient LP InsufficientLP() - * @dev emit events: - * - BucketBankruptcy + * @dev === Write state === + * @dev decrement `lender.lps` accumulator + * @dev decrement `bucket.collateral` and `bucket.lps` accumulator + * @dev === Reverts on === + * @dev not enough collateral `InsufficientCollateral()` + * @dev insufficient `LP` `InsufficientLP()` + * @dev === Emit events === + * @dev - `BucketBankruptcy` */ function removeCollateral( mapping(uint256 => Bucket) storage buckets_, @@ -503,13 +501,13 @@ library LenderActions { /** * @notice Removes max collateral amount from a given bucket index. - * @dev write state: - * - _removeMaxCollateral: - * - decrement lender.lps accumulator - * - decrement bucket.collateral and bucket.lps accumulator - * @dev reverts on: - * - not enough collateral InsufficientCollateral() - * - no claim NoClaim() + * @dev === Write state === + * @dev - `_removeMaxCollateral`: + * @dev decrement `lender.lps` accumulator + * @dev decrement `bucket.collateral` and `bucket.lps` accumulator + * @dev === Reverts on === + * @dev not enough collateral `InsufficientCollateral()` + * @dev no claim `NoClaim()` * @return Amount of collateral that was removed. * @return Amount of LP redeemed for removed collateral amount. */ @@ -532,13 +530,12 @@ library LenderActions { /** * @notice See `IERC721PoolLenderActions` for descriptions - * @dev write state: - * - Buckets.addCollateral: - * - increment bucket.collateral and bucket.lps accumulator - * - addLenderLP: - * - increment lender.lps accumulator and lender.depositTime state - * @dev reverts on: - * - invalid merge index CannotMergeToHigherPrice() + * @dev === Write state === + * @dev - `Buckets.addCollateral`: + * @dev increment `bucket.collateral` and `bucket.lps` accumulator + * @dev increment `lender.lps` accumulator and `lender.depositTime` state + * @dev === Reverts on === + * @dev invalid merge index `CannotMergeToHigherPrice()` */ function mergeOrRemoveCollateral( mapping(uint256 => Bucket) storage buckets_, @@ -594,14 +591,14 @@ library LenderActions { /** * @notice Removes max collateral amount from a given bucket index. - * @dev write state: - * - decrement lender.lps accumulator - * - decrement bucket.collateral and bucket.lps accumulator - * @dev reverts on: - * - not enough collateral InsufficientCollateral() - * - no claim NoClaim() - * @dev emit events: - * - BucketBankruptcy + * @dev === Write state === + * @dev decrement `lender.lps` accumulator + * @dev decrement `bucket.collateral` and `bucket.lps` accumulator + * @dev === Reverts on === + * @dev not enough collateral `InsufficientCollateral()` + * @dev no claim `NoClaim()` + * @dev === Emit events === + * @dev - `BucketBankruptcy` * @return collateralAmount_ Amount of collateral that was removed. * @return lpAmount_ Amount of LPs redeemed for removed collateral amount. */ @@ -680,9 +677,9 @@ library LenderActions { /** * @notice Removes the amount of quote tokens calculated for the given amount of LP. - * @dev write state: - * - Deposits.unscaledRemove (remove amount in Fenwick tree, from index): - * - update values array state + * @dev === Write state === + * @dev - `Deposits.unscaledRemove` (remove amount in `Fenwick` tree, from index): + * @dev update `values` array state * @return removedAmount_ Amount of scaled deposit removed. * @return redeemedLPs_ Amount of bucket LP corresponding for calculated scaled deposit amount. * @return unscaledRemaining_ Amount of unscaled deposit remaining. diff --git a/src/libraries/external/PoolCommons.sol b/src/libraries/external/PoolCommons.sol index 95ea4e4e7..dbffe991a 100644 --- a/src/libraries/external/PoolCommons.sol +++ b/src/libraries/external/PoolCommons.sol @@ -47,6 +47,7 @@ library PoolCommons { /*** Local Var Structs ***/ /*************************/ + /// @dev Struct used for `updateInterestState` function local vars. struct UpdateInterestLocalVars { uint256 debtEma; uint256 depositEma; @@ -71,11 +72,11 @@ library PoolCommons { /** * @notice Calculates EMAs, caches values required for calculating interest rate, and saves new values in storage. * @notice Calculates new pool interest rate (Never called more than once every 12 hours) and saves new values in storage. - * @dev write state: - * - EMAs state - * - interest rate accumulator and interestRateUpdate state - * @dev emit events: - * - UpdateInterestRate + * @dev === Write state === + * @dev `EMA`s state + * @dev interest rate accumulator and `interestRateUpdate` state + * @dev === Emit events === + * @dev - `UpdateInterestRate` / `ResetInterestRate` */ function updateInterestState( InterestState storage interestParams_, @@ -200,12 +201,15 @@ library PoolCommons { /** * @notice Calculates new pool interest and scale the fenwick tree to update amount of debt owed to lenders (saved in storage). - * @dev write state: - * - Deposits.mult (scale Fenwick tree with new interest accrued): - * - update scaling array state + * @dev === Write state === + * @dev - `Deposits.mult` (scale `Fenwick` tree with new interest accrued): + * @dev update `scaling` array state + * @param emaParams_ Struct for pool `EMA`s state. + * @param deposits_ Struct for pool deposits state. + * @param poolState_ Current state of the pool. * @param thresholdPrice_ Current Pool Threshold Price. * @param elapsed_ Time elapsed since last inflator update. - * @return newInflator_ The new value of pool inflator. + * @return newInflator_ The new value of pool inflator. */ function accrueInterest( EmaState storage emaParams_, @@ -292,8 +296,8 @@ library PoolCommons { /** * @notice Calculates pool meaningful actual utilization. - * @param debtEma_ EMA of pool debt. - * @param depositEma_ EMA of meaningful pool deposit. + * @param debtEma_ `EMA` of pool debt. + * @param depositEma_ `EMA` of meaningful pool deposit. * @return utilization_ Pool meaningful actual utilization value. */ function _utilization( diff --git a/src/libraries/external/PositionNFTSVG.sol b/src/libraries/external/PositionNFTSVG.sol index f0a5e6270..539f6400c 100644 --- a/src/libraries/external/PositionNFTSVG.sol +++ b/src/libraries/external/PositionNFTSVG.sol @@ -7,7 +7,7 @@ import { Base64 } from '@base64-sol/base64.sol'; /** @title Position NFT SVG library - @notice External library containing logic for generating SVG for a Position NFT. + @notice External library containing logic for generating `SVG` for a Position `NFT`. */ library PositionNFTSVG { diff --git a/src/libraries/external/SettlerActions.sol b/src/libraries/external/SettlerActions.sol index d24bf9a6d..ff1f2acb7 100644 --- a/src/libraries/external/SettlerActions.sol +++ b/src/libraries/external/SettlerActions.sol @@ -36,7 +36,7 @@ import { Maths } from '../internal/Maths.sol'; /** @title Auction settler library @notice External library containing actions involving auctions within pool: - - settle auctions + - `settle` auctions */ library SettlerActions { @@ -44,6 +44,7 @@ library SettlerActions { /*** Local Var Structs ***/ /*************************/ + /// @dev Struct used for `settlePoolDebt` function local vars. struct SettleLocalVars { uint256 collateralUsed; // [WAD] collateral used to settle debt uint256 debt; // [WAD] debt to settle @@ -82,23 +83,21 @@ library SettlerActions { /***************************/ /** - * @notice Settles the debt of the given loan / borrower. - * @dev write state: - * - Deposits.unscaledRemove() (remove amount in Fenwick tree, from index): - * - update values array state - * - Buckets.addCollateral: - * - increment bucket.collateral and bucket.lps accumulator - * - addLenderLP: - * - increment lender.lps accumulator and lender.depositTime state - * - update borrower state - * @dev reverts on: - * - loan is not in auction NoAuction() - * - 72 hours didn't pass and auction still has collateral AuctionNotClearable() - * @dev emit events: - * - Settle - * - BucketBankruptcy - * @param params_ Settle params - * @return result_ The result of settle action. + * @notice See `IPoolSettlerActions` for descriptions. + * @dev === Write state === + * @dev - `Deposits.unscaledRemove()` (remove amount in `Fenwick` tree, from index): + * @dev update `values` array state + * @dev - `Buckets.addCollateral`: + * @dev increment `bucket.collateral` and `bucket.lps` accumulator + * @dev increment `lender.lps` accumulator and `lender.depositTime` state + * @dev - update borrower state + * @dev === Reverts on === + * @dev loan is not in auction `NoAuction()` + * @dev `72` hours didn't pass and auction still has collateral `AuctionNotClearable()` + * @dev === Emit events === + * @dev - `Settle` + * @dev - `BucketBankruptcy` + * @return result_ The `SettleResult` struct result of settle action. */ function settlePoolDebt( AuctionsState storage auctions_, @@ -282,13 +281,16 @@ library SettlerActions { /** * @notice Performs auction settle based on pool type, emits settle event and removes auction from auctions queue. - * @dev emit events: - * - AuctionNFTSettle or AuctionSettle + * @dev === Emit events === + * @dev - `AuctionNFTSettle` or `AuctionSettle` + * @param auctions_ Struct for pool auctions state. + * @param buckets_ Struct for pool buckets state. + * @param deposits_ Struct for pool deposits state. * @param borrowerAddress_ Address of the borrower that exits auction. - * @param borrowerCollateral_ Borrower collateral amount before auction exit (in NFT could be fragmented as result of partial takes). - * @param poolType_ Type of the pool (can be ERC20 or NFT). - * @return remainingCollateral_ Collateral remaining after auction is settled (same amount for ERC20 pool, rounded collateral for NFT pool). - * @return compensatedCollateral_ Amount of collateral compensated (NFT settle only), to be deducted from pool pledged collateral accumulator. 0 for ERC20 pools. + * @param borrowerCollateral_ Borrower collateral amount before auction exit (in `NFT` could be fragmented as result of partial takes). + * @param poolType_ Type of the pool (can be `ERC20` or `ERC721`). + * @return remainingCollateral_ Collateral remaining after auction is settled (same amount for `ERC20` pool, rounded collateral for `ERC721` pool). + * @return compensatedCollateral_ Amount of collateral compensated (`ERC721` settle only), to be deducted from pool pledged collateral accumulator. Always `0` for `ERC20` pools. */ function _settleAuction( AuctionsState storage auctions_, @@ -351,11 +353,12 @@ library SettlerActions { /** * @notice Removes auction and repairs the queue order. - * @notice Updates kicker's claimable balance with bond size awarded and subtracts bond size awarded from liquidationBondEscrowed. - * @dev write state: - * - decrement kicker locked accumulator, increment kicker claimable accumumlator - * - decrement auctions count accumulator - * - update auction queue state + * @notice Updates kicker's claimable balance with bond size awarded and subtracts bond size awarded from `liquidationBondEscrowed`. + * @dev === Write state === + * @dev decrement kicker locked accumulator, increment kicker claimable accumumlator + * @dev decrement auctions count accumulator + * @dev update auction queue state + * @param auctions_ Struct for pool auctions state. * @param borrower_ Auctioned borrower address. */ function _removeAuction( diff --git a/src/libraries/external/TakerActions.sol b/src/libraries/external/TakerActions.sol index e0cbf6662..19934e8b0 100644 --- a/src/libraries/external/TakerActions.sol +++ b/src/libraries/external/TakerActions.sol @@ -42,7 +42,7 @@ import { Maths } from '../internal/Maths.sol'; /** @title Auction Taker Actions library @notice External library containing actions involving taking auctions within pool: - - take auctioned collateral; take reserves + - `take` and `bucketTake` auctioned collateral; take reserves */ library TakerActions { @@ -50,6 +50,7 @@ library TakerActions { /*** Function Params Structs ***/ /*******************************/ + /// @dev Struct used to hold `bucketTake` function params. struct BucketTakeParams { address borrower; // borrower address to take from bool depositTake; // deposit or arb take, used by bucket take @@ -57,6 +58,8 @@ library TakerActions { uint256 inflator; // [WAD] current pool inflator uint256 collateralScale; // precision of collateral token based on decimals } + + /// @dev Struct used to hold `take` function params. struct TakeParams { address borrower; // borrower address to take from uint256 takeCollateral; // [WAD] desired amount to take @@ -69,6 +72,7 @@ library TakerActions { /*** Local Var Structs ***/ /*************************/ + /// @dev Struct used for `take` function local vars. struct TakeLocalVars { uint256 auctionPrice; // [WAD] The price of auction. uint256 bondChange; // [WAD] The change made on the bond size (beeing reward or penalty). @@ -120,13 +124,11 @@ library TakerActions { /***************************/ /** + * @notice See `IPoolTakerActions` for descriptions. * @notice Performs bucket take collateral on an auction, rewards taker and kicker (if case) and updates loan info (settles auction if case). - * @dev reverts on: - * - insufficient collateral InsufficientCollateral() - * @param borrowerAddress_ Borrower address to take. - * @param depositTake_ If true then the take will happen at an auction price equal with bucket price. Auction price is used otherwise. - * @param index_ Index of a bucket, likely the HPB, in which collateral will be deposited. - * @return result_ BucketTakeResult struct containing details of take. + * @dev === Reverts on === + * @dev not enough collateral to take `InsufficientCollateral()` + * @return result_ `BucketTakeResult` struct containing details of bucket take result. */ function bucketTake( AuctionsState storage auctions_, @@ -189,12 +191,11 @@ library TakerActions { } /** + * @notice See `IPoolTakerActions` for descriptions. * @notice Performs take collateral on an auction, rewards taker and kicker (if case) and updates loan info (settles auction if case). - * @dev reverts on: - * - insufficient collateral InsufficientCollateral() - * @param borrowerAddress_ Borrower address to take. - * @param collateral_ Max amount of collateral that will be taken from the auction (max number of NFTs in case of ERC721 pool). - * @return result_ TakeResult struct containing details of take. + * @dev === Reverts on === + * @dev insufficient collateral to take `InsufficientCollateral()` + * @return result_ `TakeResult` struct containing details of take result. */ function take( AuctionsState storage auctions_, @@ -268,13 +269,13 @@ library TakerActions { /*************************/ /** - * @notice See `IPoolReserveAuctionActions` for descriptions. - * @dev write state: - * - decrement reserveAuction.unclaimed accumulator - * @dev reverts on: - * - not kicked or 72 hours didn't pass NoReservesAuction() - * @dev emit events: - * - ReserveAuction + * @notice See `IPoolTakerActions` for descriptions. + * @dev === Write state === + * @dev decrement `reserveAuction.unclaimed` accumulator + * @dev === Reverts on === + * @dev not kicked or `72` hours didn't pass `NoReservesAuction()` + * @dev === Emit events === + * @dev - `ReserveAuction` */ function takeReserves( ReserveAuctionState storage reserveAuction_, @@ -324,8 +325,9 @@ library TakerActions { /** * @notice Performs take collateral on an auction and updates bond size and kicker balance accordingly. - * @dev emit events: - * - Take + * @dev === Emit events === + * @dev - `Take` + * @param auctions_ Struct for pool auctions state. * @param borrower_ Struct containing auctioned borrower details. * @param params_ Struct containing take action params details. * @return vars_ Struct containing auction take vars. @@ -396,8 +398,11 @@ library TakerActions { /** * @notice Performs bucket take collateral on an auction and rewards taker and kicker (if case). - * @dev emit events: - * - BucketTake + * @dev === Emit events === + * @dev - `BucketTake` + * @param auctions_ Struct for pool auctions state. + * @param buckets_ Struct for pool buckets state. + * @param deposits_ Struct for pool deposits state. * @param borrower_ Struct containing auctioned borrower details. * @param params_ Struct containing take action details. * @return vars_ Struct containing auction take vars. @@ -466,14 +471,18 @@ library TakerActions { /** * @notice Performs update of an auctioned loan that was taken (using bucket or regular take). * @notice If borrower becomes recollateralized then auction is settled. Update loan's state. - * @dev reverts on: - * - borrower debt less than pool min debt AmountLTMinDebt() - * @param borrower_ Struct containing pool details. + * @dev === Reverts on === + * @dev borrower debt less than pool min debt `AmountLTMinDebt()` + * @param auctions_ Struct for pool auctions state. + * @param buckets_ Struct for pool buckets state. + * @param deposits_ Struct for pool deposits state. + * @param loans_ Struct for pool loans state. + * @param poolState_ Struct containing pool details. * @param borrower_ The borrower details owning loan that is taken. * @param borrowerAddress_ The address of the borrower. - * @return newLup_ The new LUP of pool (after debt is repaid). - * @return settledAuction_ True if auction is settled by the take action. (NFT take: rebalance borrower collateral in pool if true) - * @return remainingCollateral_ Borrower collateral remaining after take action. (NFT take: collateral to be rebalanced in case of NFT settlement) + * @return newLup_ The new `LUP` of pool (after debt is repaid). + * @return settledAuction_ True if auction is settled by the take action. (`NFT` take: rebalance borrower collateral in pool if true) + * @return remainingCollateral_ Borrower collateral remaining after take action. (`NFT` take: collateral to be rebalanced in case of `NFT` settlement) * @return compensatedCollateral_ Amount of collateral compensated, to be deducted from pool pledged collateral accumulator. */ function _takeLoan( @@ -539,11 +548,13 @@ library TakerActions { /** * @notice Rewards actors of a regular take action. - * @dev write state: - * - update liquidation bond size accumulator - * - update kicker's locked balance accumulator - * - update auctions.totalBondEscrowed accumulator - * @param vars Struct containing take action result details. + * @dev === Write state === + * @dev update liquidation `bond size` accumulator + * @dev update kicker's `locked balance` accumulator + * @dev update `auctions.totalBondEscrowed` accumulator + * @param auctions_ Struct for pool auctions state. + * @param liquidation_ Struct containing details of auction. + * @param vars Struct containing take action result details. */ function _rewardTake( AuctionsState storage auctions_, @@ -567,19 +578,25 @@ library TakerActions { /** * @notice Rewards actors of a bucket take action. - * @dev write state: - * - Buckets.addLenderLP: - * - increment taker lender.lps accumulator and lender.depositTime state - * - increment kicker lender.lps accumulator and lender.depositTime state - * - update liquidation bond size accumulator - * - update kicker's locked balance accumulator - * - update auctions.totalBondEscrowed accumulator - * - Deposits.unscaledRemove() (remove amount in Fenwick tree, from index): - * - update values array state - * - increment bucket.collateral and bucket.lps accumulator - * @dev emit events: - * - BucketTakeLPAwarded - * @param vars Struct containing take action result details. + * @dev === Write state === + * @dev - `Buckets.addLenderLP`: + * @dev increment taker `lender.lps` accumulator and `lender.depositTime` state + * @dev increment kicker `lender.lps` accumulator and l`ender.depositTime` state + * @dev - update liquidation bond size accumulator + * @dev - update kicker's locked balance accumulator + * @dev - update `auctions.totalBondEscrowed` accumulator + * @dev - `Deposits.unscaledRemove()` (remove amount in `Fenwick` tree, from index): + * @dev update `values` array state + * @dev - increment `bucket.collateral` and `bucket.lps` accumulator + * @dev === Emit events === + * @dev - `BucketTakeLPAwarded` + * @param auctions_ Struct for pool auctions state. + * @param deposits_ Struct for pool deposits state. + * @param buckets_ Struct for pool buckets state. + * @param liquidation_ Struct containing details of auction to be taken from. + * @param bucketIndex_ Index of a bucket, likely the `HPB`, in which collateral will be deposited. + * @param depositTake_ If `true` then the take will happen at an auction price equal with bucket price. Auction price is used otherwise. + * @param vars Struct containing bucket take action result details. */ function _rewardBucketTake( AuctionsState storage auctions_, diff --git a/src/libraries/helpers/PoolHelper.sol b/src/libraries/helpers/PoolHelper.sol index 3e0285e1e..d526896bc 100644 --- a/src/libraries/helpers/PoolHelper.sol +++ b/src/libraries/helpers/PoolHelper.sol @@ -16,33 +16,30 @@ import { Maths } from '../internal/Maths.sol'; /*** Price Conversions ***/ /*************************/ - /** - @dev constant price indices defining the min and max of the potential price range - */ + /// @dev constant price indices defining the min and max of the potential price range int256 constant MAX_BUCKET_INDEX = 4_156; int256 constant MIN_BUCKET_INDEX = -3_232; uint256 constant MAX_FENWICK_INDEX = 7_388; uint256 constant MIN_PRICE = 99_836_282_890; uint256 constant MAX_PRICE = 1_004_968_987.606512354182109771 * 1e18; - /** - @dev step amounts in basis points. This is a constant across pools at .005, achieved by dividing WAD by 10,000 - */ + + /// @dev step amounts in basis points. This is a constant across pools at `0.005`, achieved by dividing `WAD` by `10,000` int256 constant FLOAT_STEP_INT = 1.005 * 1e18; /** - * @notice Calculates the price for a given Fenwick index - * @dev Throws if index exceeds maximum constant - * @dev Uses fixed-point math to get around lack of floating point numbers in EVM - * @dev Price expected to be inputted as a 18 decimal WAD - * @dev Fenwick index is converted to bucket index - * @dev Fenwick index to bucket index conversion - * 1.00 : bucket index 0, fenwick index 4156: 7388-4156-3232=0 - * MAX_PRICE : bucket index 4156, fenwick index 0: 7388-0-3232=4156. - * MIN_PRICE : bucket index -3232, fenwick index 7388: 7388-7388-3232=-3232. - * @dev V1: price = MIN_PRICE + (FLOAT_STEP * index) - * V2: price = MAX_PRICE * (FLOAT_STEP ** (abs(int256(index - MAX_PRICE_INDEX)))); - * V3 (final): x^y = 2^(y*log_2(x)) + * @notice Calculates the price for a given `Fenwick` index. + * @dev Reverts with `BucketIndexOutOfBounds` if index exceeds maximum constant. + * @dev Uses fixed-point math to get around lack of floating point numbers in `EVM`. + * @dev Price expected to be inputted as a `WAD` (`18` decimal). + * @dev Fenwick index is converted to bucket index. + * @dev Fenwick index to bucket index conversion: + * @dev `1.00` : bucket index `0`, fenwick index `4156`: `7388-4156-3232=0`. + * @dev `MAX_PRICE` : bucket index `4156`, fenwick index `0`: `7388-0-3232=4156`. + * @dev `MIN_PRICE` : bucket index - `3232`, fenwick index `7388`: `7388-7388-3232=-3232`. + * @dev `V1`: `price = MIN_PRICE + (FLOAT_STEP * index)` + * @dev `V2`: `price = MAX_PRICE * (FLOAT_STEP ** (abs(int256(index - MAX_PRICE_INDEX))));` + * @dev `V3 (final)`: `x^y = 2^(y*log_2(x))` */ function _priceAt( uint256 index_ @@ -62,13 +59,13 @@ import { Maths } from '../internal/Maths.sol'; } /** - * @notice Calculates the Fenwick index for a given price - * @dev Throws if price exceeds maximum constant - * @dev Price expected to be inputted as a 18 decimal WAD - * @dev V1: bucket index = (price - MIN_PRICE) / FLOAT_STEP - * V2: bucket index = (log(FLOAT_STEP) * price) / MAX_PRICE - * V3 (final): bucket index = log_2(price) / log_2(FLOAT_STEP) - * @dev Fenwick index = 7388 - bucket index + 3232 + * @notice Calculates the Fenwick index for a given price. + * @dev Reverts with `BucketPriceOutOfBounds` if price exceeds maximum constant. + * @dev Price expected to be inputted as a `WAD` (`18` decimal). + * @dev `V1`: `bucket index = (price - MIN_PRICE) / FLOAT_STEP` + * @dev `V2`: `bucket index = (log(FLOAT_STEP) * price) / MAX_PRICE` + * @dev `V3 (final)`: `bucket index = log_2(price) / log_2(FLOAT_STEP)` + * @dev `Fenwick index = 7388 - bucket index + 3232` */ function _indexOf( uint256 price_ @@ -108,7 +105,7 @@ import { Maths } from '../internal/Maths.sol'; /** * @notice Calculates origination fee for a given interest rate. - * @notice Calculated as greater of the current annualized interest rate divided by 52 (one week of interest) or 5 bps. + * @notice Calculated as greater of the current annualized interest rate divided by `52` (one week of interest) or `5` bps. * @param interestRate_ The current interest rate. * @return Fee rate based upon the given interest rate. */ @@ -120,7 +117,7 @@ import { Maths } from '../internal/Maths.sol'; } /** - * @notice Calculates the unutilized deposit fee, charged to lenders who deposit below the LUP. + * @notice Calculates the unutilized deposit fee, charged to lenders who deposit below the `LUP`. * @param interestRate_ The current interest rate. * @return Fee rate based upon the given interest rate. */ @@ -132,10 +129,10 @@ import { Maths } from '../internal/Maths.sol'; } /** - * @notice Calculates debt-weighted average threshold price - * @param t0Debt_ pool debt owed by borrowers in t0 terms - * @param inflator_ pool's borrower inflator - * @param t0Debt2ToCollateral_ t0-debt-squared-to-collateral accumulator + * @notice Calculates debt-weighted average threshold price. + * @param t0Debt_ Pool debt owed by borrowers in `t0` terms. + * @param inflator_ Pool's borrower inflator. + * @param t0Debt2ToCollateral_ `t0-debt-squared-to-collateral` accumulator. */ function _dwatp( uint256 t0Debt_, @@ -151,7 +148,7 @@ import { Maths } from '../internal/Maths.sol'; * @param collateral_ Collateral to calculate collateralization for. * @param price_ Price to calculate collateralization for. * @param type_ Type of the pool. - * @return True if collateralization calculated is equal or greater than 1. + * @return `True` if collateralization calculated is equal or greater than `1`. */ function _isCollateralized( uint256 debt_, @@ -171,7 +168,7 @@ import { Maths } from '../internal/Maths.sol'; * @notice Price precision adjustment used in calculating collateral dust for a bucket. * To ensure the accuracy of the exchange rate calculation, buckets with smaller prices require * larger minimum amounts of collateral. This formula imposes a lower bound independent of token scale. - * @param bucketIndex_ Index of the bucket, or 0 for encumbered collateral with no bucket affinity. + * @param bucketIndex_ Index of the bucket, or `0` for encumbered collateral with no bucket affinity. * @return pricePrecisionAdjustment_ Unscaled integer of the minimum number of decimal places the dust limit requires. */ function _getCollateralDustPricePrecisionAdjustment( @@ -186,23 +183,23 @@ import { Maths } from '../internal/Maths.sol'; } /** - * @notice Returns the amount of collateral calculated for the given amount of LP. + * @notice Returns the amount of collateral calculated for the given amount of `LP`. * @param bucketCollateral_ Amount of collateral in bucket. - * @param bucketLPs_ Amount of LP in bucket. - * @param deposit_ Current bucket deposit (quote tokens). Used to calculate bucket's exchange rate / LP. + * @param bucketLP_ Amount of `LP` in bucket. + * @param deposit_ Current bucket deposit (quote tokens). Used to calculate bucket's exchange rate / `LP`. * @param lenderLPsBalance_ The amount of LP to calculate collateral for. - * @param bucketPrice_ Bucket price. - * @return collateralAmount_ Amount of collateral calculated for the given LP amount. + * @param bucketPrice_ Bucket's price. + * @return collateralAmount_ Amount of collateral calculated for the given `LP `amount. */ function _lpToCollateral( uint256 bucketCollateral_, - uint256 bucketLPs_, + uint256 bucketLP_, uint256 deposit_, uint256 lenderLPsBalance_, uint256 bucketPrice_ ) pure returns (uint256 collateralAmount_) { // max collateral to lps - uint256 rate = Buckets.getExchangeRate(bucketCollateral_, bucketLPs_, deposit_, bucketPrice_); + uint256 rate = Buckets.getExchangeRate(bucketCollateral_, bucketLP_, deposit_, bucketPrice_); collateralAmount_ = Maths.wdiv(Maths.wmul(lenderLPsBalance_, rate), bucketPrice_); @@ -213,24 +210,24 @@ import { Maths } from '../internal/Maths.sol'; } /** - * @notice Returns the amount of quote tokens calculated for the given amount of LP. - * @param bucketLPs_ Amount of LP in bucket. + * @notice Returns the amount of quote tokens calculated for the given amount of `LP`. + * @param bucketLP_ Amount of `LP` in bucket. * @param bucketCollateral_ Amount of collateral in bucket. - * @param deposit_ Current bucket deposit (quote tokens). Used to calculate bucket's exchange rate / LP. - * @param lenderLPsBalance_ The amount of LP to calculate quote token amount for. - * @param maxQuoteToken_ The max quote token amount to calculate LP for. - * @param bucketPrice_ Bucket price. - * @return quoteTokenAmount_ Amount of quote tokens calculated for the given LP amount. + * @param deposit_ Current bucket deposit (quote tokens). Used to calculate bucket's exchange rate / `LP`. + * @param lenderLPsBalance_ The amount of `LP` to calculate quote token amount for. + * @param maxQuoteToken_ The max quote token amount to calculate `LP` for. + * @param bucketPrice_ Bucket's price. + * @return quoteTokenAmount_ Amount of quote tokens calculated for the given `LP` amount. */ function _lpToQuoteToken( - uint256 bucketLPs_, + uint256 bucketLP_, uint256 bucketCollateral_, uint256 deposit_, uint256 lenderLPsBalance_, uint256 maxQuoteToken_, uint256 bucketPrice_ ) pure returns (uint256 quoteTokenAmount_) { - uint256 rate = Buckets.getExchangeRate(bucketCollateral_, bucketLPs_, deposit_, bucketPrice_); + uint256 rate = Buckets.getExchangeRate(bucketCollateral_, bucketLP_, deposit_, bucketPrice_); quoteTokenAmount_ = Maths.wmul(lenderLPsBalance_, rate); @@ -241,7 +238,7 @@ import { Maths } from '../internal/Maths.sol'; /** * @notice Rounds a token amount down to the minimum amount permissible by the token scale. * @param amount_ Value to be rounded. - * @param tokenScale_ Scale of the token, presented as a power of 10. + * @param tokenScale_ Scale of the token, presented as a power of `10`. * @return scaledAmount_ Rounded value. */ function _roundToScale( @@ -254,7 +251,7 @@ import { Maths } from '../internal/Maths.sol'; /** * @notice Rounds a token amount up to the next amount permissible by the token scale. * @param amount_ Value to be rounded. - * @param tokenScale_ Scale of the token, presented as a power of 10. + * @param tokenScale_ Scale of the token, presented as a power of `10`. * @return scaledAmount_ Rounded value. */ function _roundUpToScale( @@ -273,6 +270,15 @@ import { Maths } from '../internal/Maths.sol'; uint256 constant MINUTE_HALF_LIFE = 0.988514020352896135_356867505 * 1e27; // 0.5^(1/60) + /** + * @notice Calculates claimable reserves within the pool. + * @param debt_ Pool's debt. + * @param poolSize_ Pool's deposit size. + * @param totalBondEscrowed_ Total bond escrowed. + * @param reserveAuctionUnclaimed_ Pool's unclaimed reserve auction. + * @param quoteTokenBalance_ Pool's quote token balance. + * @return claimable_ Calculated pool reserves. + */ function _claimableReserves( uint256 debt_, uint256 poolSize_, @@ -285,15 +291,20 @@ import { Maths } from '../internal/Maths.sol'; claimable_ -= Maths.min(claimable_, poolSize_ + totalBondEscrowed_ + reserveAuctionUnclaimed_); } + /** + * @notice Calculates reserves auction price. + * @param reserveAuctionKicked_ Time when reserve auction was started (kicked). + * @return price_ Calculated auction price. + */ function _reserveAuctionPrice( uint256 reserveAuctionKicked_ - ) view returns (uint256 _price) { + ) view returns (uint256 price_) { if (reserveAuctionKicked_ != 0) { uint256 secondsElapsed = block.timestamp - reserveAuctionKicked_; uint256 hoursComponent = 1e27 >> secondsElapsed / 3600; uint256 minutesComponent = Maths.rpow(MINUTE_HALF_LIFE, secondsElapsed % 3600 / 60); - _price = Maths.rayToWad(1_000_000_000 * Maths.rmul(hoursComponent, minutesComponent)); + price_ = Maths.rayToWad(1_000_000_000 * Maths.rmul(hoursComponent, minutesComponent)); } } @@ -303,10 +314,10 @@ import { Maths } from '../internal/Maths.sol'; /** * @notice Calculates auction price. - * @param kickMomp_ MOMP recorded at the time of kick. - * @param neutralPrice_ Neutral Price of the auction. - * @param kickTime_ Time when auction was kicked. - * @return price_ Calculated auction price. + * @param kickMomp_ `MOMP` recorded at the time of kick. + * @param neutralPrice_ `Neutral Price` of the auction. + * @param kickTime_ Time when auction was kicked. + * @return price_ Calculated auction price. */ function _auctionPrice( uint256 kickMomp_, @@ -328,10 +339,10 @@ import { Maths } from '../internal/Maths.sol'; * @dev Called in kick and take. * @param debt_ Borrower debt. * @param collateral_ Borrower collateral. - * @param neutralPrice_ NP of auction. + * @param neutralPrice_ `NP` of auction. * @param bondFactor_ Factor used to determine bondSize. * @param auctionPrice_ Auction price at the time of call. - * @return bpf_ Factor used in determining bond Reward (positive) or penalty (negative). + * @return bpf_ Factor used in determining bond `reward` (positive) or `penalty` (negative). */ function _bpf( uint256 debt_, @@ -368,7 +379,7 @@ import { Maths } from '../internal/Maths.sol'; * @notice Calculates bond parameters of an auction. * @param borrowerDebt_ Borrower's debt before entering in liquidation. * @param collateral_ Borrower's collateral before entering in liquidation. - * @param momp_ Current pool momp. + * @param momp_ Current pool `momp`. */ function _bondParams( uint256 borrowerDebt_, diff --git a/src/libraries/helpers/RevertsHelper.sol b/src/libraries/helpers/RevertsHelper.sol index 89f34535e..fa04283bf 100644 --- a/src/libraries/helpers/RevertsHelper.sol +++ b/src/libraries/helpers/RevertsHelper.sol @@ -25,8 +25,9 @@ import { Maths } from '../internal/Maths.sol'; error TransactionExpired(); /** - * @notice Called by LPB removal functions assess whether or not LPB is locked. - * @param index_ The deposit index from which LPB is attempting to be removed. + * @notice Called by `LP` removal functions assess whether or not `LP` is locked. + * @dev Reverts with `RemoveDepositLockedByAuctionDebt` if debt locked. + * @param index_ The deposit index from which `LP` is attempting to be removed. * @param inflator_ The pool inflator used to properly assess t0 debt in auctions. */ function _revertIfAuctionDebtLocked( @@ -43,8 +44,8 @@ import { Maths } from '../internal/Maths.sol'; } /** - * @notice Check if head auction is clearable (auction is kicked and 72 hours passed since kick time or auction still has debt but no remaining collateral). - * @notice Revert if auction is clearable + * @notice Check if head auction is clearable (auction is kicked and `72` hours passed since kick time or auction still has debt but no remaining collateral). + * @dev Reverts with `AuctionNotCleared` if auction is clearable. */ function _revertIfAuctionClearable( AuctionsState storage auctions_, @@ -61,10 +62,11 @@ import { Maths } from '../internal/Maths.sol'; } /** - * @notice Check if provided price is at or above index limit provided by borrower. - * @notice Prevents stale transactions and certain MEV manipulations. - * @param newPrice_ New price to be compared with given limit price (can be LUP, NP). - * @param limitIndex_ Limit price index provided by user creating the TX. + * @notice Check if provided price is at or above index limit provided by borrower. + * @notice Prevents stale transactions and certain `MEV` manipulations. + * @dev Reverts with `LimitIndexExceeded` if index limit provided exceeded. + * @param newPrice_ New price to be compared with given limit price (can be `LUP`, `NP`). + * @param limitIndex_ Limit price index provided by user creating the transaction. */ function _revertIfPriceDroppedBelowLimit( uint256 newPrice_, @@ -76,7 +78,8 @@ import { Maths } from '../internal/Maths.sol'; /** * @notice Check if expiration provided by user has met or exceeded current block height timestamp. * @notice Prevents stale transactions interacting with the pool at potentially unfavorable prices. - * @param expiry_ Expiration provided by user when creating the TX. + * @dev Reverts with `TransactionExpired` if expired. + * @param expiry_ Expiration provided by user when creating the transaction. */ function _revertOnExpiry( uint256 expiry_ @@ -86,10 +89,11 @@ import { Maths } from '../internal/Maths.sol'; /** * @notice Called when borrower debt changes, ensuring minimum debt rules are honored. - * @param loans_ Loans heap, used to determine loan count. - * @param poolDebt_ Total pool debt, used to calculate average debt. - * @param borrowerDebt_ New debt for the borrower, assuming the current transaction succeeds. - * @param quoteDust_ Smallest amount of quote token when can be transferred, determined by token scale. + * @dev Reverts with `DustAmountNotExceeded` if under dust amount or with `AmountLTMinDebt` if amount under min debt value. + * @param loans_ Loans heap, used to determine loan count. + * @param poolDebt_ Total pool debt, used to calculate average debt. + * @param borrowerDebt_ New debt for the borrower, assuming the current transaction succeeds. + * @param quoteDust_ Smallest amount of quote token when can be transferred, determined by token scale. */ function _revertOnMinDebt( LoansState storage loans_, diff --git a/src/libraries/internal/Buckets.sol b/src/libraries/internal/Buckets.sol index e374aa4c8..9a52cbdd3 100644 --- a/src/libraries/internal/Buckets.sol +++ b/src/libraries/internal/Buckets.sol @@ -24,15 +24,15 @@ library Buckets { /***********************************/ /** - * @notice Add collateral to a bucket and updates LP for bucket and lender with the amount coresponding to collateral amount added. - * @dev Increment bucket.collateral and bucket.lps accumulator - * - addLenderLP: - * - increment lender.lps accumulator and lender.depositTime state + * @notice Add collateral to a bucket and updates `LP` for bucket and lender with the amount coresponding to collateral amount added. + * @dev Increment `bucket.collateral` and `bucket.lps` accumulator + * @dev - `addLenderLP`: + * @dev increment `lender.lps` accumulator and `lender.depositTime` state * @param lender_ Address of the lender. - * @param deposit_ Current bucket deposit (quote tokens). Used to calculate bucket's exchange rate / LP + * @param deposit_ Current bucket deposit (quote tokens). Used to calculate bucket's exchange rate / `LP`. * @param collateralAmountToAdd_ Additional collateral amount to add to bucket. * @param bucketPrice_ Bucket price. - * @return addedLPs_ Amount of bucket LP for the collateral amount added. + * @return addedLP_ Amount of bucket `LP` for the collateral amount added. */ function addCollateral( Bucket storage bucket_, @@ -40,13 +40,13 @@ library Buckets { uint256 deposit_, uint256 collateralAmountToAdd_, uint256 bucketPrice_ - ) internal returns (uint256 addedLPs_) { + ) internal returns (uint256 addedLP_) { // cannot deposit in the same block when bucket becomes insolvent uint256 bankruptcyTime = bucket_.bankruptcyTime; if (bankruptcyTime == block.timestamp) revert BucketBankruptcyBlock(); // calculate amount of LP to be added for the amount of collateral added to bucket - addedLPs_ = collateralToLP( + addedLP_ = collateralToLP( bucket_.collateral, bucket_.lps, deposit_, @@ -58,30 +58,30 @@ library Buckets { // update bucket collateral bucket_.collateral += collateralAmountToAdd_; // update bucket and lender LP balance and deposit timestamp - bucket_.lps += addedLPs_; + bucket_.lps += addedLP_; - addLenderLP(bucket_, bankruptcyTime, lender_, addedLPs_); + addLenderLP(bucket_, bankruptcyTime, lender_, addedLP_); } /** - * @notice Add amount of LP for a given lender in a given bucket. + * @notice Add amount of `LP` for a given lender in a given bucket. * @dev Increments lender lps accumulator and updates the deposit time. - * @param bucket_ Bucket to record lender LP. + * @param bucket_ Bucket to record lender `LP`. * @param bankruptcyTime_ Time when bucket become insolvent. - * @param lender_ Lender address to add LP for in the given bucket. - * @param lpsAmount_ Amount of LP to be recorded for the given lender. + * @param lender_ Lender address to add `LP` for in the given bucket. + * @param lpAmount_ Amount of `LP` to be recorded for the given lender. */ function addLenderLP( Bucket storage bucket_, uint256 bankruptcyTime_, address lender_, - uint256 lpsAmount_ + uint256 lpAmount_ ) internal { - if (lpsAmount_ != 0) { + if (lpAmount_ != 0) { Lender storage lender = bucket_.lenders[lender_]; - if (bankruptcyTime_ >= lender.depositTime) lender.lps = lpsAmount_; - else lender.lps += lpsAmount_; + if (bankruptcyTime_ >= lender.depositTime) lender.lps = lpAmount_; + else lender.lps += lpAmount_; lender.depositTime = block.timestamp; } @@ -92,62 +92,62 @@ library Buckets { /**********************/ /** - * @notice Returns the amount of bucket LP calculated for the given amount of collateral. + * @notice Returns the amount of bucket `LP` calculated for the given amount of collateral. * @param bucketCollateral_ Amount of collateral in bucket. - * @param bucketLPs_ Amount of LP in bucket. - * @param deposit_ Current bucket deposit (quote tokens). Used to calculate bucket's exchange rate / LP. - * @param collateral_ The amount of collateral to calculate bucket LP for. - * @param bucketPrice_ Price bucket. - * @return lps_ Amount of LP calculated for the amount of collateral. + * @param bucketLP_ Amount of `LP` in bucket. + * @param deposit_ Current bucket deposit (quote tokens). Used to calculate bucket's exchange rate / `LP`. + * @param collateral_ The amount of collateral to calculate bucket LP for. + * @param bucketPrice_ Bucket's price. + * @return lp_ Amount of `LP` calculated for the amount of collateral. */ function collateralToLP( uint256 bucketCollateral_, - uint256 bucketLPs_, + uint256 bucketLP_, uint256 deposit_, uint256 collateral_, uint256 bucketPrice_ - ) internal pure returns (uint256 lps_) { - uint256 rate = getExchangeRate(bucketCollateral_, bucketLPs_, deposit_, bucketPrice_); + ) internal pure returns (uint256 lp_) { + uint256 rate = getExchangeRate(bucketCollateral_, bucketLP_, deposit_, bucketPrice_); - lps_ = Maths.wdiv(Maths.wmul(collateral_, bucketPrice_), rate); + lp_ = Maths.wdiv(Maths.wmul(collateral_, bucketPrice_), rate); } /** - * @notice Returns the amount of LP calculated for the given amount of quote tokens. + * @notice Returns the amount of `LP` calculated for the given amount of quote tokens. * @param bucketCollateral_ Amount of collateral in bucket. - * @param bucketLPs_ Amount of LP in bucket. - * @param deposit_ Current bucket deposit (quote tokens). Used to calculate bucket's exchange rate / LP. - * @param quoteTokens_ The amount of quote tokens to calculate LP amount for. - * @param bucketPrice_ Price bucket. - * @return The amount of LP coresponding to the given quote tokens in current bucket. + * @param bucketLP_ Amount of `LP` in bucket. + * @param deposit_ Current bucket deposit (quote tokens). Used to calculate bucket's exchange rate / `LP`. + * @param quoteTokens_ The amount of quote tokens to calculate `LP` amount for. + * @param bucketPrice_ Bucket's price. + * @return The amount of `LP` coresponding to the given quote tokens in current bucket. */ function quoteTokensToLP( uint256 bucketCollateral_, - uint256 bucketLPs_, + uint256 bucketLP_, uint256 deposit_, uint256 quoteTokens_, uint256 bucketPrice_ ) internal pure returns (uint256) { return Maths.wdiv( quoteTokens_, - getExchangeRate(bucketCollateral_, bucketLPs_, deposit_, bucketPrice_) + getExchangeRate(bucketCollateral_, bucketLP_, deposit_, bucketPrice_) ); } /** * @notice Returns the exchange rate for a given bucket. * @param bucketCollateral_ Amount of collateral in bucket. - * @param bucketLPs_ Amount of LP in bucket. + * @param bucketLP_ Amount of `LP` in bucket. * @param bucketDeposit_ The amount of quote tokens deposited in the given bucket. * @param bucketPrice_ Bucket's price. */ function getExchangeRate( uint256 bucketCollateral_, - uint256 bucketLPs_, + uint256 bucketLP_, uint256 bucketDeposit_, uint256 bucketPrice_ ) internal pure returns (uint256) { - return bucketLPs_ == 0 ? Maths.WAD : - Maths.wdiv(bucketDeposit_ + Maths.wmul(bucketPrice_, bucketCollateral_), bucketLPs_); + return bucketLP_ == 0 ? Maths.WAD : + Maths.wdiv(bucketDeposit_ + Maths.wmul(bucketPrice_, bucketCollateral_), bucketLP_); } } diff --git a/src/libraries/internal/Deposits.sol b/src/libraries/internal/Deposits.sol index 8003f6eeb..382121597 100644 --- a/src/libraries/internal/Deposits.sol +++ b/src/libraries/internal/Deposits.sol @@ -11,15 +11,15 @@ import { Maths } from './Maths.sol'; /** @title Deposits library @notice Internal library containing common logic for deposits management. - @dev Implemented as Fenwick Tree data structure. + @dev Implemented as `Fenwick Tree` data structure. */ library Deposits { - // Max index supported in the Fenwick tree + /// @dev Max index supported in the `Fenwick` tree uint256 internal constant SIZE = 8192; /** - * @notice increase a value in the FenwickTree at an index. + * @notice Increase a value in the FenwickTree at an index. * @dev Starts at leaf/target and moved up towards root * @param index_ The deposit index. * @param unscaledAddAmount_ The unscaled amount to increase deposit by. @@ -64,11 +64,11 @@ library Deposits { /** * @notice Finds index and sum of first bucket that EXCEEDS the given sum - * @dev Used in lup calculation + * @dev Used in `LUP` calculation * @param targetSum_ The sum to find index for. - * @return sumIndex_ Smallest index where prefixsum greater than the sum - * @return sumIndexSum_ Sum at index PRECEDING sumIndex_ - * @return sumIndexScale_ Scale of bucket PRECEDING sumIndex_ + * @return sumIndex_ Smallest index where prefixsum greater than the sum. + * @return sumIndexSum_ Sum at index PRECEDING `sumIndex_`. + * @return sumIndexScale_ Scale of bucket PRECEDING `sumIndex_`. */ function findIndexAndSumOfSum( DepositsState storage deposits_, @@ -114,10 +114,10 @@ library Deposits { } /** - * @notice Finds index of passed sum. Helper function for findIndexAndSumOfSum - * @dev Used in lup calculation + * @notice Finds index of passed sum. Helper function for `findIndexAndSumOfSum`. + * @dev Used in `LUP` calculation * @param sum_ The sum to find index for. - * @return sumIndex_ Smallest index where prefixsum greater than the sum + * @return sumIndex_ Smallest index where prefixsum greater than the sum. */ function findIndexOfSum( DepositsState storage deposits_, @@ -127,9 +127,9 @@ library Deposits { } /** - * @notice Get least significant bit (LSB) of intiger, i_. + * @notice Get least significant bit (`LSB`) of integer `i_`. * @dev Used primarily to decrement the binary index in loops, iterating over range parents. - * @param i_ The integer with which to return the LSB. + * @param i_ The integer with which to return the `LSB`. */ function lsb( uint256 i_ @@ -142,7 +142,7 @@ library Deposits { /** * @notice Scale values in the tree from the index provided, upwards. - * @dev Starts at passed in node and increments through range parent nodes, and ends at 8192. + * @dev Starts at passed in node and increments through range parent nodes, and ends at `8192`. * @param index_ The index to start scaling from. * @param factor_ The factor to scale the values by. */ @@ -210,7 +210,7 @@ library Deposits { /** * @notice Get prefix sum of all indexes from provided index downwards. - * @dev Starts at tree root and decrements through range parent nodes summing from index i_'s range to index 0. + * @dev Starts at tree root and decrements through range parent nodes summing from index `i_`'s range to index `0`. * @param sumIndex_ The index to receive the prefix sum. * @param sum_ The prefix sum from current index downwards. */ @@ -257,10 +257,10 @@ library Deposits { } /** - * @notice Decrease a node in the FenwickTree at an index. - * @dev Starts at leaf/target and moved up towards root - * @param index_ The deposit index. - * @param unscaledRemoveAmount_ Unscaled amount to decrease deposit by. + * @notice Decrease a node in the `FenwickTree` at an index. + * @dev Starts at leaf/target and moved up towards root. + * @param index_ The deposit index. + * @param unscaledRemoveAmount_ Unscaled amount to decrease deposit by. */ function unscaledRemove( DepositsState storage deposits_, @@ -293,7 +293,7 @@ library Deposits { /** * @notice Scale tree starting from given index. - * @dev Starts at leaf/target and moved up towards root + * @dev Starts at leaf/target and moved up towards root. * @param index_ The deposit index. * @return scaled_ Scaled value. */ @@ -364,9 +364,9 @@ library Deposits { } /** - * @notice Returns LUP for a given debt value (capped at min bucket price). - * @param debt_ The debt amount to calculate LUP for. - * @return LUP for given debt. + * @notice Returns `LUP` for a given debt value (capped at min bucket price). + * @param debt_ The debt amount to calculate `LUP` for. + * @return `LUP` for given debt. */ function getLup( DepositsState storage deposits_, diff --git a/src/libraries/internal/Loans.sol b/src/libraries/internal/Loans.sol index ff1bf1200..97c6528e7 100644 --- a/src/libraries/internal/Loans.sol +++ b/src/libraries/internal/Loans.sol @@ -18,7 +18,11 @@ import { Maths } from './Maths.sol'; /** @title Loans library @notice Internal library containing common logic for loans management. - @dev Implemented as Max Heap data structure. + @dev The `Loans` heap is a `Max Heap` data structure (complete binary tree), the root node is the loan with the highest threshold price (`TP`) + at a given time. The heap is represented as an array, where the first element is a dummy element (`Loan(address(0), 0)`) and the first + value of the heap starts at index `1`, `ROOT_INDEX`. The threshold price of a loan's parent is always greater than or equal to the + threshold price of the loan. + @dev This code was modified from the following source: https://github.com/zmitton/eth-heap/blob/master/contracts/Heap.sol */ library Loans { @@ -37,34 +41,28 @@ library Loans { /** * @notice Initializes Loans Max Heap. - * @dev Organizes loans so Highest Threshold Price can be retreived easily. - * @param loans_ Holds Loan heap data. + * @dev Organizes loans so `Highest Threshold Price` can be retrieved easily. + * @param loans_ Holds Loan heap data. */ function init(LoansState storage loans_) internal { loans_.loans.push(Loan(address(0), 0)); } - /** - * The Loans heap is a Max Heap data structure (complete binary tree), the root node is the loan with the highest threshold price (TP) - * at a given time. The heap is represented as an array, where the first element is a dummy element (Loan(address(0), 0)) and the first - * value of the heap starts at index 1, ROOT_INDEX. The threshold price of a loan's parent is always greater than or equal to the - * threshold price of the loan. - * This code was modified from the following source: https://github.com/zmitton/eth-heap/blob/master/contracts/Heap.sol - */ - /***********************************/ /*** Loans Management Functions ***/ /***********************************/ /** - * @notice Updates a loan: updates heap (upsert if TP not 0, remove otherwise) and borrower balance. - * @dev write state: - * - _upsert: - * - insert or update loan in loans array - * - remove: - * - remove loan from loans array - * - update borrower in address => borrower mapping - * @param loans_ Holds loan heap data. + * @notice Updates a loan: updates heap (`upsert` if `TP` not `0`, `remove` otherwise) and borrower balance. + * @dev === Write state === + * @dev - `_upsert`: + * @dev insert or update loan in `loans` array + * @dev - `remove`: + * @dev remove loan from `loans` array + * @dev - update borrower in `address => borrower` mapping + * @param loans_ Holds loans heap data. + * @param auctions_ Struct for pool auctions state. + * @param deposits_ Struct for pool deposits state. * @param borrower_ Borrower struct with borrower details. * @param borrowerAddress_ Borrower's address to update. * @param poolDebt_ Pool's current debt. @@ -128,10 +126,10 @@ library Loans { /**************************************/ /** - * @notice Moves a Loan up the heap. - * @param loans_ Holds loan heap data. - * @param loan_ Loan to be moved. - * @param i_ Index for Loan to be moved to. + * @notice Moves a `Loan` up the heap. + * @param loans_ Holds loans heap data. + * @param loan_ `Loan` to be moved. + * @param i_ Index for `Loan` to be moved to. */ function _bubbleUp(LoansState storage loans_, Loan memory loan_, uint i_) private { uint256 count = loans_.loans.length; @@ -144,10 +142,10 @@ library Loans { } /** - * @notice Moves a Loan down the heap. - * @param loans_ Holds Loan heap data. - * @param loan_ Loan to be moved. - * @param i_ Index for Loan to be moved to. + * @notice Moves a `Loan` down the heap. + * @param loans_ Holds loans heap data. + * @param loan_ `Loan` to be moved. + * @param i_ Index for `Loan` to be moved to. */ function _bubbleDown(LoansState storage loans_, Loan memory loan_, uint i_) private { // Left child index. @@ -173,10 +171,10 @@ library Loans { } /** - * @notice Inserts a Loan in the heap. - * @param loans_ Holds loan heap data. - * @param loan_ Loan to be inserted. - * @param i_ index for Loan to be inserted at. + * @notice Inserts a `Loan` in the heap. + * @param loans_ Holds loans heap data. + * @param loan_ `Loan` to be inserted. + * @param i_ Index for `Loan` to be inserted at. */ function _insert(LoansState storage loans_, Loan memory loan_, uint i_, uint256 count_) private { if (i_ == count_) loans_.loans.push(loan_); @@ -186,10 +184,10 @@ library Loans { } /** - * @notice Removes loan from heap given borrower address. - * @param loans_ Holds loan heap data. - * @param borrower_ Borrower address whose loan is being updated or inserted. - * @param id_ Loan id. + * @notice Removes `Loan` from heap given borrower address. + * @param loans_ Holds loans heap data. + * @param borrower_ Borrower address whose `Loan` is being updated or inserted. + * @param id_ `Loan` id. */ function remove(LoansState storage loans_, address borrower_, uint256 id_) internal { delete loans_.indices[borrower_]; @@ -205,10 +203,10 @@ library Loans { /** * @notice Performs an insert or an update dependent on borrowers existance. - * @param loans_ Holds loan heap data. + * @param loans_ Holds loans heap data. * @param borrower_ Borrower address that is being updated or inserted. - * @param id_ Loan id. - * @param thresholdPrice_ Threshold Price that is updated or inserted. + * @param id_ `Loan` id. + * @param thresholdPrice_ `Threshold Price` that is updated or inserted. */ function _upsert( LoansState storage loans_, @@ -239,19 +237,19 @@ library Loans { /**********************/ /** - * @notice Retreives Loan by index, i_. - * @param loans_ Holds loan heap data. - * @param i_ Index to retreive Loan. - * @return Loan Loan retrieved by index. + * @notice Retreives `Loan` by index, `i_`. + * @param loans_ Holds loans heap data. + * @param i_ Index to retrieve `Loan`. + * @return `Loan` retrieved by index. */ function getByIndex(LoansState storage loans_, uint256 i_) internal view returns(Loan memory) { return loans_.loans.length > i_ ? loans_.loans[i_] : Loan(address(0), 0); } /** - * @notice Retreives Loan with the highest threshold price value. - * @param loans_ Holds loan heap data. - * @return Loan Max Loan in the Heap. + * @notice Retreives `Loan` with the highest threshold price value. + * @param loans_ Holds loans heap data. + * @return `Max Loan` in the heap. */ function getMax(LoansState storage loans_) internal view returns(Loan memory) { return getByIndex(loans_, ROOT_INDEX); @@ -259,8 +257,8 @@ library Loans { /** * @notice Returns number of loans in pool. - * @param loans_ Holds loan heap data. - * @return number of loans in pool. + * @param loans_ Holds loans heap data. + * @return umber of loans in pool. */ function noOfLoans(LoansState storage loans_) internal view returns (uint256) { return loans_.loans.length - 1; From 0f5ec56d4522970093873d0c80f54a0174babe4b Mon Sep 17 00:00:00 2001 From: grandizzy Date: Tue, 18 Apr 2023 21:03:00 +0300 Subject: [PATCH 04/11] If and for consistent style --- src/PoolInfoUtils.sol | 2 +- src/base/Pool.sol | 4 ++-- src/libraries/external/SettlerActions.sol | 4 ++-- src/libraries/internal/Deposits.sol | 2 +- .../ERC20Pool/handlers/BasicERC20PoolHandler.sol | 2 +- .../ERC721Pool/BasicERC721PoolInvariants.t.sol | 2 +- .../ERC721Pool/handlers/BasicERC721PoolHandler.sol | 2 +- .../unbounded/UnboundedBasicERC721PoolHandler.sol | 6 +++--- tests/forge/invariants/base/BasicInvariants.t.sol | 4 ++-- .../invariants/base/handlers/BasicPoolHandler.sol | 2 +- .../base/handlers/LiquidationPoolHandler.sol | 2 +- tests/forge/unit/ERC20Pool/ERC20DSTestPlus.sol | 14 +++++++------- tests/forge/unit/ERC721Pool/ERC721DSTestPlus.sol | 2 +- tests/forge/unit/PositionManager.t.sol | 6 +++--- tests/forge/unit/Rewards/RewardsDSTestPlus.sol | 8 ++++---- tests/forge/unit/Rewards/RewardsManager.t.sol | 8 ++++---- tests/forge/utils/DSTestPlus.sol | 8 ++++---- 17 files changed, 39 insertions(+), 39 deletions(-) diff --git a/src/PoolInfoUtils.sol b/src/PoolInfoUtils.sol index 96f0f80ec..eff048ebc 100644 --- a/src/PoolInfoUtils.sol +++ b/src/PoolInfoUtils.sol @@ -224,7 +224,7 @@ contract PoolInfoUtils { (uint256 bondEscrowed, uint256 unclaimedReserve, uint256 auctionKickTime, ) = pool.reservesInfo(); // due to rounding issues, especially in Auction.settle, this can be slighly negative - if( poolDebt + quoteTokenBalance >= poolSize + bondEscrowed + unclaimedReserve) { + if ( poolDebt + quoteTokenBalance >= poolSize + bondEscrowed + unclaimedReserve) { reserves_ = poolDebt + quoteTokenBalance - poolSize - bondEscrowed - unclaimedReserve; } diff --git a/src/base/Pool.sol b/src/base/Pool.sol index c31728bc2..60956e0e2 100644 --- a/src/base/Pool.sol +++ b/src/base/Pool.sol @@ -309,7 +309,7 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { poolState.t0Debt = result.t0PoolDebt; _updateInterestState(poolState, result.lup); - if(result.amountToCoverBond != 0) _transferQuoteTokenFrom(msg.sender, result.amountToCoverBond); + if (result.amountToCoverBond != 0) _transferQuoteTokenFrom(msg.sender, result.amountToCoverBond); } /** @@ -352,7 +352,7 @@ abstract contract Pool is Clone, ReentrancyGuard, Multicall, IPool { _updateInterestState(poolState, result.lup); // transfer from kicker to pool the difference to cover bond - if(result.amountToCoverBond != 0) _transferQuoteTokenFrom(msg.sender, result.amountToCoverBond); + if (result.amountToCoverBond != 0) _transferQuoteTokenFrom(msg.sender, result.amountToCoverBond); } /** diff --git a/src/libraries/external/SettlerActions.sol b/src/libraries/external/SettlerActions.sol index ff1f2acb7..2e262de00 100644 --- a/src/libraries/external/SettlerActions.sol +++ b/src/libraries/external/SettlerActions.sol @@ -381,12 +381,12 @@ library SettlerActions { auctions_.head = address(0); auctions_.tail = address(0); } - else if(auctions_.head == borrower_) { + else if (auctions_.head == borrower_) { // liquidation is the head auctions_.liquidations[liquidation.next].prev = address(0); auctions_.head = liquidation.next; } - else if(auctions_.tail == borrower_) { + else if (auctions_.tail == borrower_) { // liquidation is the tail auctions_.liquidations[liquidation.prev].next = address(0); auctions_.tail = liquidation.prev; diff --git a/src/libraries/internal/Deposits.sol b/src/libraries/internal/Deposits.sol index 382121597..af69d4c3b 100644 --- a/src/libraries/internal/Deposits.sol +++ b/src/libraries/internal/Deposits.sol @@ -168,7 +168,7 @@ library Deposits { // subtree what was scaled earlier. Therefore: we need to increment it's stored value // (in sum) which was set in a prior interation in case 1. while (bit <= SIZE) { - if((bit & index_) != 0) { + if ((bit & index_) != 0) { // Case 1 as described above value = deposits_.values[index_]; scaling = deposits_.scaling[index_]; diff --git a/tests/forge/invariants/ERC20Pool/handlers/BasicERC20PoolHandler.sol b/tests/forge/invariants/ERC20Pool/handlers/BasicERC20PoolHandler.sol index 63fd35a17..3cb90041d 100644 --- a/tests/forge/invariants/ERC20Pool/handlers/BasicERC20PoolHandler.sol +++ b/tests/forge/invariants/ERC20Pool/handlers/BasicERC20PoolHandler.sol @@ -143,7 +143,7 @@ contract BasicERC20PoolHandler is UnboundedBasicERC20PoolHandler, BasicPoolHandl // ensure actor has collateral to remove (uint256 lpBalanceBefore, ) = _pool.lenderInfo(_lenderBucketIndex, _actor); - if(lpBalanceBefore == 0) _addCollateral(boundedAmount_, _lenderBucketIndex); + if (lpBalanceBefore == 0) _addCollateral(boundedAmount_, _lenderBucketIndex); } function _prePledgeCollateral( diff --git a/tests/forge/invariants/ERC721Pool/BasicERC721PoolInvariants.t.sol b/tests/forge/invariants/ERC721Pool/BasicERC721PoolInvariants.t.sol index 129dcb47e..c57141ec6 100644 --- a/tests/forge/invariants/ERC721Pool/BasicERC721PoolInvariants.t.sol +++ b/tests/forge/invariants/ERC721Pool/BasicERC721PoolInvariants.t.sol @@ -90,7 +90,7 @@ contract BasicERC721PoolInvariants is BasicInvariants { uint256 collateral; uint256[] memory collateralBuckets = IBaseHandler(_handler).getCollateralBuckets(); - for(uint256 i = 0; i < collateralBuckets.length; i++) { + for (uint256 i = 0; i < collateralBuckets.length; i++) { uint256 bucketIndex = collateralBuckets[i]; (, collateral, , , ) = _erc721pool.bucketInfo(bucketIndex); bucketCollateral += collateral; diff --git a/tests/forge/invariants/ERC721Pool/handlers/BasicERC721PoolHandler.sol b/tests/forge/invariants/ERC721Pool/handlers/BasicERC721PoolHandler.sol index 3b9153003..d3286f13d 100644 --- a/tests/forge/invariants/ERC721Pool/handlers/BasicERC721PoolHandler.sol +++ b/tests/forge/invariants/ERC721Pool/handlers/BasicERC721PoolHandler.sol @@ -144,7 +144,7 @@ contract BasicERC721PoolHandler is UnboundedBasicERC721PoolHandler, BasicPoolHan // ensure actor has collateral to remove (uint256 lpBalanceBefore, ) = _pool.lenderInfo(_lenderBucketIndex, _actor); - if(lpBalanceBefore == 0) _addCollateral(boundedAmount_, _lenderBucketIndex); + if (lpBalanceBefore == 0) _addCollateral(boundedAmount_, _lenderBucketIndex); } function _prePledgeCollateral( diff --git a/tests/forge/invariants/ERC721Pool/handlers/unbounded/UnboundedBasicERC721PoolHandler.sol b/tests/forge/invariants/ERC721Pool/handlers/unbounded/UnboundedBasicERC721PoolHandler.sol index 97c39bd95..227391879 100644 --- a/tests/forge/invariants/ERC721Pool/handlers/unbounded/UnboundedBasicERC721PoolHandler.sol +++ b/tests/forge/invariants/ERC721Pool/handlers/unbounded/UnboundedBasicERC721PoolHandler.sol @@ -43,7 +43,7 @@ abstract contract UnboundedBasicERC721PoolHandler is UnboundedBasicPoolHandler, _collateral.mint(_actor, amount_); _collateral.setApprovalForAll(address(_pool), true); uint256[] memory tokenIds = new uint256[](amount_); - for(uint256 i = 0; i < amount_; i++) { + for (uint256 i = 0; i < amount_; i++) { tokenIds[i] = _collateral.tokenOfOwnerByIndex(_actor, i); } @@ -102,7 +102,7 @@ abstract contract UnboundedBasicERC721PoolHandler is UnboundedBasicPoolHandler, _collateral.mint(_actor, amount_); _collateral.setApprovalForAll(address(_pool), true); uint256[] memory tokenIds = new uint256[](amount_); - for(uint256 i = 0; i < amount_; i++) { + for (uint256 i = 0; i < amount_; i++) { tokenIds[i] = _collateral.tokenOfOwnerByIndex(_actor, i); } @@ -161,7 +161,7 @@ abstract contract UnboundedBasicERC721PoolHandler is UnboundedBasicPoolHandler, _collateral.mint(_actor, collateralToPledge); _collateral.setApprovalForAll(address(_pool), true); uint256[] memory tokenIds = new uint256[](collateralToPledge); - for(uint256 i = 0; i < collateralToPledge; i++) { + for (uint256 i = 0; i < collateralToPledge; i++) { tokenIds[i] = _collateral.tokenOfOwnerByIndex(_actor, i); } diff --git a/tests/forge/invariants/base/BasicInvariants.t.sol b/tests/forge/invariants/base/BasicInvariants.t.sol index ae714fa34..064416b10 100644 --- a/tests/forge/invariants/base/BasicInvariants.t.sol +++ b/tests/forge/invariants/base/BasicInvariants.t.sol @@ -245,7 +245,7 @@ abstract contract BasicInvariants is BaseInvariants { } uint256 poolT0Debt = _pool.totalT0Debt(); - if(poolT0Debt == 0) require(currentInflator == 1e18, "Incorrect inflator update"); + if (poolT0Debt == 0) require(currentInflator == 1e18, "Incorrect inflator update"); previousInflator = currentInflator; previousInflatorUpdate = currentInflatorUpdate; @@ -336,7 +336,7 @@ abstract contract BasicInvariants is BaseInvariants { uint256 nextNonzeroBucket = _pool.depositIndex(_pool.depositUpToIndex(bucketIndex)+1); console.log("bucketIndex: ", bucketIndex); console.log("Next nonzero bucket: ", nextNonzeroBucket); - for(uint256 j = bucketIndex + 1; j < nextNonzeroBucket && j < LENDER_MAX_BUCKET_INDEX; j++) { + for (uint256 j = bucketIndex + 1; j < nextNonzeroBucket && j < LENDER_MAX_BUCKET_INDEX; j++) { (, , , uint256 depositAtJ, ) = _pool.bucketInfo(j); console.log("Deposit at %s is %s", j, depositAtJ); require( diff --git a/tests/forge/invariants/base/handlers/BasicPoolHandler.sol b/tests/forge/invariants/base/handlers/BasicPoolHandler.sol index 133178ed5..e19d14fee 100644 --- a/tests/forge/invariants/base/handlers/BasicPoolHandler.sol +++ b/tests/forge/invariants/base/handlers/BasicPoolHandler.sol @@ -125,7 +125,7 @@ abstract contract BasicPoolHandler is UnboundedBasicPoolHandler { ) internal returns (address receiver_, uint256 boundedLps_) { // ensure actor has LP to transfer (uint256 senderLpBalance, ) = _pool.lenderInfo(_lenderBucketIndex, _actor); - if(senderLpBalance == 0) _addQuoteToken(1e24, _lenderBucketIndex); + if (senderLpBalance == 0) _addQuoteToken(1e24, _lenderBucketIndex); (senderLpBalance, ) = _pool.lenderInfo(_lenderBucketIndex, _actor); diff --git a/tests/forge/invariants/base/handlers/LiquidationPoolHandler.sol b/tests/forge/invariants/base/handlers/LiquidationPoolHandler.sol index ba80bd9da..800244f51 100644 --- a/tests/forge/invariants/base/handlers/LiquidationPoolHandler.sol +++ b/tests/forge/invariants/base/handlers/LiquidationPoolHandler.sol @@ -159,7 +159,7 @@ abstract contract LiquidationPoolHandler is UnboundedLiquidationPoolHandler, Bas // Action phase _actor = kicker; - if(!borrowerKicked) _kickAuction(borrower_); + if (!borrowerKicked) _kickAuction(borrower_); } function _constrictTakeAmount(uint256 amountToTake_) internal view virtual returns(uint256 boundedAmount_); diff --git a/tests/forge/unit/ERC20Pool/ERC20DSTestPlus.sol b/tests/forge/unit/ERC20Pool/ERC20DSTestPlus.sol index c6a392f7d..ce523bfc5 100644 --- a/tests/forge/unit/ERC20Pool/ERC20DSTestPlus.sol +++ b/tests/forge/unit/ERC20Pool/ERC20DSTestPlus.sol @@ -80,13 +80,13 @@ abstract contract ERC20DSTestPlus is DSTestPlus, IERC20PoolEvents { uint256 lpRedeemed; // redeem LP for quote token if available - if(lenderLpBalance != 0 && bucketQuote != 0) { + if (lenderLpBalance != 0 && bucketQuote != 0) { (, lpRedeemed) = _pool.removeQuoteToken(type(uint256).max, bucketIndex); lenderLpBalance -= lpRedeemed; } // redeem LP for collateral if available - if(lenderLpBalance != 0 && bucketCollateral != 0) { + if (lenderLpBalance != 0 && bucketCollateral != 0) { (, lpRedeemed) = ERC20Pool(address(_pool)).removeCollateral(type(uint256).max, bucketIndex); lenderLpBalance -= lpRedeemed; } @@ -108,7 +108,7 @@ abstract contract ERC20DSTestPlus is DSTestPlus, IERC20PoolEvents { } uint256 pledgedCollateral = 0; - for(uint i = 0; i < borrowers.length(); i++) { + for (uint i = 0; i < borrowers.length(); i++) { (, uint256 collateral,) = _poolUtils.borrowerInfo(address(_pool), borrowers.at(i)); pledgedCollateral += collateral; } @@ -143,11 +143,11 @@ abstract contract ERC20DSTestPlus is DSTestPlus, IERC20PoolEvents { _; validateCollateral(bucketsUsed, borrowers); - for(uint i = 0; i < borrowers.length(); i++) { + for (uint i = 0; i < borrowers.length(); i++) { repayDebt(borrowers.at(i)); } - for(uint i = 0; i < lenders.length(); i++) { + for (uint i = 0; i < lenders.length(); i++) { redeemLendersLp(lenders.at(i), lendersDepositedIndex[lenders.at(i)]); } @@ -420,8 +420,8 @@ abstract contract ERC20DSTestPlus is DSTestPlus, IERC20PoolEvents { emit TransferLP(from, to, indexes, lpBalance); _pool.transferLP(from, to, indexes); - for(uint256 i = 0; i < indexes.length ;i++ ){ - if(lenders.contains(from)){ + for (uint256 i = 0; i < indexes.length ;i++ ){ + if (lenders.contains(from)){ lenders.add(to); lendersDepositedIndex[to].add(indexes[i]); } diff --git a/tests/forge/unit/ERC721Pool/ERC721DSTestPlus.sol b/tests/forge/unit/ERC721Pool/ERC721DSTestPlus.sol index b2e425ae9..dc44a3ffb 100644 --- a/tests/forge/unit/ERC721Pool/ERC721DSTestPlus.sol +++ b/tests/forge/unit/ERC721Pool/ERC721DSTestPlus.sol @@ -433,7 +433,7 @@ abstract contract ERC721DSTestPlus is DSTestPlus, IERC721PoolEvents { function _assertCollateralInvariants() internal { uint256 collateralInBuckets; - for(uint256 bucketIndex = 0; bucketIndex <= 7388; bucketIndex++) { + for (uint256 bucketIndex = 0; bucketIndex <= 7388; bucketIndex++) { (, uint256 bucketCollateral, , , ) = _pool.bucketInfo(bucketIndex); collateralInBuckets += bucketCollateral; } diff --git a/tests/forge/unit/PositionManager.t.sol b/tests/forge/unit/PositionManager.t.sol index a5c553905..b6d25ac21 100644 --- a/tests/forge/unit/PositionManager.t.sol +++ b/tests/forge/unit/PositionManager.t.sol @@ -2679,7 +2679,7 @@ contract PositionManagerERC20PoolTest is PositionManagerERC20PoolHelperContract tokenIds[1] = _mintNFT(alice, alice, address(_pool)); assertFalse(_positionManager.isIndexInPosition(tokenIds[1], 2550)); - for(uint256 i = 0; i < addresses.length; ++i) { + for (uint256 i = 0; i < addresses.length; ++i) { // construct memorialize params struct IPositionManagerOwnerActions.MemorializePositionsParams memory memorializeParams = IPositionManagerOwnerActions.MemorializePositionsParams( tokenIds[i], indexes @@ -2711,7 +2711,7 @@ contract PositionManagerERC20PoolTest is PositionManagerERC20PoolHelperContract assertEq(depositTime, aliceDepositTime + 1 hours); // both alice and bob redeem - for(uint256 i = 0; i < addresses.length; ++i) { + for (uint256 i = 0; i < addresses.length; ++i) { // construct memorialize params struct IPositionManagerOwnerActions.RedeemPositionsParams memory params = IPositionManagerOwnerActions.RedeemPositionsParams( tokenIds[i], address(_pool), indexes @@ -2731,7 +2731,7 @@ contract PositionManagerERC20PoolTest is PositionManagerERC20PoolHelperContract assertEq(depositTime, aliceDepositTime + 1 hours); // attempt to redeem again should fail - for(uint256 i = 0; i < addresses.length; ++i) { + for (uint256 i = 0; i < addresses.length; ++i) { // construct memorialize params struct IPositionManagerOwnerActions.RedeemPositionsParams memory params = IPositionManagerOwnerActions.RedeemPositionsParams( tokenIds[i], address(_pool), indexes diff --git a/tests/forge/unit/Rewards/RewardsDSTestPlus.sol b/tests/forge/unit/Rewards/RewardsDSTestPlus.sol index a54ae2526..93fe06234 100644 --- a/tests/forge/unit/Rewards/RewardsDSTestPlus.sol +++ b/tests/forge/unit/Rewards/RewardsDSTestPlus.sol @@ -96,7 +96,7 @@ abstract contract RewardsDSTestPlus is IRewardsManagerEvents, ERC20HelperContrac assertEq(PositionManager(address(_positionManager)).ownerOf(tokenId), owner); // invariant: all bucket snapshots are removed for the token id that was unstaken - for(uint256 bucketIndex = 0; bucketIndex <= 7388; bucketIndex++) { + for (uint256 bucketIndex = 0; bucketIndex <= 7388; bucketIndex++) { (uint256 lps, uint256 rate) = _rewardsManager.getBucketStateStakeInfo(tokenId, bucketIndex); assertEq(lps, 0); assertEq(rate, 0); @@ -484,12 +484,12 @@ abstract contract RewardsHelperContract is RewardsDSTestPlus { // Helper function that returns a random subset from array function _getRandomSubsetFromArray(uint256[] memory array) internal returns (uint256[] memory subsetArray) { uint256[] memory copyOfArray = new uint256[](array.length); - for(uint j = 0; j < copyOfArray.length; j++){ + for (uint j = 0; j < copyOfArray.length; j++){ copyOfArray[j] = array[j]; } uint256 randomNoOfNfts = randomInRange(1, copyOfArray.length); subsetArray = new uint256[](randomNoOfNfts); - for(uint256 i = 0; i < randomNoOfNfts; i++) { + for (uint256 i = 0; i < randomNoOfNfts; i++) { uint256 randomIndex = randomInRange(0, copyOfArray.length - i - 1); subsetArray[i] = copyOfArray[randomIndex]; copyOfArray[randomIndex] = copyOfArray[copyOfArray.length - i - 1]; @@ -499,7 +499,7 @@ abstract contract RewardsHelperContract is RewardsDSTestPlus { // Returns N addresses array function _getAddresses(uint256 noOfAddress) internal returns(address[] memory addresses_) { addresses_ = new address[](noOfAddress); - for(uint i = 0; i < noOfAddress; i++) { + for (uint i = 0; i < noOfAddress; i++) { addresses_[i] = makeAddr(string(abi.encodePacked("Minter", Strings.toString(i)))); } } diff --git a/tests/forge/unit/Rewards/RewardsManager.t.sol b/tests/forge/unit/Rewards/RewardsManager.t.sol index 191212bc0..2185f0f06 100644 --- a/tests/forge/unit/Rewards/RewardsManager.t.sol +++ b/tests/forge/unit/Rewards/RewardsManager.t.sol @@ -1802,7 +1802,7 @@ contract RewardsManagerTest is RewardsHelperContract { address[] memory minters = _getAddresses(deposits); // stake variable no of deposits - for(uint256 i = 0; i < deposits; ++i) { + for (uint256 i = 0; i < deposits; ++i) { tokenIds[i] = _mintAndMemorializePositionNFT({ indexes: depositIndexes, @@ -1816,12 +1816,12 @@ contract RewardsManagerTest is RewardsHelperContract { uint256 updaterBalance = _ajnaToken.balanceOf(_updater); - for(uint i = 0; i < deposits; i++) { + for (uint i = 0; i < deposits; i++) { minterToBalance[minters[i]] = _ajnaToken.balanceOf(minters[i]); } // start variable no of reserve Auctions and claim rewards for random tokenIds in each epoch - for(uint i = 0; i < reserveAuctions; ++i) { + for (uint i = 0; i < reserveAuctions; ++i) { uint256 limitIndex = _findSecondLowestIndexPrice(depositIndexes); // start and end new reserve auction @@ -1850,7 +1850,7 @@ contract RewardsManagerTest is RewardsHelperContract { // pick random NFTs from all NFTs to claim rewards uint256[] memory randomNfts = _getRandomSubsetFromArray(tokenIds); - for(uint j = 0; j < randomNfts.length; j++) { + for (uint j = 0; j < randomNfts.length; j++) { address minterAddress = tokenIdToMinter[randomNfts[j]]; changePrank(minterAddress); diff --git a/tests/forge/utils/DSTestPlus.sol b/tests/forge/utils/DSTestPlus.sol index ad24f0e89..1aab9bcae 100644 --- a/tests/forge/utils/DSTestPlus.sol +++ b/tests/forge/utils/DSTestPlus.sol @@ -246,7 +246,7 @@ abstract contract DSTestPlus is Test, IPoolEvents { changePrank(from); vm.expectEmit(true, true, false, true); emit Kick(borrower, debt, collateral, bond); - if(transferAmount != 0) _assertQuoteTokenTransferEvent(from, address(_pool), transferAmount); + if (transferAmount != 0) _assertQuoteTokenTransferEvent(from, address(_pool), transferAmount); _pool.kick(borrower, MAX_FENWICK_INDEX); } @@ -266,7 +266,7 @@ abstract contract DSTestPlus is Test, IPoolEvents { emit Kick(borrower, debt, collateral, bond); vm.expectEmit(true, true, false, true); emit RemoveQuoteToken(from, index, removedFromDeposit, removedFromDeposit, lup); - if(transferAmount != 0) _assertQuoteTokenTransferEvent(from, address(_pool), transferAmount); + if (transferAmount != 0) _assertQuoteTokenTransferEvent(from, address(_pool), transferAmount); _pool.kickWithDeposit(index, MAX_FENWICK_INDEX); } @@ -595,12 +595,12 @@ abstract contract DSTestPlus is Test, IPoolEvents { uint256 curLpBalance; // sum up LP across lenders - for(uint i = 0; i < lenders.length(); i++ ){ + for (uint i = 0; i < lenders.length(); i++ ){ (curLpBalance, ) = _pool.lenderInfo(index, lenders.at(i)); lenderLps += curLpBalance; } // handle borrowers awarded LP from liquidation - for(uint i = 0; i < borrowers.length(); i++ ){ + for (uint i = 0; i < borrowers.length(); i++ ){ address borrower = borrowers.at(i); if (!lenders.contains(borrower)) { (curLpBalance, ) = _pool.lenderInfo(index, borrowers.at(i)); From eecb253354473ab80957d099319aefdaac8e06c4 Mon Sep 17 00:00:00 2001 From: grandizzy Date: Tue, 18 Apr 2023 22:24:02 +0300 Subject: [PATCH 05/11] Rewards and Position manager forge doc --- src/PoolInfoUtils.sol | 144 +++++++++------ src/PositionManager.sol | 167 ++++++++++-------- src/RewardsManager.sol | 143 ++++++++------- .../position/IPositionManagerDerivedState.sol | 48 ++--- .../position/IPositionManagerErrors.sol | 12 +- .../position/IPositionManagerEvents.sol | 22 +-- .../position/IPositionManagerOwnerActions.sol | 42 ++--- .../position/IPositionManagerState.sol | 9 +- .../rewards/IRewardsManagerDerivedState.sol | 12 +- .../rewards/IRewardsManagerErrors.sol | 4 +- .../rewards/IRewardsManagerEvents.sol | 34 ++-- .../rewards/IRewardsManagerOwnerActions.sol | 48 ++--- .../rewards/IRewardsManagerState.sol | 46 ++--- 13 files changed, 398 insertions(+), 333 deletions(-) diff --git a/src/PoolInfoUtils.sol b/src/PoolInfoUtils.sol index eff048ebc..f87e39e90 100644 --- a/src/PoolInfoUtils.sol +++ b/src/PoolInfoUtils.sol @@ -27,20 +27,21 @@ import { PoolCommons } from './libraries/external/PoolCommons.sol'; /** * @title Pool Info Utils contract - * @notice Contract for providing pools information for any deployed pool. - * @dev Pool info is calculated using same helper functions / logic as in Pool contracts. + * @notice Contract for providing information for any deployed pool. + * @dev Pool info is calculated using same helper functions / logic as in `Pool` contracts. */ contract PoolInfoUtils { /** - * @notice Exposes status of a liquidation auction - * @param borrower_ Identifies the loan being liquidated - * @return kickTime_ Time auction was kicked, implying end time - * @return collateral_ Remaining collateral available to be purchased (WAD) - * @return debtToCover_ Borrower debt to be covered (WAD) - * @return isCollateralized_ If true, takes will revert - * @return price_ Current price of the auction (WAD) - * @return neutralPrice_ Price at which bond holder is neither rewarded nor penalized (WAD) + * @notice Exposes status of a liquidation auction. + * @param ajnaPool_ Address of `Ajna` pool. + * @param borrower_ Identifies the loan being liquidated. + * @return kickTime_ Time auction was kicked, implying end time. + * @return collateral_ Remaining collateral available to be purchased. (`WAD`) + * @return debtToCover_ Borrower debt to be covered. (`WAD`) + * @return isCollateralized_ `True` if loan is collateralized. + * @return price_ Current price of the auction. (`WAD`) + * @return neutralPrice_ Price at which bond holder is neither rewarded nor penalized. (`WAD`) */ function auctionStatus(address ajnaPool_, address borrower_) external @@ -68,13 +69,21 @@ contract PoolInfoUtils { } } + /** + * @notice Retrieves info of a given borrower in a given `Ajna` pool. + * @param ajnaPool_ Address of `Ajna` pool. + * @param borrower_ Borrower's address. + * @return debt_ Current debt owed by borrower (`WAD`). + * @return collateral_ Pledged collateral, including encumbered (`WAD`). + * @return t0Np_ `Neutral price` (`WAD`). + */ function borrowerInfo(address ajnaPool_, address borrower_) external view returns ( - uint256 debt_, // current debt owed by borrower (WAD) - uint256 collateral_, // deposited collateral including encumbered (WAD) - uint256 t0Np_ // Np / inflator, used in neutralPrice calc (WAD) + uint256 debt_, + uint256 collateral_, + uint256 t0Np_ ) { IPool pool = IPool(ajnaPool_); @@ -96,13 +105,14 @@ contract PoolInfoUtils { /** * @notice Get a bucket struct for a given index. + * @param ajnaPool_ Address of `Ajna` pool. * @param index_ The index of the bucket to retrieve. - * @return price_ Bucket price (WAD) - * @return quoteTokens_ Amount of quote token in bucket, deposit + interest (WAD) - * @return collateral_ Unencumbered collateral in bucket (WAD). - * @return bucketLPs_ Outstanding LP balance in bucket (WAD) - * @return scale_ Lender interest multiplier (WAD). - * @return exchangeRate_ The exchange rate of the bucket, in WAD units. + * @return price_ Bucket's price (`WAD`). + * @return quoteTokens_ Amount of quote token in bucket, `deposit + interest` (`WAD`). + * @return collateral_ Unencumbered collateral in bucket (`WAD`). + * @return bucketLP_ Outstanding `LP` balance in bucket (`WAD`). + * @return scale_ Lender interest multiplier (`WAD`). + * @return exchangeRate_ The exchange rate of the bucket, in `WAD` units. */ function bucketInfo(address ajnaPool_, uint256 index_) external @@ -111,7 +121,7 @@ contract PoolInfoUtils { uint256 price_, uint256 quoteTokens_, uint256 collateral_, - uint256 bucketLPs_, + uint256 bucketLP_, uint256 scale_, uint256 exchangeRate_ ) @@ -120,15 +130,16 @@ contract PoolInfoUtils { price_ = _priceAt(index_); - (bucketLPs_, collateral_, , quoteTokens_, scale_) = pool.bucketInfo(index_); - exchangeRate_ = Buckets.getExchangeRate(collateral_, bucketLPs_, quoteTokens_, price_); + (bucketLP_, collateral_, , quoteTokens_, scale_) = pool.bucketInfo(index_); + exchangeRate_ = Buckets.getExchangeRate(collateral_, bucketLP_, quoteTokens_, price_); } /** * @notice Returns info related to pool loans. - * @return poolSize_ The total amount of quote tokens in pool (WAD). + * @param ajnaPool_ Address of `Ajna` pool. + * @return poolSize_ The total amount of quote tokens in pool (`WAD`). * @return loansCount_ The number of loans in pool. - * @return maxBorrower_ The address with the highest TP in pool. + * @return maxBorrower_ The address with the highest `TP` in pool. * @return pendingInflator_ Pending inflator in pool. * @return pendingInterestFactor_ Factor used to scale the inflator. */ @@ -161,12 +172,13 @@ contract PoolInfoUtils { /** * @notice Returns info related to pool prices. - * @return hpb_ The price value of the current Highest Price Bucket (HPB), in WAD units. - * @return hpbIndex_ The index of the current Highest Price Bucket (HPB), in WAD units. - * @return htp_ The price value of the current Highest Threshold Price (HTP) bucket, in WAD units. - * @return htpIndex_ The index of the current Highest Threshold Price (HTP) bucket, in WAD units. - * @return lup_ The price value of the current Lowest Utilized Price (LUP) bucket, in WAD units. - * @return lupIndex_ The index of the current Lowest Utilized Price (LUP) bucket, in WAD units. + * @param ajnaPool_ Address of `Ajna` pool. + * @return hpb_ The price value of the current `Highest Price Bucket` (`HPB`), in `WAD` units. + * @return hpbIndex_ The index of the current `Highest Price Bucket` (`HPB`), in `WAD` units. + * @return htp_ The price value of the current `Highest Threshold Price` (`HTP`) bucket, in `WAD` units. + * @return htpIndex_ The index of the current `Highest Threshold Price` (`HTP`) bucket, in `WAD` units. + * @return lup_ The price value of the current `Lowest Utilized Price` (LUP) bucket, in `WAD` units. + * @return lupIndex_ The index of the current `Lowest Utilized Price` (`LUP`) bucket, in `WAD` units. */ function poolPricesInfo(address ajnaPool_) external @@ -196,11 +208,12 @@ contract PoolInfoUtils { } /** - * @notice Returns info related to Claimaible Reserve Auction. + * @notice Returns info related to `Claimaible Reserve Auction`. + * @param ajnaPool_ Address of `Ajna` pool. * @return reserves_ The amount of excess quote tokens. - * @return claimableReserves_ Denominated in quote token, or 0 if no reserves can be auctioned. + * @return claimableReserves_ Denominated in quote token, or `0` if no reserves can be auctioned. * @return claimableReservesRemaining_ Amount of claimable reserves which has not yet been taken. - * @return auctionPrice_ Current price at which 1 quote token may be purchased, denominated in Ajna. + * @return auctionPrice_ Current price at which `1` quote token may be purchased, denominated in `Ajna`. * @return timeRemaining_ Seconds remaining before takes are no longer allowed. */ function poolReservesInfo(address ajnaPool_) @@ -242,11 +255,12 @@ contract PoolInfoUtils { } /** - * @notice Returns info related to Claimaible Reserve Auction. + * @notice Returns info related to pool utilization. + * @param ajnaPool_ Address of `Ajna` pool. * @return poolMinDebtAmount_ Minimum debt amount. * @return poolCollateralization_ Current pool collateralization ratio. - * @return poolActualUtilization_ The current pool actual utilization, in WAD units. - * @return poolTargetUtilization_ The current pool Target utilization, in WAD units. + * @return poolActualUtilization_ The current pool actual utilization, in `WAD` units. + * @return poolTargetUtilization_ The current pool Target utilization, in `WAD` units. */ function poolUtilizationInfo(address ajnaPool_) external @@ -278,6 +292,8 @@ contract PoolInfoUtils { /** * @notice Returns the proportion of interest rate which is awarded to lenders; * the remainder accumulates in reserves. + * @param ajnaPool_ Address of `Ajna` pool. + * @return lenderInterestMargin_ Lender interest margin in pool. */ function lenderInterestMargin(address ajnaPool_) external @@ -291,6 +307,9 @@ contract PoolInfoUtils { lenderInterestMargin_ = PoolCommons.lenderInterestMargin(utilization); } + /** + * @notice Returns bucket price for a given bucket index. + */ function indexToPrice( uint256 index_ ) external pure returns (uint256) @@ -298,6 +317,9 @@ contract PoolInfoUtils { return _priceAt(index_); } + /** + * @notice Returns bucket index for a given bucket price. + */ function priceToIndex( uint256 price_ ) external pure returns (uint256) @@ -305,6 +327,9 @@ contract PoolInfoUtils { return _indexOf(price_); } + /** + * @notice Returns current `LUP` for a given pool. + */ function lup( address ajnaPool_ ) external view returns (uint256) { @@ -316,6 +341,9 @@ contract PoolInfoUtils { return _priceAt(currentLupIndex); } + /** + * @notice Returns current `LUP` index for a given pool. + */ function lupIndex( address ajnaPool_ ) external view returns (uint256) { @@ -326,6 +354,9 @@ contract PoolInfoUtils { return pool.depositIndex(debt); } + /** + * @notice Returns current `HPB` for a given pool. + */ function hpb( address ajnaPool_ ) external view returns (uint256) { @@ -336,6 +367,9 @@ contract PoolInfoUtils { return _priceAt(hbpIndex); } + /** + * @notice Returns current `HPB` index for a given pool. + */ function hpbIndex( address ajnaPool_ ) external view returns (uint256) { @@ -344,12 +378,18 @@ contract PoolInfoUtils { return pool.depositIndex(1); } + /** + * @notice Returns current `HTP` for a given pool. + */ function htp( address ajnaPool_ ) external view returns (uint256 htp_) { (, htp_, ) = IPool(ajnaPool_).loansInfo(); } + /** + * @notice Returns current `MOMP` for a given pool. + */ function momp( address ajnaPool_ ) external view returns (uint256) { @@ -369,7 +409,7 @@ contract PoolInfoUtils { /** * @notice Calculates origination fee rate for a pool. - * @notice Calculated as greater of the current annualized interest rate divided by 52 (one week of interest) or 5 bps. + * @notice Calculated as greater of the current annualized interest rate divided by `52` (one week of interest) or `5` bps. * @return Fee rate calculated from the pool interest rate. */ function borrowFeeRate( @@ -381,7 +421,7 @@ contract PoolInfoUtils { /** * @notice Calculates unutilized deposit fee rate for a pool. - * @notice Calculated as current annualized rate divided by 365 (24 hours of interest). + * @notice Calculated as current annualized rate divided by `365` (`24` hours of interest). * @return Fee rate calculated from the pool interest rate. */ function unutilizedDepositFeeRate( @@ -392,14 +432,14 @@ contract PoolInfoUtils { } /** - * @notice Calculate the amount of quote tokens in bucket for a given amount of LP. - * @param lps_ The number of LP to calculate amounts for. + * @notice Calculate the amount of quote tokens in bucket for a given amount of `LP`. + * @param lp_ The number of `LP` to calculate amounts for. * @param index_ The price bucket index for which the value should be calculated. - * @return quoteAmount_ The exact amount of quote tokens that can be exchanged for the given LP, WAD units. + * @return quoteAmount_ The exact amount of quote tokens that can be exchanged for the given `LP`, `WAD` units. */ function lpToQuoteTokens( address ajnaPool_, - uint256 lps_, + uint256 lp_, uint256 index_ ) external view returns (uint256 quoteAmount_) { IPool pool = IPool(ajnaPool_); @@ -408,21 +448,21 @@ contract PoolInfoUtils { bucketLPs_, bucketCollateral, bucketDeposit, - lps_, + lp_, bucketDeposit, _priceAt(index_) ); } /** - * @notice Calculate the amount of collateral tokens in bucket for a given amount of LP. - * @param lps_ The number of LP to calculate amounts for. + * @notice Calculate the amount of collateral tokens in bucket for a given amount of `LP`. + * @param lp_ The number of `LP` to calculate amounts for. * @param index_ The price bucket index for which the value should be calculated. - * @return collateralAmount_ The exact amount of collateral tokens that can be exchanged for the given LP, WAD units. + * @return collateralAmount_ The exact amount of collateral tokens that can be exchanged for the given `LP`, `WAD` units. */ function lpToCollateral( address ajnaPool_, - uint256 lps_, + uint256 lp_, uint256 index_ ) external view returns (uint256 collateralAmount_) { IPool pool = IPool(ajnaPool_); @@ -431,7 +471,7 @@ contract PoolInfoUtils { bucketCollateral, bucketLPs_, bucketDeposit, - lps_, + lp_, _priceAt(index_) ); } @@ -459,7 +499,7 @@ contract PoolInfoUtils { * @param debt_ The debt amount. * @param collateral_ The collateral amount. * @param price_ The price to calculate collateralization at. - * @return Collateralization value. 1**18 if debt amount is 0. + * @return Collateralization value. `1 WAD` if debt amount is `0`. */ function _collateralization( uint256 debt_, @@ -471,9 +511,9 @@ contract PoolInfoUtils { } /** - * @notice Calculates target utilization for given EMA values. - * @param debtColEma_ The EMA of debt squared to collateral. - * @param lupt0DebtEma_ The EMA of LUP * t0 debt. + * @notice Calculates target utilization for given `EMA` values. + * @param debtColEma_ The `EMA` of debt squared to collateral. + * @param lupt0DebtEma_ The `EMA` of `LUP * t0 debt`. * @return Target utilization of the pool. */ function _targetUtilization( diff --git a/src/PositionManager.sol b/src/PositionManager.sol index 19f07702f..9eae95ac5 100644 --- a/src/PositionManager.sol +++ b/src/PositionManager.sol @@ -31,13 +31,13 @@ import { PositionNFTSVG } from './libraries/external/PositionNFTSVG.sol'; /** * @title Position Manager Contract - * @notice Used by Pool lenders to optionally mint NFT that represents their positions. - * Lenders can: - * - mint positions NFT token for a specific pool - * - memorialize positions for given buckets - * - move liquidity in pool - * - redeem positions for given buckets - * - burn positions NFT + * @notice Used by Pool lenders to optionally mint `NFT` that represents their positions. + * `Lenders` can: + * - `mint` positions `NFT` token for a specific pool + * - `memorialize` positions for given buckets + * - `move liquidity` in pool + * - `redeem` positions for given buckets + * - `burn` positions `NFT` */ contract PositionManager is ERC721, PermitERC721, IPositionManager, Multicall, ReentrancyGuard { @@ -48,25 +48,33 @@ contract PositionManager is ERC721, PermitERC721, IPositionManager, Multicall, R /*** State Variables ***/ /***********************/ - mapping(uint256 => address) public override poolKey; // token id => ajna pool address for which token was minted + /// @dev Mapping of `token id => ajna pool address` for which token was minted. + mapping(uint256 => address) public override poolKey; - mapping(uint256 => mapping(uint256 => Position)) internal positions; // token id => bucket index => Position struct - mapping(uint256 => uint96) internal nonces; // token id => nonce value used for permit - mapping(uint256 => EnumerableSet.UintSet) internal positionIndexes; // token id => bucket indexes associated with position + /// @dev Mapping of `token id => ajna pool address` for which token was minted. + mapping(uint256 => mapping(uint256 => Position)) internal positions; + /// @dev Mapping of `token id => nonce` value used for permit. + mapping(uint256 => uint96) internal nonces; + /// @dev Mapping of `token id => bucket indexes` associated with position. + mapping(uint256 => EnumerableSet.UintSet) internal positionIndexes; - uint176 private _nextId = 1; // id of the next token that will be minted. Skips 0 + /// @dev Id of the next token that will be minted. Skips `0`. + uint176 private _nextId = 1; /******************/ /*** Immutables ***/ /******************/ - ERC20PoolFactory private immutable erc20PoolFactory; // The ERC20 pools factory contract, used to check if address is an Ajna pool - ERC721PoolFactory private immutable erc721PoolFactory; // The ERC721 pools factory contract, used to check if address is an Ajna pool + /// @dev The `ERC20` pools factory contract, used to check if address is an `Ajna` pool. + ERC20PoolFactory private immutable erc20PoolFactory; + /// @dev The `ERC721` pools factory contract, used to check if address is an `Ajna` pool. + ERC721PoolFactory private immutable erc721PoolFactory; /*************************/ /*** Local Var Structs ***/ /*************************/ + /// @dev Struct used for `moveLiquidity` function local vars. struct MoveLiquidityLocalVars { uint256 bucketLPs; // [WAD] amount of LP in from bucket uint256 bucketCollateral; // [WAD] amount of collateral in from bucket @@ -82,6 +90,11 @@ contract PositionManager is ERC721, PermitERC721, IPositionManager, Multicall, R /*** Modifiers ***/ /*****************/ + /** + * @dev Modifier used to check if sender can interact with token id. + * @param pool_ `Ajna` pool address. + * @param tokenId_ Id of positions `NFT`. + */ modifier mayInteract(address pool_, uint256 tokenId_) { // revert if token id is not a valid / minted id @@ -114,17 +127,17 @@ contract PositionManager is ERC721, PermitERC721, IPositionManager, Multicall, R /** * @inheritdoc IPositionManagerOwnerActions - * @dev write state: - * - nonces: remove tokenId nonce - * - poolKey: remove tokenId => pool mapping - * @dev revert on: - * - mayInteract: - * - token id is not a valid / minted id - * - sender is not owner NoAuth() - * - token id not minted for given pool WrongPool() - * - positions token to burn has liquidity LiquidityNotRemoved() - * @dev emit events: - * - Burn + * @dev === Write state === + * @dev `nonces`: remove `tokenId` nonce + * @dev `poolKey`: remove `tokenId => pool` mapping + * @dev === Revert on === + * @dev - `mayInteract`: + * @dev token id is not a valid / minted id + * @dev sender is not owner `NoAuth()` + * @dev token id not minted for given pool `WrongPool()` + * @dev - positions token to burn has liquidity `LiquidityNotRemoved()` + * @dev === Emit events === + * @dev - `Burn` */ function burn( BurnParams calldata params_ @@ -143,16 +156,16 @@ contract PositionManager is ERC721, PermitERC721, IPositionManager, Multicall, R /** * @inheritdoc IPositionManagerOwnerActions - * @dev External calls to Pool contract: - * - lenderInfo(): get lender position in bucket - * - transferLP(): transfer LP ownership to PositionManager contracts - * @dev write state: - * - positionIndexes: add bucket index - * - positions: update tokenId => bucket id position - * @dev revert on: - * - positions token to burn has liquidity LiquidityNotRemoved() - * @dev emit events: - * - MemorializePosition + * @dev External calls to `Pool` contract: + * @dev - `lenderInfo()`: get lender position in bucket + * @dev - `transferLP()`: transfer `LP` ownership to `PositionManager` contract + * @dev === Write state === + * @dev `positionIndexes`: add bucket index + * @dev `positions`: update `tokenId => bucket id` position + * @dev === Revert on === + * @dev positions token to burn has liquidity `LiquidityNotRemoved()` + * @dev === Emit events === + * @dev - `MemorializePosition` */ function memorializePositions( MemorializePositionsParams calldata params_ @@ -204,12 +217,12 @@ contract PositionManager is ERC721, PermitERC721, IPositionManager, Multicall, R /** * @inheritdoc IPositionManagerOwnerActions - * @dev write state: - * - poolKey: update tokenId => pool mapping - * @dev revert on: - * - provided pool not valid NotAjnaPool() - * @dev emit events: - * - Mint + * @dev === Write state === + * @dev `poolKey`: update `tokenId => pool` mapping + * @dev === Revert on === + * @dev provided pool not valid `NotAjnaPool()` + * @dev === Emit events === + * @dev - `Mint` */ function mint( MintParams calldata params_ @@ -229,22 +242,22 @@ contract PositionManager is ERC721, PermitERC721, IPositionManager, Multicall, R /** * @inheritdoc IPositionManagerOwnerActions - * @dev External calls to Pool contract: - * - bucketInfo(): get from bucket info - * - moveQuoteToken(): move liquidity between buckets - * @dev write state: - * - positionIndexes: remove from bucket index - * - positionIndexes: add to bucket index - * - positions: update from bucket position - * - positions: update to bucket position - * @dev revert on: - * - mayInteract: - * - token id is not a valid / minted id - * - sender is not owner NoAuth() - * - token id not minted for given pool WrongPool() - * - positions token to burn has liquidity LiquidityNotRemoved() - * @dev emit events: - * - MoveLiquidity + * @dev External calls to `Pool` contract: + * @dev `bucketInfo()`: get from bucket info + * @dev `moveQuoteToken()`: move liquidity between buckets + * @dev === Write state === + * @dev `positionIndexes`: remove from bucket index + * @dev `positionIndexes`: add to bucket index + * @dev `positions`: update from bucket position + * @dev `positions`: update to bucket position + * @dev === Revert on === + * @dev - `mayInteract`: + * @dev token id is not a valid / minted id + * @dev sender is not owner `NoAuth()` + * @dev token id not minted for given pool `WrongPool()` + * @dev - positions token to burn has liquidity `LiquidityNotRemoved()` + * @dev === Emit events === + * @dev - `MoveLiquidity` */ function moveLiquidity( MoveLiquidityParams calldata params_ @@ -321,20 +334,20 @@ contract PositionManager is ERC721, PermitERC721, IPositionManager, Multicall, R /** * @inheritdoc IPositionManagerOwnerActions - * @dev External calls to Pool contract: - * - increaseLPAllowance(): approve ownership for transfer - * - transferLP(): transfer LP ownership from PositionManager contract - * @dev write state: - * - positionIndexes: remove from bucket index - * - positions: delete bucket position - * @dev revert on: - * - mayInteract: - * - token id is not a valid / minted id - * - sender is not owner NoAuth() - * - token id not minted for given pool WrongPool() - * - position not tracked RemoveLiquidityFailed() - * @dev emit events: - * - RedeemPosition + * @dev External calls to `Pool` contract: + * @dev `increaseLPAllowance()`: approve ownership for transfer + * @dev `transferLP()`: transfer `LP` ownership from `PositionManager` contract + * @dev === Write state === + * @dev `positionIndexes`: remove from bucket index + * @dev `positions`: delete bucket position + * @dev === Revert on === + * @dev - `mayInteract`: + * @dev token id is not a valid / minted id + * @dev sender is not owner `NoAuth()` + * @dev token id not minted for given pool `WrongPool()` + * @dev - position not tracked `RemoveLiquidityFailed()` + * @dev === Emit events === + * @dev - `RedeemPosition` */ function reedemPositions( RedeemPositionsParams calldata params_ @@ -385,7 +398,7 @@ contract PositionManager is ERC721, PermitERC721, IPositionManager, Multicall, R /** * @notice Retrieves token's next nonce for permit. - * @param tokenId_ Address of the Ajna pool to retrieve accumulators of. + * @param tokenId_ Address of the `Ajna` pool to retrieve accumulators of. * @return Incremented token permit nonce. */ function _getAndIncrementNonce( @@ -395,10 +408,10 @@ contract PositionManager is ERC721, PermitERC721, IPositionManager, Multicall, R } /** - * @notice Checks that a provided pool address was deployed by an Ajna factory. - * @param pool_ Address of the Ajna pool. + * @notice Checks that a provided pool address was deployed by an `Ajna` factory. + * @param pool_ Address of the `Ajna` pool. * @param subsetHash_ Factory's subset hash pool. - * @return True if a valid Ajna pool false otherwise. + * @return `True` if a valid `Ajna` pool, `false` otherwise. */ function _isAjnaPool( address pool_, @@ -414,11 +427,11 @@ contract PositionManager is ERC721, PermitERC721, IPositionManager, Multicall, R } /** - * @notice Checks that a bucket index associated with a given NFT didn't go bankrupt after memorialization. + * @notice Checks that a bucket index associated with a given `NFT` didn't go bankrupt after memorialization. * @param pool_ The address of the pool of memorialized position. * @param index_ The bucket index to check deposit time for. * @param depositTime_ The recorded deposit time of the position. - * @return True if the bucket went bankrupt after that position memorialzied their lpb. + * @return `True` if the bucket went bankrupt after that position memorialzied their `LP`. */ function _bucketBankruptAfterDeposit( IPool pool_, diff --git a/src/RewardsManager.sol b/src/RewardsManager.sol index aca8dad8c..b04fafd1e 100644 --- a/src/RewardsManager.sol +++ b/src/RewardsManager.sol @@ -24,13 +24,13 @@ import { Maths } from './libraries/internal/Maths.sol'; /** * @title Rewards (staking) Manager contract - * @notice Pool lenders can optionally mint NFT that represents their positions. - * The Rewards contract allows pool lenders with positions NFT to stake and earn AJNA tokens. - * Lenders with NFTs can: - * - stake token - * - update bucket exchange rate and earn rewards - * - claim rewards - * - unstake token + * @notice Pool lenders can optionally mint `NFT` that represents their positions. + * The Rewards contract allows pool lenders with positions `NFT` to stake and earn `Ajna` tokens. + * Lenders with `NFT`s can: + * - `stake` token + * - `update bucket exchange rate` and earn rewards + * - `claim` rewards + * - `unstake` token */ contract RewardsManager is IRewardsManager, ReentrancyGuard { @@ -41,16 +41,16 @@ contract RewardsManager is IRewardsManager, ReentrancyGuard { /*****************/ /** - * @notice Maximum percentage of tokens burned that can be claimed as Ajna token lp nft rewards. + * @notice Maximum percentage of tokens burned that can be claimed as `Ajna` token `LP` `NFT` rewards. */ uint256 internal constant REWARD_CAP = 0.8 * 1e18; /** - * @notice Maximum percentage of tokens burned that can be claimed as Ajna token update rewards. + * @notice Maximum percentage of tokens burned that can be claimed as `Ajna` token update rewards. */ uint256 internal constant UPDATE_CAP = 0.1 * 1e18; /** * @notice Reward factor by which to scale the total rewards earned. - * @dev ensures that rewards issued to staked lenders in a given pool are less than the ajna tokens burned in that pool. + * @dev ensures that rewards issued to staked lenders in a given pool are less than the `Ajna` tokens burned in that pool. */ uint256 internal constant REWARD_FACTOR = 0.5 * 1e18; /** @@ -66,21 +66,27 @@ contract RewardsManager is IRewardsManager, ReentrancyGuard { /*** State Variables ***/ /***********************/ - mapping(uint256 => mapping(uint256 => bool)) public override isEpochClaimed; // tokenID => epoch => bool has claimed - mapping(uint256 => uint256) public override rewardsClaimed; // epoch => tokens claimed - mapping(uint256 => uint256) public override updateRewardsClaimed; // epoch => tokens claimed + /// @dev `tokenID => epoch => bool has claimed` mapping. + mapping(uint256 => mapping(uint256 => bool)) public override isEpochClaimed; + /// @dev `epoch => rewards claimed` mapping. + mapping(uint256 => uint256) public override rewardsClaimed; + /// @dev `epoch => update bucket rate rewards claimed` mapping. + mapping(uint256 => uint256) public override updateRewardsClaimed; - // Mapping of per pool bucket exchange rates at a given burn event. - mapping(address => mapping(uint256 => mapping(uint256 => uint256))) internal bucketExchangeRates; // poolAddress => bucketIndex => epoch => bucket exchange rate + /// @dev Mapping of per pool bucket exchange rates at a given burn event `poolAddress => bucketIndex => epoch => bucket exchange rate`. + mapping(address => mapping(uint256 => mapping(uint256 => uint256))) internal bucketExchangeRates; - mapping(uint256 => StakeInfo) internal stakes; // tokenID => Stake info + /// @dev Mapping `tokenID => Stake info`. + mapping(uint256 => StakeInfo) internal stakes; /******************/ /*** Immutables ***/ /******************/ - address public immutable ajnaToken; // address of the AJNA token - IPositionManager public immutable positionManager; // The PositionManager contract + /// @dev Address of the `Ajna` token. + address public immutable ajnaToken; + /// @dev The `PositionManager` contract + IPositionManager public immutable positionManager; /*******************/ /*** Constructor ***/ @@ -99,11 +105,11 @@ contract RewardsManager is IRewardsManager, ReentrancyGuard { /** * @inheritdoc IRewardsManagerOwnerActions - * @dev revert on: - * - not owner NotOwnerOfDeposit() - * - already claimed AlreadyClaimed() - * @dev emit events: - * - ClaimRewards + * @dev === Revert on === + * @dev not owner `NotOwnerOfDeposit()` + * @dev already claimed `AlreadyClaimed()` + * @dev === Emit events === + * @dev - `ClaimRewards` */ function claimRewards( uint256 tokenId_, @@ -120,11 +126,11 @@ contract RewardsManager is IRewardsManager, ReentrancyGuard { /** * @inheritdoc IRewardsManagerOwnerActions - * @dev revert on: - * - not owner NotOwnerOfDeposit() - * - invalid index params MoveStakedLiquidityInvalid() - * @dev emit events: - * - MoveStakedLiquidity + * @dev === Revert on === + * @dev not owner `NotOwnerOfDeposit()` + * @dev invalid index params `MoveStakedLiquidityInvalid()` + * @dev === Emit events === + * @dev - `MoveStakedLiquidity` */ function moveStakedLiquidity( uint256 tokenId_, @@ -193,10 +199,10 @@ contract RewardsManager is IRewardsManager, ReentrancyGuard { /** * @inheritdoc IRewardsManagerOwnerActions - * @dev revert on: - * - not owner NotOwnerOfDeposit() - * @dev emit events: - * - Stake + * @dev === Revert on === + * @dev not owner `NotOwnerOfDeposit()` + * @dev === Emit events === + * @dev - `Stake` */ function stake( uint256 tokenId_ @@ -255,11 +261,11 @@ contract RewardsManager is IRewardsManager, ReentrancyGuard { /** * @inheritdoc IRewardsManagerOwnerActions - * @dev revert on: - * - not owner NotOwnerOfDeposit() - * @dev emit events: - * - ClaimRewards - * - Unstake + * @dev === Revert on === + * @dev not owner `NotOwnerOfDeposit()` + * @dev === Emit events === + * @dev - `ClaimRewards` + * @dev - `Unstake` */ function unstake( uint256 tokenId_ @@ -298,8 +304,8 @@ contract RewardsManager is IRewardsManager, ReentrancyGuard { /** * @inheritdoc IRewardsManagerOwnerActions - * @dev emit events: - * - UpdateExchangeRates + * @dev === Emit events === + * @dev - `UpdateExchangeRates` */ function updateBucketExchangeRatesAndClaim( address pool_, @@ -369,11 +375,11 @@ contract RewardsManager is IRewardsManager, ReentrancyGuard { /**************************/ /** - * @notice Calculate the amount of rewards that have been accumulated by a staked NFT. + * @notice Calculate the amount of rewards that have been accumulated by a staked `NFT`. * @dev Rewards are calculated as the difference in exchange rates between the last interaction burn event and the current burn event. - * @param tokenId_ ID of the staked LP NFT. + * @param tokenId_ `ID` of the staked `LP` `NFT`. * @param epochToClaim_ The burn epoch to claim rewards for (rewards calculation starts from the last claimed epoch). - * @return rewards_ Amount of rewards earned by the NFT. + * @return rewards_ Amount of rewards earned by the `NFT`. */ function _calculateAndClaimRewards( uint256 tokenId_, @@ -408,13 +414,13 @@ contract RewardsManager is IRewardsManager, ReentrancyGuard { } /** - * @notice Calculate the amount of rewards that have been accumulated by a staked NFT in next epoch. + * @notice Calculate the amount of rewards that have been accumulated by a staked `NFT` in next epoch. * @dev Rewards are calculated as the difference in exchange rates between the last interaction burn event and the current burn event. - * @param tokenId_ ID of the staked LP NFT. + * @param tokenId_ `ID` of the staked `LP` `NFT`. * @param epoch_ The current epoch. * @param stakingEpoch_ The epoch in which token was staked. * @param ajnaPool_ Address of the pool. - * @param positionIndexes_ Bucket ids associated with NFT staked. + * @param positionIndexes_ Bucket ids associated with `NFT` staked. * @return epochRewards_ Calculated rewards in epoch. */ function _calculateNextEpochRewards( @@ -470,11 +476,11 @@ contract RewardsManager is IRewardsManager, ReentrancyGuard { } /** - * @notice Calculate the amount of interest that has accrued to a lender in a bucket based upon their LP. + * @notice Calculate the amount of interest that has accrued to a lender in a bucket based upon their `LP`. * @param pool_ Address of the pool whose exchange rates are being checked. * @param nextEventEpoch_ The next event epoch to check the exchange rate for. * @param bucketIndex_ Index of the bucket to check the exchange rate for. - * @param bucketLPs Amount of LP in bucket. + * @param bucketLP_ Amount of `LP` in bucket. * @param exchangeRate_ Exchange rate in current epoch. * @return interestEarned_ The amount of interest accrued. */ @@ -482,7 +488,7 @@ contract RewardsManager is IRewardsManager, ReentrancyGuard { address pool_, uint256 nextEventEpoch_, uint256 bucketIndex_, - uint256 bucketLPs, + uint256 bucketLP_, uint256 exchangeRate_ ) internal view returns (uint256 interestEarned_) { @@ -495,7 +501,7 @@ contract RewardsManager is IRewardsManager, ReentrancyGuard { // calculate the equivalent amount of quote tokens given the stakes lp balance, // and the exchange rate at the next and current burn events - interestEarned_ = Maths.wmul(nextExchangeRate - exchangeRate_, bucketLPs); + interestEarned_ = Maths.wmul(nextExchangeRate - exchangeRate_, bucketLP_); } } @@ -503,11 +509,12 @@ contract RewardsManager is IRewardsManager, ReentrancyGuard { /** * @notice Calculate new rewards between current and next epoch, based on earned interest. - * @param ajnaPool_ Address of the pool. - * @param interestEarned_ The amount of interest accrued to current epoch. - * @param nextEpoch_ The next burn event epoch to calculate new rewards. - * @param epoch_ The current burn event epoch to calculate new rewards. - * @return newRewards_ New rewards between current and next burn event epoch. + * @param ajnaPool_ Address of the pool. + * @param interestEarned_ The amount of interest accrued to current epoch. + * @param nextEpoch_ The next burn event epoch to calculate new rewards. + * @param epoch_ The current burn event epoch to calculate new rewards. + * @param rewardsClaimedInEpoch_ Rewards claimed in epoch. + * @return newRewards_ New rewards between current and next burn event epoch. */ function _calculateNewRewards( address ajnaPool_, @@ -544,12 +551,12 @@ contract RewardsManager is IRewardsManager, ReentrancyGuard { } /** - * @notice Claim rewards that have been accumulated by a staked NFT. - * @param stakeInfo_ Details of stake to claim rewards for. - * @param tokenId_ ID of the staked LP NFT. + * @notice Claim rewards that have been accumulated by a staked `NFT`. + * @param stakeInfo_ `StakeInfo` struct containing details of stake to claim rewards for. + * @param tokenId_ `ID` of the staked `LP` `NFT`. * @param epochToClaim_ The burn epoch to claim rewards for (rewards calculation starts from the last claimed epoch) * @param validateEpoch_ True if the epoch is received as a parameter and needs to be validated (lower or equal with latest epoch). - * @param ajnaPool_ Address of ajna pool associated with the stake. + * @param ajnaPool_ Address of `Ajna` pool associated with the stake. */ function _claimRewards( StakeInfo storage stakeInfo_, @@ -619,11 +626,11 @@ contract RewardsManager is IRewardsManager, ReentrancyGuard { /** * @notice Retrieve the total ajna tokens burned and total interest earned by a pool since a given block. - * @param pool_ Address of the Ajna pool to retrieve accumulators of. + * @param pool_ Address of the `Ajna` pool to retrieve accumulators of. * @param currentBurnEventEpoch_ The latest burn event. * @param lastBurnEventEpoch_ The burn event to use as checkpoint since which values have accumulated. * @return Timestamp of the latest burn event. - * @return Total ajna tokens burned by the pool since the last burn event. + * @return Total `Ajna` tokens burned by the pool since the last burn event. * @return Total interest earned by the pool since the last burn event. */ function _getPoolAccumulators( @@ -655,10 +662,11 @@ contract RewardsManager is IRewardsManager, ReentrancyGuard { /** * @notice Update the exchange rate of a list of buckets. - * @dev Called as part of stakeToken, unstakeToken, and claimRewards, as well as updateBucketExchangeRatesAndClaim. - * @dev Caller can claim 5% of the rewards that have accumulated to each bucket since the last burn event, if it hasn't already been updated. - * @param pool_ Address of the pool whose exchange rates are being updated. - * @param indexes_ List of bucket indexes to be updated. + * @dev Called as part of `stake`, `unstake`, and `claimRewards`, as well as `updateBucketExchangeRatesAndClaim`. + * @dev Caller can claim `5%` of the rewards that have accumulated to each bucket since the last burn event, if it hasn't already been updated. + * @param pool_ Address of the pool whose exchange rates are being updated. + * @param indexes_ List of bucket indexes to be updated. + * @return updatedRewards_ Update exchange rate rewards. */ function _updateBucketExchangeRates( address pool_, @@ -753,8 +761,9 @@ contract RewardsManager is IRewardsManager, ReentrancyGuard { * @param pool_ Address of the pool whose exchange rates are being updated. * @param bucketIndex_ Bucket index to update exchange rate. * @param burnEpoch_ Current burn epoch of the pool. - * @param totalBurned_ Total Ajna tokens burned in pool. + * @param totalBurned_ Total `Ajna` tokens burned in pool. * @param interestEarned_ Total interest rate earned in pool. + * @return rewards_ Rewards for bucket exchange rate update. */ function _updateBucketExchangeRateAndCalculateRewards( address pool_, @@ -794,8 +803,8 @@ contract RewardsManager is IRewardsManager, ReentrancyGuard { } } - /** @notice Utility method to transfer Ajna rewards to the sender - * @dev This method is used to transfer rewards to the sender after a successful claim or update. + /** @notice Utility method to transfer `Ajna` rewards to the sender + * @dev This method is used to transfer rewards to the `msg.sender` after a successful claim or update. * @dev It is used to ensure that rewards claimers will be able to claim some portion of the remaining tokens if a claim would exceed the remaining contract balance. * @param rewardsEarned_ Amount of rewards earned by the caller. */ diff --git a/src/interfaces/position/IPositionManagerDerivedState.sol b/src/interfaces/position/IPositionManagerDerivedState.sol index 7cc95761a..7119646f7 100644 --- a/src/interfaces/position/IPositionManagerDerivedState.sol +++ b/src/interfaces/position/IPositionManagerDerivedState.sol @@ -8,42 +8,42 @@ pragma solidity 0.8.14; interface IPositionManagerDerivedState { /** - * @notice Returns the LP accrued to a given tokenId, bucket pairing. + * @notice Returns the `LP` accrued to a given `tokenId`, bucket pairing. * @dev Nested mappings aren't returned normally as part of the default getter for a mapping. - * @param tokenId Unique ID of token. - * @param index Index of bucket to check LP balance of. - * @return lps Balance of lps in the bucket for this position. + * @param tokenId_ Unique `ID` of token. + * @param index_ Index of bucket to check `LP` balance of. + * @return lp_ Balance of `LP` in the bucket for this position. */ function getLP( - uint256 tokenId, - uint256 index - ) external view returns (uint256 lps); + uint256 tokenId_, + uint256 index_ + ) external view returns (uint256 lp_); /** - * @notice Returns an array of bucket indexes in which an NFT has liquidity. + * @notice Returns an array of bucket indexes in which an `NFT` has liquidity. * @dev Potentially includes buckets that have been bankrupted. - * @param tokenId Unique ID of token. + * @param tokenId_ Unique `ID` of token. * @return Array of bucket indexes. */ function getPositionIndexes( - uint256 tokenId + uint256 tokenId_ ) external view returns (uint256[] memory); /** - * @notice Returns an array of bucket indexes in which an NFT has liquidity, with bankrupt buckets removed. - * @param tokenId Unique ID of token. + * @notice Returns an array of bucket indexes in which an `NFT` has liquidity, with bankrupt buckets removed. + * @param tokenId_ Unique `ID` of token. * @return Array of bucket indexes filtered for active liquidity. */ function getPositionIndexesFiltered( - uint256 tokenId + uint256 tokenId_ ) external view returns (uint256[] memory); /** - * @notice Returns information about a given NFT. - * @param tokenId_ Unique ID of token. + * @notice Returns information about a given `NFT`. + * @param tokenId_ Unique `ID` of token. * @param index_ Bucket index to check for position information. - * @return lps in that bucket. - * @return position's deposit time. + * @return `LP` in bucket. + * @return Position's deposit time. */ function getPositionInfo( uint256 tokenId_, @@ -52,15 +52,15 @@ interface IPositionManagerDerivedState { /** - * @notice Checks if a given tokenId has a given position bucket - * @param tokenId Unique ID of token. - * @param index Index of bucket to check if in position buckets. - * @return bucketInPosition True if tokenId has the position bucket. + * @notice Checks if a given `tokenId` has a given position bucket + * @param tokenId_ Unique `ID` of token. + * @param index_ Index of bucket to check if in position buckets. + * @return bucketInPosition_ `True` if tokenId has the position bucket. */ function isIndexInPosition( - uint256 tokenId, - uint256 index - ) external view returns (bool bucketInPosition); + uint256 tokenId_, + uint256 index_ + ) external view returns (bool bucketInPosition_); /** * @notice Checks if a tokenId has a position in a bucket that was bankrupted. diff --git a/src/interfaces/position/IPositionManagerErrors.sol b/src/interfaces/position/IPositionManagerErrors.sol index adc5077ef..dcfa90877 100644 --- a/src/interfaces/position/IPositionManagerErrors.sol +++ b/src/interfaces/position/IPositionManagerErrors.sol @@ -8,32 +8,32 @@ pragma solidity 0.8.14; interface IPositionManagerErrors { /** - * @notice User attempting to utilize LPB from a bankrupt bucket. + * @notice User attempting to utilize `LP` from a bankrupt bucket. */ error BucketBankrupt(); /** - * @notice User attempting to burn a LPB NFT before removing liquidity. + * @notice User attempting to burn a `LP` `NFT` before removing liquidity. */ error LiquidityNotRemoved(); /** - * @notice User not authorized to interact with the specified NFT. + * @notice User not authorized to interact with the specified `NFT`. */ error NoAuth(); /** - * @notice User attempted to mint an NFT pointing to a pool that wasn't deployed by an Ajna factory. + * @notice User attempted to mint an `NFT` pointing to a pool that wasn't deployed by an `Ajna` factory. */ error NotAjnaPool(); /** - * @notice User failed to remove position from their NFT. + * @notice User failed to remove position from their `NFT`. */ error RemovePositionFailed(); /** - * @notice User attempting to interact with a pool that doesn't match the pool associated with the tokenId. + * @notice User attempting to interact with a pool that doesn't match the pool associated with the `tokenId`. */ error WrongPool(); } \ No newline at end of file diff --git a/src/interfaces/position/IPositionManagerEvents.sol b/src/interfaces/position/IPositionManagerEvents.sol index f8ebe89e7..e74458ec2 100644 --- a/src/interfaces/position/IPositionManagerEvents.sol +++ b/src/interfaces/position/IPositionManagerEvents.sol @@ -8,9 +8,9 @@ pragma solidity 0.8.14; interface IPositionManagerEvents { /** - * @notice Emitted when an existing NFT was burned. + * @notice Emitted when an existing `NFT` was burned. * @param lender Lender address. - * @param tokenId The token id of the NFT that was burned. + * @param tokenId The token id of the `NFT` that was burned. */ event Burn( address indexed lender, @@ -18,8 +18,8 @@ interface IPositionManagerEvents { ); /** - * @notice Emitted when existing positions were memorialized for a given NFT. - * @param tokenId The tokenId of the NFT. + * @notice Emitted when existing positions were memorialized for a given `NFT`. + * @param tokenId The `tokenId` of the `NFT`. * @param indexes Bucket indexes of memorialized positions. */ event MemorializePosition( @@ -29,10 +29,10 @@ interface IPositionManagerEvents { ); /** - * @notice Emitted when representative NFT minted. + * @notice Emitted when representative `NFT` minted. * @param lender Lender address. * @param pool Pool address. - * @param tokenId The tokenId of the newly minted NFT. + * @param tokenId The `tokenId` of the newly minted `NFT`. */ event Mint( address indexed lender, @@ -43,11 +43,11 @@ interface IPositionManagerEvents { /** * @notice Emitted when a position's liquidity is moved between buckets. * @param lender Lender address. - * @param tokenId The tokenId of the newly minted NFT. + * @param tokenId The `tokenId` of the newly minted `NFT`. * @param fromIndex Index of bucket from where liquidity is moved. * @param toIndex Index of bucket where liquidity is moved. - * @param lpRedeemedFrom Amount of LP removed from the `from` bucket. - * @param lpAwardedTo Amount of LP credited to the `to` bucket. + * @param lpRedeemedFrom Amount of `LP` removed from the `from` bucket. + * @param lpAwardedTo Amount of `LP` credited to the `to` bucket. */ event MoveLiquidity( address indexed lender, @@ -59,8 +59,8 @@ interface IPositionManagerEvents { ); /** - * @notice Emitted when existing positions were redeemed for a given NFT. - * @param tokenId The tokenId of the NFT. + * @notice Emitted when existing positions were redeemed for a given `NFT`. + * @param tokenId The `tokenId` of the `NFT`. * @param indexes Bucket indexes of redeemed positions. */ event RedeemPosition( diff --git a/src/interfaces/position/IPositionManagerOwnerActions.sol b/src/interfaces/position/IPositionManagerOwnerActions.sol index 7138f811b..ebeeb305f 100644 --- a/src/interfaces/position/IPositionManagerOwnerActions.sol +++ b/src/interfaces/position/IPositionManagerOwnerActions.sol @@ -8,12 +8,12 @@ pragma solidity 0.8.14; interface IPositionManagerOwnerActions { /** - * @notice Called by owners to burn an existing NFT. - * @dev Requires that all lps have been removed from the NFT prior to calling. - * @param params Calldata struct supplying inputs required to update the underlying assets owed to an NFT. + * @notice Called by owners to burn an existing `NFT`. + * @dev Requires that all `LP` have been removed from the `NFT `prior to calling. + * @param params_ Calldata struct supplying inputs required to update the underlying assets owed to an `NFT`. */ function burn( - BurnParams calldata params + BurnParams calldata params_ ) external; /** @@ -22,40 +22,40 @@ interface IPositionManagerOwnerActions { * @dev The NFT must have already been created, and the number of buckets to be memorialized at a time determined by function caller. * @dev An additional call is made to the pool to transfer the LP from their previous owner, to the Position Manager. * @dev `Pool.increaseLPAllowance` must be called prior to calling this method in order to allow Position manager contract to transfer LP to be memorialized. - * @param params Calldata struct supplying inputs required to conduct the memorialization. + * @param params_ Calldata struct supplying inputs required to conduct the memorialization. */ function memorializePositions( - MemorializePositionsParams calldata params + MemorializePositionsParams calldata params_ ) external; /** - * @notice Called by owners to mint and receive an Ajna Position NFT. - * @dev PositionNFTs can only be minited with an association to pools that have been deployed by the Ajna ERC20PoolFactory or ERC721PoolFactory. - * @param params Calldata struct supplying inputs required to mint a positions NFT. - * @return tokenId The tokenId of the newly minted NFT. + * @notice Called by owners to mint and receive an `Ajna` Position `NFT`. + * @dev Position `NFT`s can only be minited with an association to pools that have been deployed by the `Ajna` `ERC20PoolFactory` or `ERC721PoolFactory`. + * @param params_ Calldata struct supplying inputs required to mint a positions `NFT`. + * @return tokenId_ The `tokenId` of the newly minted `NFT`. */ function mint( - MintParams calldata params - ) external returns (uint256 tokenId); + MintParams calldata params_ + ) external returns (uint256 tokenId_); /** * @notice Called by owners to move liquidity between two buckets. - * @param params Calldata struct supplying inputs required to move liquidity tokens. + * @param params_ Calldata struct supplying inputs required to move liquidity tokens. */ function moveLiquidity( - MoveLiquidityParams calldata params + MoveLiquidityParams calldata params_ ) external; /** - * @notice Called to reedem existing positions with a given NFT. + * @notice Called to reedem existing positions with a given `NFT`. * @dev The array of buckets is expected to be constructed off chain by scanning events for that lender. - * @dev The NFT must have already been created, and the number of buckets to be memorialized at a time determined by function caller. - * @dev An additional call is made to the pool to transfer the LP Position Manager to owner. - * @dev `Pool.approveLPTransferors` must be called prior to calling this method in order to allow Position manager contract to transfer redeemed LP. - * @param params Calldata struct supplying inputs required to conduct the redeem. + * @dev The `NFT` must have already been created, and the number of buckets to be memorialized at a time determined by function caller. + * @dev An additional call is made to the pool to transfer the `LP` Position Manager to owner. + * @dev `Pool.approveLPTransferors` must be called prior to calling this method in order to allow `Position manager` contract to transfer redeemed `LP`. + * @param params_ Calldata struct supplying inputs required to conduct the redeem. */ function reedemPositions( - RedeemPositionsParams calldata params + RedeemPositionsParams calldata params_ ) external; /*********************/ @@ -63,7 +63,7 @@ interface IPositionManagerOwnerActions { /*********************/ /** - * @notice Struct holding parameters for burning an NFT. + * @notice Struct holding parameters for burning an `NFT`. */ struct BurnParams { uint256 tokenId; // The tokenId of the positions NFT to burn diff --git a/src/interfaces/position/IPositionManagerState.sol b/src/interfaces/position/IPositionManagerState.sol index 364e00bbb..26e669a4e 100644 --- a/src/interfaces/position/IPositionManagerState.sol +++ b/src/interfaces/position/IPositionManagerState.sol @@ -8,15 +8,16 @@ pragma solidity 0.8.14; interface IPositionManagerState { /** - * @notice Returns the pool address associated with a positions NFT. - * @param tokenId The token id of the positions NFT. - * @return Pool address associated with the NFT. + * @notice Returns the pool address associated with a positions `NFT`. + * @param tokenId_ The token id of the positions `NFT`. + * @return Pool address associated with the `NFT`. */ function poolKey( - uint256 tokenId + uint256 tokenId_ ) external view returns (address); } +/// @dev Struct holding Position `LP` state. struct Position { uint256 lps; // [WAD] position LP uint256 depositTime; // deposit time for position diff --git a/src/interfaces/rewards/IRewardsManagerDerivedState.sol b/src/interfaces/rewards/IRewardsManagerDerivedState.sol index 2e1a53e8a..ab360f44f 100644 --- a/src/interfaces/rewards/IRewardsManagerDerivedState.sol +++ b/src/interfaces/rewards/IRewardsManagerDerivedState.sol @@ -8,14 +8,14 @@ pragma solidity 0.8.14; interface IRewardsManagerDerivedState { /** - * @notice Calculate the amount of rewards that have been accumulated by a staked NFT. - * @param tokenId ID of the staked LP NFT. - * @param claimEpoch The end burn epoch to calculate rewards for (rewards calculation starts from the last claimed epoch). - * @return rewards_ The amount of rewards earned by the NFT. + * @notice Calculate the amount of rewards that have been accumulated by a staked `NFT`. + * @param tokenId_ `ID` of the staked `LP` `NFT`. + * @param epochToClaim_ The end burn epoch to calculate rewards for (rewards calculation starts from the last claimed epoch). + * @return The amount of rewards earned by the staked `NFT`. */ function calculateRewards( - uint256 tokenId, - uint256 claimEpoch + uint256 tokenId_, + uint256 epochToClaim_ ) external view returns (uint256); } diff --git a/src/interfaces/rewards/IRewardsManagerErrors.sol b/src/interfaces/rewards/IRewardsManagerErrors.sol index dbfa58320..591af6c5f 100644 --- a/src/interfaces/rewards/IRewardsManagerErrors.sol +++ b/src/interfaces/rewards/IRewardsManagerErrors.sol @@ -22,12 +22,12 @@ interface IRewardsManagerErrors { error MoveStakedLiquidityInvalid(); /** - * @notice User attempted to interact with an NFT they aren't the owner of. + * @notice User attempted to interact with an `NFT` they aren't the owner of. */ error NotOwnerOfDeposit(); /** - * @notice Can't deploy with Ajna token address 0x0 address. + * @notice Can't deploy with `Ajna` token address `0x` address. */ error DeployWithZeroAddress(); } \ No newline at end of file diff --git a/src/interfaces/rewards/IRewardsManagerEvents.sol b/src/interfaces/rewards/IRewardsManagerEvents.sol index f1607eb4b..04dc2e403 100644 --- a/src/interfaces/rewards/IRewardsManagerEvents.sol +++ b/src/interfaces/rewards/IRewardsManagerEvents.sol @@ -8,12 +8,12 @@ pragma solidity 0.8.14; interface IRewardsManagerEvents { /** - * @notice Emitted when lender claims rewards that have accrued to their staked NFT. - * @param owner Owner of the staked NFT. - * @param ajnaPool Address of the Ajna pool the NFT corresponds to. - * @param tokenId ID of the staked NFT. + * @notice Emitted when lender claims rewards that have accrued to their staked `NFT`. + * @param owner Owner of the staked `NFT`. + * @param ajnaPool Address of the `Ajna` pool the `NFT` corresponds to. + * @param tokenId `ID` of the staked `NFT`. * @param epochsClaimed Array of burn epochs claimed. - * @param amount The amount of AJNA tokens claimed by the staker. + * @param amount The amount of `Ajna` tokens claimed by the staker. */ event ClaimRewards( address indexed owner, @@ -24,8 +24,8 @@ interface IRewardsManagerEvents { ); /** - * @notice Emitted when moves liquidity in a staked NFT between buckets. - * @param tokenId ID of the staked NFT. + * @notice Emitted when moves liquidity in a staked `NFT` between buckets. + * @param tokenId `ID` of the staked `NFT`. * @param fromIndexes Array of indexes from which liquidity was moved. * @param toIndexes Array of indexes to which liquidity was moved. */ @@ -36,10 +36,10 @@ interface IRewardsManagerEvents { ); /** - * @notice Emitted when lender stakes their LP NFT in the rewards contract. - * @param owner Owner of the staked NFT. - * @param ajnaPool Address of the Ajna pool the NFT corresponds to. - * @param tokenId ID of the staked NFT. + * @notice Emitted when lender stakes their `LP` `NFT` in the rewards contract. + * @param owner Owner of the staked `NFT`. + * @param ajnaPool Address of the `Ajna` pool the `NFT` corresponds to. + * @param tokenId `ID` of the staked `NFT`. */ event Stake( address indexed owner, @@ -50,9 +50,9 @@ interface IRewardsManagerEvents { /** * @notice Emitted when someone records the latest exchange rate for a bucket in a pool, and claims the associated reward. * @param caller Address of the recorder. The address which will receive an update reward, if applicable. - * @param ajnaPool Address of the Ajna pool whose exchange rates are being updated. + * @param ajnaPool Address of the `Ajna` pool whose exchange rates are being updated. * @param indexesUpdated Array of bucket indexes whose exchange rates are being updated. - * @param rewardsClaimed Amount of ajna tokens claimed by the recorder as a reward for updating each bucket index. + * @param rewardsClaimed Amount of `Ajna` tokens claimed by the recorder as a reward for updating each bucket index. */ event UpdateExchangeRates( address indexed caller, @@ -62,10 +62,10 @@ interface IRewardsManagerEvents { ); /** - * @notice Emitted when lender withdraws their LP NFT from the rewards contract. - * @param owner Owner of the staked NFT. - * @param ajnaPool Address of the Ajna pool the NFT corresponds to. - * @param tokenId ID of the staked NFT. + * @notice Emitted when lender withdraws their `LP` `NFT` from the rewards contract. + * @param owner Owner of the staked `NFT`. + * @param ajnaPool Address of the `Ajna` pool the `NFT` corresponds to. + * @param tokenId `ID` of the staked `NFT`. */ event Unstake( address indexed owner, diff --git a/src/interfaces/rewards/IRewardsManagerOwnerActions.sol b/src/interfaces/rewards/IRewardsManagerOwnerActions.sol index fd378b0a5..00cbda95c 100644 --- a/src/interfaces/rewards/IRewardsManagerOwnerActions.sol +++ b/src/interfaces/rewards/IRewardsManagerOwnerActions.sol @@ -8,25 +8,25 @@ pragma solidity 0.8.14; interface IRewardsManagerOwnerActions { /** - * @notice Claim ajna token rewards that have accrued to a staked LP NFT. - * @dev Updates exchange rates for each bucket the NFT is associated with. - * @param tokenId ID of the staked LP NFT. - * @param claimEpoch The burn epoch to claim rewards for. + * @notice Claim `Ajna` token rewards that have accrued to a staked `LP` `NFT`. + * @dev Updates exchange rates for each bucket the `NFT` is associated with. + * @param tokenId_ `ID` of the staked `LP` `NFT`. + * @param epochToClaim_ The burn epoch to claim rewards for. */ function claimRewards( - uint256 tokenId, - uint256 claimEpoch + uint256 tokenId_, + uint256 epochToClaim_ ) external; /** - * @notice Moves liquidity in a staked NFT between buckets. - * @dev Calls out to PositionManager.moveLiquidity(). - * @dev Automatically claims any available rewards in all existing buckets. Updates exchange rates for each new bucket the NFT is associated with. - * @dev fromBuckets and toBuckets must be the same array length. Liquidity is moved from the fromBuckets to the toBuckets in the same index. - * @param tokenId_ ID of the staked LP NFT. + * @notice Moves liquidity in a staked `NFT` between buckets. + * @dev Calls out to `PositionManager.moveLiquidity()`. + * @dev Automatically claims any available rewards in all existing buckets. Updates exchange rates for each new bucket the `NFT` is associated with. + * @dev `fromBuckets_` and `toBuckets_` must be the same array length. Liquidity is moved from the `fromBuckets_` to the `toBuckets_` in the same index. + * @param tokenId_ `ID` of the staked `LP` `NFT`. * @param fromBuckets_ The list of bucket indexes to move liquidity from. * @param toBuckets_ The list of bucket indexes to move liquidity to. - * @param expiry_ Timestamp after which this TX will revert, preventing inclusion in a block with unfavorable price. + * @param expiry_ Timestamp after which this transaction will revert, preventing inclusion in a block with unfavorable price. */ function moveStakedLiquidity( uint256 tokenId_, @@ -36,33 +36,33 @@ interface IRewardsManagerOwnerActions { ) external; /** - * @notice Stake a LP NFT into the rewards contract. - * @dev Updates exchange rates for each bucket the NFT is associated with. - * @param tokenId ID of the LP NFT to stake in the AjnaRewards contract. + * @notice Stake a `LP` `NFT` into the rewards contract. + * @dev Updates exchange rates for each bucket the `NFT` is associated with. + * @param tokenId_ `ID` of the `LP` `NFT` to stake in the `Rewards contract. */ function stake( - uint256 tokenId + uint256 tokenId_ ) external; /** - * @notice Withdraw a staked LP NFT from the rewards contract. + * @notice Withdraw a staked `LP` `NFT` from the rewards contract. * @notice If rewards are available, claim all available rewards before withdrawal. - * @param tokenId ID of the staked LP NFT. + * @param tokenId_ `ID` of the staked `LP` `NFT`. */ function unstake( - uint256 tokenId + uint256 tokenId_ ) external; /** * @notice Update the exchange rate of a list of buckets. - * @dev Caller can claim 5% of the rewards that have accumulated to each bucket since the last burn event, if it hasn't already been updated. - * @param pool Address of the pool whose exchange rates are being updated. - * @param indexes List of bucket indexes to be updated. + * @dev Caller can claim `5%` of the rewards that have accumulated to each bucket since the last burn event, if it hasn't already been updated. + * @param pool_ Address of the pool whose exchange rates are being updated. + * @param indexes_ List of bucket indexes to be updated. * @return Returns reward amount for updating bucket exchange rates. */ function updateBucketExchangeRatesAndClaim( - address pool, - uint256[] calldata indexes + address pool_, + uint256[] calldata indexes_ ) external returns (uint256); } \ No newline at end of file diff --git a/src/interfaces/rewards/IRewardsManagerState.sol b/src/interfaces/rewards/IRewardsManagerState.sol index 061b8cd64..a933f5304 100644 --- a/src/interfaces/rewards/IRewardsManagerState.sol +++ b/src/interfaces/rewards/IRewardsManagerState.sol @@ -9,54 +9,54 @@ interface IRewardsManagerState { /** * @notice Track whether a depositor has claimed rewards for a given burn event epoch. - * @param tokenId ID of the staked LP NFT. - * @param epoch The burn epoch to track if rewards were claimed. - * @return True if rewards were claimed for the given epoch, else false. + * @param tokenId_ ID of the staked `LP` `NFT`. + * @param epoch_ The burn epoch to track if rewards were claimed. + * @return `True` if rewards were claimed for the given epoch, else false. */ function isEpochClaimed( - uint256 tokenId, - uint256 epoch + uint256 tokenId_, + uint256 epoch_ ) external view returns (bool); /** * @notice Track the total amount of rewards that have been claimed for a given epoch. - * @param epoch The burn epoch to track if rewards were claimed. + * @param epoch_ The burn epoch to track if rewards were claimed. * @return The amount of rewards claimed in given epoch. */ function rewardsClaimed( - uint256 epoch + uint256 epoch_ ) external view returns (uint256); /** * @notice Track the total amount of rewards that have been claimed for a given burn event's bucket updates. - * @param epoch The burn epoch to track if rewards were claimed. + * @param epoch_ The burn epoch to track if rewards were claimed. * @return The amount of update rewards claimed in given epoch. */ function updateRewardsClaimed( - uint256 epoch + uint256 epoch_ ) external view returns (uint256); /** * @notice Retrieve information about a given stake. - * @param tokenId ID of the NFT staked in the rewards contract to retrieve information about. - * @return The owner of a given NFT stake. - * @return The Pool the NFT represents positions in. - * @return The last burn epoch in which the owner of the NFT claimed rewards. + * @param tokenId_ `ID` of the `NFT` staked in the rewards contract to retrieve information about. + * @return owner_ The owner of a given `NFT` stake. + * @return pool_ The `Pool` the `NFT` represents positions in. + * @return lastClaimedEpoch_ The last burn epoch in which the owner of the `NFT` claimed rewards. */ function getStakeInfo( - uint256 tokenId - ) external view returns (address, address, uint256); + uint256 tokenId_ + ) external view returns (address owner_, address pool_, uint256 lastClaimedEpoch_); /** - * @notice Retrieve information about recorded LP and rate values for a given bucket and a given stake, at stake time. - * @param tokenId ID of the NFT staked in the rewards contract to retrieve information about. - * @param bucketId ID of the bucket to retrieve recorded information at stake time. - * @return [WAD] LP amount the NFT owner is entitled in current bucket at the time of staking. - * @return [WAD] current bucket exchange rate at the time of staking. + * @notice Retrieve information about recorded `LP` and rate values for a given bucket and a given stake, at stake time. + * @param tokenId_ `ID` of the `NFT` staked in the rewards contract to retrieve information about. + * @param bucketId_ `ID` of the bucket to retrieve recorded information at stake time. + * @return `LP` amount (in `WAD`) the `NFT` owner is entitled in current bucket at the time of staking. + * @return Current bucket exchange rate (`WAD`) at the time of staking. */ function getBucketStateStakeInfo( - uint256 tokenId, - uint256 bucketId + uint256 tokenId_, + uint256 bucketId_ ) external view returns (uint256, uint256); } @@ -65,6 +65,7 @@ interface IRewardsManagerState { /*** State Structs ***/ /*********************/ +/// @dev Struct holding stake info state. struct StakeInfo { address ajnaPool; // address of the Ajna pool the NFT corresponds to uint96 lastClaimedEpoch; // last epoch the stake claimed rewards @@ -73,6 +74,7 @@ struct StakeInfo { mapping(uint256 => BucketState) snapshot; // the LP NFT's balances and exchange rates in each bucket at the time of staking } +/// @dev Struct holding bucket state at stake time. struct BucketState { uint128 lpsAtStakeTime; // [WAD] LP amount the NFT owner is entitled in current bucket at the time of staking uint128 rateAtStakeTime; // [WAD] current bucket exchange rate at the time of staking From bb6dbd25f814770b5ee330e498a5a585a72e2361 Mon Sep 17 00:00:00 2001 From: grandizzy Date: Wed, 19 Apr 2023 08:06:42 +0300 Subject: [PATCH 06/11] Add docs gitignore --- docs/.gitignore | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 docs/.gitignore diff --git a/docs/.gitignore b/docs/.gitignore new file mode 100644 index 000000000..0e09091d7 --- /dev/null +++ b/docs/.gitignore @@ -0,0 +1,3 @@ +book* +src/ +solidity.min.js \ No newline at end of file From b17cf3384b1f1683118fb9959697c75da5e66d31 Mon Sep 17 00:00:00 2001 From: grandizzy Date: Wed, 19 Apr 2023 08:17:14 +0300 Subject: [PATCH 07/11] Use index_ instead i_ in Loans library --- src/libraries/internal/Loans.sol | 68 ++++++++++++++++---------------- 1 file changed, 34 insertions(+), 34 deletions(-) diff --git a/src/libraries/internal/Loans.sol b/src/libraries/internal/Loans.sol index 97c6528e7..c62e80529 100644 --- a/src/libraries/internal/Loans.sol +++ b/src/libraries/internal/Loans.sol @@ -128,16 +128,16 @@ library Loans { /** * @notice Moves a `Loan` up the heap. * @param loans_ Holds loans heap data. - * @param loan_ `Loan` to be moved. - * @param i_ Index for `Loan` to be moved to. + * @param loan_ `Loan` to be moved. + * @param index_ Index of `Loan` to be moved to. */ - function _bubbleUp(LoansState storage loans_, Loan memory loan_, uint i_) private { + function _bubbleUp(LoansState storage loans_, Loan memory loan_, uint index_) private { uint256 count = loans_.loans.length; - if (i_ == ROOT_INDEX || loan_.thresholdPrice <= loans_.loans[i_ / 2].thresholdPrice){ - _insert(loans_, loan_, i_, count); + if (index_ == ROOT_INDEX || loan_.thresholdPrice <= loans_.loans[index_ / 2].thresholdPrice){ + _insert(loans_, loan_, index_, count); } else { - _insert(loans_, loans_.loans[i_ / 2], i_, count); - _bubbleUp(loans_, loan_, i_ / 2); + _insert(loans_, loans_.loans[index_ / 2], index_, count); + _bubbleUp(loans_, loan_, index_ / 2); } } @@ -145,15 +145,15 @@ library Loans { * @notice Moves a `Loan` down the heap. * @param loans_ Holds loans heap data. * @param loan_ `Loan` to be moved. - * @param i_ Index for `Loan` to be moved to. + * @param index_ Index of `Loan` to be moved to. */ - function _bubbleDown(LoansState storage loans_, Loan memory loan_, uint i_) private { + function _bubbleDown(LoansState storage loans_, Loan memory loan_, uint index_) private { // Left child index. - uint cIndex = i_ * 2; + uint cIndex = index_ * 2; uint256 count = loans_.loans.length; if (count <= cIndex) { - _insert(loans_, loan_, i_, count); + _insert(loans_, loan_, index_, count); } else { Loan memory largestChild = loans_.loans[cIndex]; @@ -162,9 +162,9 @@ library Loans { } if (largestChild.thresholdPrice <= loan_.thresholdPrice) { - _insert(loans_, loan_, i_, count); + _insert(loans_, loan_, index_, count); } else { - _insert(loans_, largestChild, i_, count); + _insert(loans_, largestChild, index_, count); _bubbleDown(loans_, loan_, cIndex); } } @@ -174,30 +174,30 @@ library Loans { * @notice Inserts a `Loan` in the heap. * @param loans_ Holds loans heap data. * @param loan_ `Loan` to be inserted. - * @param i_ Index for `Loan` to be inserted at. + * @param index_ Index of `Loan` to be inserted at. */ - function _insert(LoansState storage loans_, Loan memory loan_, uint i_, uint256 count_) private { - if (i_ == count_) loans_.loans.push(loan_); - else loans_.loans[i_] = loan_; + function _insert(LoansState storage loans_, Loan memory loan_, uint index_, uint256 count_) private { + if (index_ == count_) loans_.loans.push(loan_); + else loans_.loans[index_] = loan_; - loans_.indices[loan_.borrower] = i_; + loans_.indices[loan_.borrower] = index_; } /** * @notice Removes `Loan` from heap given borrower address. * @param loans_ Holds loans heap data. * @param borrower_ Borrower address whose `Loan` is being updated or inserted. - * @param id_ `Loan` id. + * @param index_ Index of `Loan` to be removed. */ - function remove(LoansState storage loans_, address borrower_, uint256 id_) internal { + function remove(LoansState storage loans_, address borrower_, uint256 index_) internal { delete loans_.indices[borrower_]; uint256 tailIndex = loans_.loans.length - 1; - if (id_ == tailIndex) loans_.loans.pop(); // we're removing the tail, pop without sorting + if (index_ == tailIndex) loans_.loans.pop(); // we're removing the tail, pop without sorting else { Loan memory tail = loans_.loans[tailIndex]; loans_.loans.pop(); // remove tail loan - _bubbleUp(loans_, tail, id_); - _bubbleDown(loans_, loans_.loans[id_], id_); + _bubbleUp(loans_, tail, index_); + _bubbleDown(loans_, loans_.loans[index_], index_); } } @@ -205,24 +205,24 @@ library Loans { * @notice Performs an insert or an update dependent on borrowers existance. * @param loans_ Holds loans heap data. * @param borrower_ Borrower address that is being updated or inserted. - * @param id_ `Loan` id. + * @param index_ Index of `Loan` to be upserted. * @param thresholdPrice_ `Threshold Price` that is updated or inserted. */ function _upsert( LoansState storage loans_, address borrower_, - uint256 id_, + uint256 index_, uint96 thresholdPrice_ ) internal { // Loan exists, update in place. - if (id_ != 0) { - Loan memory currentLoan = loans_.loans[id_]; + if (index_ != 0) { + Loan memory currentLoan = loans_.loans[index_]; if (currentLoan.thresholdPrice > thresholdPrice_) { currentLoan.thresholdPrice = thresholdPrice_; - _bubbleDown(loans_, currentLoan, id_); + _bubbleDown(loans_, currentLoan, index_); } else { currentLoan.thresholdPrice = thresholdPrice_; - _bubbleUp(loans_, currentLoan, id_); + _bubbleUp(loans_, currentLoan, index_); } // New loan, insert it @@ -237,13 +237,13 @@ library Loans { /**********************/ /** - * @notice Retreives `Loan` by index, `i_`. + * @notice Retreives `Loan` by index, `index_`. * @param loans_ Holds loans heap data. - * @param i_ Index to retrieve `Loan`. - * @return `Loan` retrieved by index. + * @param index_ Index to retrieve `Loan`. + * @return `Loan` struct retrieved by index. */ - function getByIndex(LoansState storage loans_, uint256 i_) internal view returns(Loan memory) { - return loans_.loans.length > i_ ? loans_.loans[i_] : Loan(address(0), 0); + function getByIndex(LoansState storage loans_, uint256 index_) internal view returns(Loan memory) { + return loans_.loans.length > index_ ? loans_.loans[index_] : Loan(address(0), 0); } /** From a2db7a49ae4ae489bb199e422db1518a416965cb Mon Sep 17 00:00:00 2001 From: grandizzy Date: Wed, 19 Apr 2023 09:31:43 +0300 Subject: [PATCH 08/11] Consistent LPs to LP naming --- src/PoolInfoUtils.sol | 8 +- src/PositionManager.sol | 6 +- src/interfaces/pool/commons/IPoolEvents.sol | 8 +- src/libraries/external/KickerActions.sol | 26 ++-- src/libraries/external/LPActions.sol | 12 +- src/libraries/external/LenderActions.sol | 140 +++++++++--------- src/libraries/external/SettlerActions.sol | 18 +-- src/libraries/external/TakerActions.sol | 20 +-- src/libraries/helpers/PoolHelper.sol | 14 +- .../unit/ERC20Pool/ERC20PoolInfoUtils.t.sol | 10 +- .../ERC20PoolLiquidationsScaled.t.sol | 42 +++--- .../unit/ERC20Pool/ERC20PoolPrecision.t.sol | 4 +- .../unit/ERC20Pool/ERC20PoolTransferLPs.t.sol | 2 +- tests/forge/unit/PositionManager.t.sol | 8 +- 14 files changed, 159 insertions(+), 159 deletions(-) diff --git a/src/PoolInfoUtils.sol b/src/PoolInfoUtils.sol index f87e39e90..a87dbbb42 100644 --- a/src/PoolInfoUtils.sol +++ b/src/PoolInfoUtils.sol @@ -443,9 +443,9 @@ contract PoolInfoUtils { uint256 index_ ) external view returns (uint256 quoteAmount_) { IPool pool = IPool(ajnaPool_); - (uint256 bucketLPs_, uint256 bucketCollateral , , uint256 bucketDeposit, ) = pool.bucketInfo(index_); + (uint256 bucketLP_, uint256 bucketCollateral , , uint256 bucketDeposit, ) = pool.bucketInfo(index_); quoteAmount_ = _lpToQuoteToken( - bucketLPs_, + bucketLP_, bucketCollateral, bucketDeposit, lp_, @@ -466,10 +466,10 @@ contract PoolInfoUtils { uint256 index_ ) external view returns (uint256 collateralAmount_) { IPool pool = IPool(ajnaPool_); - (uint256 bucketLPs_, uint256 bucketCollateral , , uint256 bucketDeposit, ) = pool.bucketInfo(index_); + (uint256 bucketLP_, uint256 bucketCollateral , , uint256 bucketDeposit, ) = pool.bucketInfo(index_); collateralAmount_ = _lpToCollateral( bucketCollateral, - bucketLPs_, + bucketLP_, bucketDeposit, lp_, _priceAt(index_) diff --git a/src/PositionManager.sol b/src/PositionManager.sol index 9eae95ac5..261fbc146 100644 --- a/src/PositionManager.sol +++ b/src/PositionManager.sol @@ -76,7 +76,7 @@ contract PositionManager is ERC721, PermitERC721, IPositionManager, Multicall, R /// @dev Struct used for `moveLiquidity` function local vars. struct MoveLiquidityLocalVars { - uint256 bucketLPs; // [WAD] amount of LP in from bucket + uint256 bucketLP; // [WAD] amount of LP in from bucket uint256 bucketCollateral; // [WAD] amount of collateral in from bucket uint256 bankruptcyTime; // from bucket bankruptcy time uint256 bucketDeposit; // [WAD] from bucket deposit @@ -275,7 +275,7 @@ contract PositionManager is ERC721, PermitERC721, IPositionManager, Multicall, R // retrieve info of bucket from which liquidity is moved ( - vars.bucketLPs, + vars.bucketLP, vars.bucketCollateral, vars.bankruptcyTime, vars.bucketDeposit, @@ -286,7 +286,7 @@ contract PositionManager is ERC721, PermitERC721, IPositionManager, Multicall, R // calculate the max amount of quote tokens that can be moved, given the tracked LP vars.maxQuote = _lpToQuoteToken( - vars.bucketLPs, + vars.bucketLP, vars.bucketCollateral, vars.bucketDeposit, fromPosition.lps, diff --git a/src/interfaces/pool/commons/IPoolEvents.sol b/src/interfaces/pool/commons/IPoolEvents.sol index 1f8ef2061..e404fdd66 100644 --- a/src/interfaces/pool/commons/IPoolEvents.sol +++ b/src/interfaces/pool/commons/IPoolEvents.sol @@ -200,13 +200,13 @@ interface IPoolEvents { * @notice Emitted when `NFT` auction is completed. * @param borrower Address of borrower that exits auction. * @param collateral Borrower's remaining collateral when auction completed. - * @param lps Amount of `LP` given to the borrower to compensate fractional collateral (if any). + * @param lp Amount of `LP` given to the borrower to compensate fractional collateral (if any). * @param index Index of the bucket with `LP` to compensate fractional collateral. */ event AuctionNFTSettle( address indexed borrower, uint256 collateral, - uint256 lps, + uint256 lp, uint256 index ); @@ -304,13 +304,13 @@ interface IPoolEvents { * @param owner The original owner address of the position. * @param newOwner The new owner address of the position. * @param indexes Array of price bucket indexes at which `LP` were transferred. - * @param lps Amount of `LP` transferred. + * @param lp Amount of `LP` transferred. */ event TransferLP( address owner, address newOwner, uint256[] indexes, - uint256 lps + uint256 lp ); /**************************/ diff --git a/src/libraries/external/KickerActions.sol b/src/libraries/external/KickerActions.sol index 368fd50be..ed516d6cc 100644 --- a/src/libraries/external/KickerActions.sol +++ b/src/libraries/external/KickerActions.sol @@ -68,13 +68,13 @@ library KickerActions { uint256 amountToDebitFromDeposit; // [WAD] the amount of quote tokens used to kick and debited from lender deposit uint256 bucketCollateral; // [WAD] amount of collateral in bucket uint256 bucketDeposit; // [WAD] amount of quote tokens in bucket - uint256 bucketLPs; // [WAD] LP of the bucket + uint256 bucketLP; // [WAD] LP of the bucket uint256 bucketPrice; // [WAD] bucket price uint256 bucketRate; // [WAD] bucket exchange rate uint256 bucketScale; // [WAD] bucket scales uint256 bucketUnscaledDeposit; // [WAD] unscaled amount of quote tokens in bucket - uint256 lenderLPs; // [WAD] LP of lender in bucket - uint256 redeemedLPs; // [WAD] LP used by kick action + uint256 lenderLP; // [WAD] LP of lender in bucket + uint256 redeemedLP; // [WAD] LP used by kick action } /**************/ @@ -153,9 +153,9 @@ library KickerActions { KickWithDepositLocalVars memory vars; - if (bucket.bankruptcyTime < lender.depositTime) vars.lenderLPs = lender.lps; + if (bucket.bankruptcyTime < lender.depositTime) vars.lenderLP = lender.lps; - vars.bucketLPs = bucket.lps; + vars.bucketLP = bucket.lps; vars.bucketCollateral = bucket.collateral; vars.bucketPrice = _priceAt(index_); vars.bucketUnscaledDeposit = Deposits.unscaledValueAt(deposits_, index_); @@ -165,12 +165,12 @@ library KickerActions { // calculate max amount that can be removed (constrained by lender LP in bucket, bucket deposit and the amount lender wants to remove) vars.bucketRate = Buckets.getExchangeRate( vars.bucketCollateral, - vars.bucketLPs, + vars.bucketLP, vars.bucketDeposit, vars.bucketPrice ); - vars.amountToDebitFromDeposit = Maths.wmul(vars.lenderLPs, vars.bucketRate); // calculate amount to remove based on lender LP in bucket + vars.amountToDebitFromDeposit = Maths.wmul(vars.lenderLP, vars.bucketRate); // calculate amount to remove based on lender LP in bucket if (vars.amountToDebitFromDeposit > vars.bucketDeposit) vars.amountToDebitFromDeposit = vars.bucketDeposit; // cap the amount to remove at bucket deposit @@ -203,13 +203,13 @@ library KickerActions { // remove amount from deposits if (vars.amountToDebitFromDeposit == vars.bucketDeposit && vars.bucketCollateral == 0) { - // In this case we are redeeming the entire bucket exactly, and need to ensure bucket LPs are set to 0 - vars.redeemedLPs = vars.bucketLPs; + // In this case we are redeeming the entire bucket exactly, and need to ensure bucket LP are set to 0 + vars.redeemedLP = vars.bucketLP; Deposits.unscaledRemove(deposits_, index_, vars.bucketUnscaledDeposit); } else { - vars.redeemedLPs = Maths.wdiv(vars.amountToDebitFromDeposit, vars.bucketRate); + vars.redeemedLP = Maths.wdiv(vars.amountToDebitFromDeposit, vars.bucketRate); Deposits.unscaledRemove( deposits_, @@ -219,14 +219,14 @@ library KickerActions { } // remove bucket LP coresponding to the amount removed from deposits - lender.lps -= vars.redeemedLPs; - bucket.lps -= vars.redeemedLPs; + lender.lps -= vars.redeemedLP; + bucket.lps -= vars.redeemedLP; emit RemoveQuoteToken( msg.sender, index_, vars.amountToDebitFromDeposit, - vars.redeemedLPs, + vars.redeemedLP, kickResult_.lup ); } diff --git a/src/libraries/external/LPActions.sol b/src/libraries/external/LPActions.sol index a0e523fc5..204691dc0 100644 --- a/src/libraries/external/LPActions.sol +++ b/src/libraries/external/LPActions.sol @@ -25,7 +25,7 @@ library LPActions { event IncreaseLPAllowance(address indexed owner, address indexed spender, uint256[] indexes, uint256[] amounts); event DecreaseLPAllowance(address indexed owner, address indexed spender, uint256[] indexes, uint256[] amounts); event RevokeLPAllowance(address indexed owner, address indexed spender, uint256[] indexes); - event TransferLP(address owner, address newOwner, uint256[] indexes, uint256 lps); + event TransferLP(address owner, address newOwner, uint256[] indexes, uint256 lp); /**************/ /*** Errors ***/ @@ -222,7 +222,7 @@ library LPActions { uint256 indexesLength = indexes_.length; uint256 index; - uint256 lpsTransferred; + uint256 lpTransferred; for (uint256 i = 0; i < indexesLength; ) { index = indexes_[i]; @@ -243,7 +243,7 @@ library LPActions { // transfer allowed amount or entire LP balance allowedAmount = Maths.min(allowedAmount, ownerLpBalance); - // move owner lps (if any) to the new owner + // move owner LP (if any) to the new owner if (allowedAmount != 0) { Lender storage newOwner = bucket.lenders[newOwnerAddress_]; @@ -257,8 +257,8 @@ library LPActions { newOwner.lps = allowedAmount; } - owner.lps -= allowedAmount; // remove amount of LP from old owner - lpsTransferred += allowedAmount; // add amount of LP to total LP transferred + owner.lps -= allowedAmount; // remove amount of LP from old owner + lpTransferred += allowedAmount; // add amount of LP to total LP transferred // set the deposit time as the max of transferred deposit and current deposit time newOwner.depositTime = Maths.max(ownerDepositTime, newOwnerDepositTime); @@ -274,7 +274,7 @@ library LPActions { ownerAddress_, newOwnerAddress_, indexes_, - lpsTransferred + lpTransferred ); } } diff --git a/src/libraries/external/LenderActions.sol b/src/libraries/external/LenderActions.sol index 28a9b214c..c23ec6d56 100644 --- a/src/libraries/external/LenderActions.sol +++ b/src/libraries/external/LenderActions.sol @@ -36,10 +36,10 @@ library LenderActions { struct MoveQuoteLocalVars { uint256 fromBucketPrice; // [WAD] Price of the bucket to move amount from. uint256 fromBucketCollateral; // [WAD] Total amount of collateral in from bucket. - uint256 fromBucketLPs; // [WAD] Total amount of LP in from bucket. - uint256 fromBucketLenderLPs; // [WAD] Amount of LP owned by lender in from bucket. + uint256 fromBucketLP; // [WAD] Total amount of LP in from bucket. + uint256 fromBucketLenderLP; // [WAD] Amount of LP owned by lender in from bucket. uint256 fromBucketDepositTime; // Time of lender deposit in the bucket to move amount from. - uint256 fromBucketRemainingLPs; // Amount of LP remaining in from bucket after move. + uint256 fromBucketRemainingLP; // Amount of LP remaining in from bucket after move. uint256 fromBucketRemainingDeposit; // Amount of scaled deposit remaining in from bucket after move. uint256 toBucketPrice; // [WAD] Price of the bucket to move amount to. uint256 toBucketBankruptcyTime; // Time the bucket to move amount to was marked as insolvent. @@ -55,7 +55,7 @@ library LenderActions { struct RemoveDepositParams { uint256 depositConstraint; // [WAD] Constraint on deposit in quote token. uint256 lpConstraint; // [WAD] Constraint in LPB terms. - uint256 bucketLPs; // [WAD] Total LPB in the bucket. + uint256 bucketLP; // [WAD] Total LPB in the bucket. uint256 bucketCollateral; // [WAD] Claimable collateral in the bucket. uint256 price; // [WAD] Price of bucket. uint256 index; // Bucket index. @@ -107,7 +107,7 @@ library LenderActions { DepositsState storage deposits_, uint256 collateralAmountToAdd_, uint256 index_ - ) external returns (uint256 bucketLPs_) { + ) external returns (uint256 bucketLP_) { // revert if no amount to be added if (collateralAmountToAdd_ == 0) revert InvalidAmount(); // revert if adding at invalid index @@ -116,7 +116,7 @@ library LenderActions { uint256 bucketDeposit = Deposits.valueAt(deposits_, index_); uint256 bucketPrice = _priceAt(index_); - bucketLPs_ = Buckets.addCollateral( + bucketLP_ = Buckets.addCollateral( buckets_[index_], msg.sender, bucketDeposit, @@ -142,7 +142,7 @@ library LenderActions { DepositsState storage deposits_, PoolState calldata poolState_, AddQuoteParams calldata params_ - ) external returns (uint256 bucketLPs_, uint256 lup_) { + ) external returns (uint256 bucketLP_, uint256 lup_) { // revert if no amount to be added if (params_.amount == 0) revert InvalidAmount(); // revert if adding to an invalid index @@ -168,7 +168,7 @@ library LenderActions { addedAmount = Maths.wmul(addedAmount, Maths.WAD - _depositFeeRate(poolState_.rate)); } - bucketLPs_ = Buckets.quoteTokensToLP( + bucketLP_ = Buckets.quoteTokensToLP( bucket.collateral, bucket.lps, bucketDeposit, @@ -179,10 +179,10 @@ library LenderActions { Deposits.unscaledAdd(deposits_, params_.index, Maths.wdiv(addedAmount, bucketScale)); // update lender LP - Buckets.addLenderLP(bucket, bankruptcyTime, msg.sender, bucketLPs_); + Buckets.addLenderLP(bucket, bankruptcyTime, msg.sender, bucketLP_); // update bucket LP - bucket.lps += bucketLPs_; + bucket.lps += bucketLP_; // only need to recalculate LUP if the deposit was above it if (!depositBelowLup) { @@ -194,7 +194,7 @@ library LenderActions { msg.sender, params_.index, addedAmount, - bucketLPs_, + bucketLP_, lup_ ); } @@ -222,7 +222,7 @@ library LenderActions { DepositsState storage deposits_, PoolState calldata poolState_, MoveQuoteParams calldata params_ - ) external returns (uint256 fromBucketRedeemedLPs_, uint256 toBucketLPs_, uint256 movedAmount_, uint256 lup_) { + ) external returns (uint256 fromBucketRedeemedLP_, uint256 toBucketLP_, uint256 movedAmount_, uint256 lup_) { if (params_.maxAmountToMove == 0) revert InvalidAmount(); if (params_.fromIndex == params_.toIndex) @@ -245,19 +245,19 @@ library LenderActions { vars.fromBucketPrice = _priceAt(params_.fromIndex); vars.fromBucketCollateral = fromBucket.collateral; - vars.fromBucketLPs = fromBucket.lps; + vars.fromBucketLP = fromBucket.lps; vars.fromBucketDepositTime = fromBucketLender.depositTime; vars.toBucketPrice = _priceAt(params_.toIndex); - if (fromBucket.bankruptcyTime < vars.fromBucketDepositTime) vars.fromBucketLenderLPs = fromBucketLender.lps; + if (fromBucket.bankruptcyTime < vars.fromBucketDepositTime) vars.fromBucketLenderLP = fromBucketLender.lps; - (movedAmount_, fromBucketRedeemedLPs_, vars.fromBucketRemainingDeposit) = _removeMaxDeposit( + (movedAmount_, fromBucketRedeemedLP_, vars.fromBucketRemainingDeposit) = _removeMaxDeposit( deposits_, RemoveDepositParams({ depositConstraint: params_.maxAmountToMove, - lpConstraint: vars.fromBucketLenderLPs, - bucketLPs: vars.fromBucketLPs, + lpConstraint: vars.fromBucketLenderLP, + bucketLP: vars.fromBucketLP, bucketCollateral: vars.fromBucketCollateral, price: vars.fromBucketPrice, index: params_.fromIndex, @@ -275,7 +275,7 @@ library LenderActions { vars.toBucketScale = Deposits.scale(deposits_, params_.toIndex); vars.toBucketDeposit = Maths.wmul(vars.toBucketUnscaledDeposit, vars.toBucketScale); - toBucketLPs_ = Buckets.quoteTokensToLP( + toBucketLP_ = Buckets.quoteTokensToLP( toBucket.collateral, toBucket.lps, vars.toBucketDeposit, @@ -291,22 +291,22 @@ library LenderActions { if (params_.fromIndex < params_.toIndex && vars.htp > lup_) revert LUPBelowHTP(); // update lender and bucket LP balance in from bucket - vars.fromBucketRemainingLPs = vars.fromBucketLPs - fromBucketRedeemedLPs_; + vars.fromBucketRemainingLP = vars.fromBucketLP - fromBucketRedeemedLP_; // check if from bucket healthy after move quote tokens - set bankruptcy if collateral and deposit are 0 but there's still LP - if (vars.fromBucketCollateral == 0 && vars.fromBucketRemainingDeposit == 0 && vars.fromBucketRemainingLPs != 0) { + if (vars.fromBucketCollateral == 0 && vars.fromBucketRemainingDeposit == 0 && vars.fromBucketRemainingLP != 0) { fromBucket.lps = 0; fromBucket.bankruptcyTime = block.timestamp; emit BucketBankruptcy( params_.fromIndex, - vars.fromBucketRemainingLPs + vars.fromBucketRemainingLP ); } else { // update lender and bucket LP balance - fromBucketLender.lps -= fromBucketRedeemedLPs_; + fromBucketLender.lps -= fromBucketRedeemedLP_; - fromBucket.lps = vars.fromBucketRemainingLPs; + fromBucket.lps = vars.fromBucketRemainingLP; } // update lender and bucket LP balance in target bucket @@ -315,27 +315,27 @@ library LenderActions { vars.toBucketDepositTime = toBucketLender.depositTime; if (vars.toBucketBankruptcyTime >= vars.toBucketDepositTime) { // bucket is bankrupt and deposit was done before bankruptcy time, reset lender lp amount - toBucketLender.lps = toBucketLPs_; + toBucketLender.lps = toBucketLP_; // set deposit time of the lender's to bucket as bucket's last bankruptcy timestamp + 1 so deposit won't get invalidated vars.toBucketDepositTime = vars.toBucketBankruptcyTime + 1; } else { - toBucketLender.lps += toBucketLPs_; + toBucketLender.lps += toBucketLP_; } // set deposit time to the greater of the lender's from bucket and the target bucket toBucketLender.depositTime = Maths.max(vars.fromBucketDepositTime, vars.toBucketDepositTime); // update bucket LP balance - toBucket.lps += toBucketLPs_; + toBucket.lps += toBucketLP_; emit MoveQuoteToken( msg.sender, params_.fromIndex, params_.toIndex, movedAmount_, - fromBucketRedeemedLPs_, - toBucketLPs_, + fromBucketRedeemedLP_, + toBucketLP_, lup_ ); } @@ -359,7 +359,7 @@ library LenderActions { DepositsState storage deposits_, PoolState calldata poolState_, RemoveQuoteParams calldata params_ - ) external returns (uint256 removedAmount_, uint256 redeemedLPs_, uint256 lup_) { + ) external returns (uint256 removedAmount_, uint256 redeemedLP_, uint256 lup_) { // revert if no amount to be removed if (params_.maxAmount == 0) revert InvalidAmount(); @@ -376,13 +376,13 @@ library LenderActions { removeParams.depositConstraint = params_.maxAmount; removeParams.price = _priceAt(params_.index); - removeParams.bucketLPs = bucket.lps; + removeParams.bucketLP = bucket.lps; removeParams.bucketCollateral = bucket.collateral; removeParams.index = params_.index; removeParams.dustLimit = poolState_.quoteDustLimit; uint256 unscaledRemaining; - (removedAmount_, redeemedLPs_, unscaledRemaining) = _removeMaxDeposit( + (removedAmount_, redeemedLP_, unscaledRemaining) = _removeMaxDeposit( deposits_, removeParams ); @@ -400,29 +400,29 @@ library LenderActions { (poolState_.debt != 0 && poolState_.debt > Deposits.treeSum(deposits_)) ) revert LUPBelowHTP(); - uint256 lpsRemaining = removeParams.bucketLPs - redeemedLPs_; + uint256 lpRemaining = removeParams.bucketLP - redeemedLP_; // check if bucket healthy after remove quote tokens - set bankruptcy if collateral and deposit are 0 but there's still LP - if (removeParams.bucketCollateral == 0 && unscaledRemaining == 0 && lpsRemaining != 0) { + if (removeParams.bucketCollateral == 0 && unscaledRemaining == 0 && lpRemaining != 0) { bucket.lps = 0; bucket.bankruptcyTime = block.timestamp; emit BucketBankruptcy( params_.index, - lpsRemaining + lpRemaining ); } else { // update lender and bucket LP balances - lender.lps -= redeemedLPs_; + lender.lps -= redeemedLP_; - bucket.lps = lpsRemaining; + bucket.lps = lpRemaining; } emit RemoveQuoteToken( msg.sender, params_.index, removedAmount_, - redeemedLPs_, + redeemedLP_, lup_ ); } @@ -454,12 +454,12 @@ library LenderActions { if (amount_ > bucketCollateral) revert InsufficientCollateral(); uint256 bucketPrice = _priceAt(index_); - uint256 bucketLPs = bucket.lps; + uint256 bucketLP = bucket.lps; uint256 bucketDeposit = Deposits.valueAt(deposits_, index_); lpAmount_ = Buckets.collateralToLP( bucketCollateral, - bucketLPs, + bucketLP, bucketDeposit, amount_, bucketPrice @@ -472,10 +472,10 @@ library LenderActions { if (lenderLpBalance == 0 || lpAmount_ > lenderLpBalance) revert InsufficientLP(); // update bucket LP and collateral balance - bucketLPs -= lpAmount_; + bucketLP -= lpAmount_; // If clearing out the bucket collateral, ensure it's zeroed out - if (bucketLPs == 0 && bucketDeposit == 0) { + if (bucketLP == 0 && bucketDeposit == 0) { amount_ = bucketCollateral; } @@ -483,19 +483,19 @@ library LenderActions { bucket.collateral = bucketCollateral; // check if bucket healthy after collateral remove - set bankruptcy if collateral and deposit are 0 but there's still LP - if (bucketCollateral == 0 && bucketDeposit == 0 && bucketLPs != 0) { + if (bucketCollateral == 0 && bucketDeposit == 0 && bucketLP != 0) { bucket.lps = 0; bucket.bankruptcyTime = block.timestamp; emit BucketBankruptcy( index_, - bucketLPs + bucketLP ); } else { // update lender LP balance lender.lps -= lpAmount_; - bucket.lps = bucketLPs; + bucket.lps = bucketLP; } } @@ -543,7 +543,7 @@ library LenderActions { uint256[] calldata removalIndexes_, uint256 collateralAmount_, uint256 toIndex_ - ) external returns (uint256 collateralToMerge_, uint256 bucketLPs_) { + ) external returns (uint256 collateralToMerge_, uint256 bucketLP_) { uint256 i; uint256 fromIndex; uint256 collateralRemoved; @@ -575,7 +575,7 @@ library LenderActions { uint256 toBucketDeposit = Deposits.valueAt(deposits_, toIndex_); uint256 toBucketPrice = _priceAt(toIndex_); - bucketLPs_ = Buckets.addCollateral( + bucketLP_ = Buckets.addCollateral( buckets_[toIndex_], msg.sender, toBucketDeposit, @@ -600,7 +600,7 @@ library LenderActions { * @dev === Emit events === * @dev - `BucketBankruptcy` * @return collateralAmount_ Amount of collateral that was removed. - * @return lpAmount_ Amount of LPs redeemed for removed collateral amount. + * @return lpAmount_ Amount of `LP` redeemed for removed collateral amount. */ function _removeMaxCollateral( mapping(uint256 => Bucket) storage buckets_, @@ -621,37 +621,37 @@ library LenderActions { if (lenderLpBalance == 0) revert NoClaim(); // revert if no LP to redeem uint256 bucketPrice = _priceAt(index_); - uint256 bucketLPs = bucket.lps; + uint256 bucketLP = bucket.lps; uint256 bucketDeposit = Deposits.valueAt(deposits_, index_); // limit amount by what is available in the bucket collateralAmount_ = Maths.min(maxAmount_, bucketCollateral); // determine how much LP would be required to remove the requested amount - uint256 requiredLPs = Buckets.collateralToLP( + uint256 requiredLP = Buckets.collateralToLP( bucketCollateral, - bucketLPs, + bucketLP, bucketDeposit, collateralAmount_, bucketPrice ); // limit withdrawal by the lender's LPB - if (requiredLPs <= lenderLpBalance) { + if (requiredLP <= lenderLpBalance) { // withdraw collateralAmount_ as is - lpAmount_ = requiredLPs; + lpAmount_ = requiredLP; } else { lpAmount_ = lenderLpBalance; - collateralAmount_ = Maths.wdiv(Maths.wmul(lenderLpBalance, collateralAmount_), requiredLPs); + collateralAmount_ = Maths.wdiv(Maths.wmul(lenderLpBalance, collateralAmount_), requiredLP); if (collateralAmount_ == 0) revert InsufficientLP(); } - // update bucket LPs and collateral balance - bucketLPs -= Maths.min(bucketLPs, lpAmount_); + // update bucket LP and collateral balance + bucketLP -= Maths.min(bucketLP, lpAmount_); // If clearing out the bucket collateral, ensure it's zeroed out - if (bucketLPs == 0 && bucketDeposit == 0) { + if (bucketLP == 0 && bucketDeposit == 0) { collateralAmount_ = bucketCollateral; } @@ -659,19 +659,19 @@ library LenderActions { bucket.collateral = bucketCollateral; // check if bucket healthy after collateral remove - set bankruptcy if collateral and deposit are 0 but there's still LP - if (bucketCollateral == 0 && bucketDeposit == 0 && bucketLPs != 0) { + if (bucketCollateral == 0 && bucketDeposit == 0 && bucketLP != 0) { bucket.lps = 0; bucket.bankruptcyTime = block.timestamp; emit BucketBankruptcy( index_, - bucketLPs + bucketLP ); } else { // update lender LP balance lender.lps -= lpAmount_; - bucket.lps = bucketLPs; + bucket.lps = bucketLP; } } @@ -681,13 +681,13 @@ library LenderActions { * @dev - `Deposits.unscaledRemove` (remove amount in `Fenwick` tree, from index): * @dev update `values` array state * @return removedAmount_ Amount of scaled deposit removed. - * @return redeemedLPs_ Amount of bucket LP corresponding for calculated scaled deposit amount. + * @return redeemedLP_ Amount of bucket `LP` corresponding for calculated scaled deposit amount. * @return unscaledRemaining_ Amount of unscaled deposit remaining. */ function _removeMaxDeposit( DepositsState storage deposits_, RemoveDepositParams memory params_ - ) internal returns (uint256 removedAmount_, uint256 redeemedLPs_, uint256 unscaledRemaining_) { + ) internal returns (uint256 removedAmount_, uint256 redeemedLP_, uint256 unscaledRemaining_) { uint256 unscaledDepositAvailable = Deposits.unscaledValueAt(deposits_, params_.index); if (unscaledDepositAvailable == 0) revert InsufficientLiquidity(); // revert if there's no liquidity available to remove @@ -698,7 +698,7 @@ library LenderActions { uint256 exchangeRate = Buckets.getExchangeRate( params_.bucketCollateral, - params_.bucketLPs, + params_.bucketLP, scaledDepositAvailable, params_.price ); @@ -706,8 +706,8 @@ library LenderActions { // Below is pseudocode explaining the logic behind finding the constrained amount of deposit and LPB // scaledRemovedAmount is constrained by the scaled maxAmount(in QT), the scaledDeposit constraint, and // the lender LPB exchange rate in scaled deposit-to-LPB for the bucket: - // scaledRemovedAmount = min ( maxAmount_, scaledDeposit, lenderLPsBalance*exchangeRate) - // redeemedLPs_ = min ( maxAmount_/scaledExchangeRate, scaledDeposit/exchangeRate, lenderLPsBalance) + // scaledRemovedAmount = min ( maxAmount_, scaledDeposit, lenderLPBalance*exchangeRate) + // redeemedLP_ = min ( maxAmount_/scaledExchangeRate, scaledDeposit/exchangeRate, lenderLPBalance) uint256 scaledLpConstraint = Maths.wmul(params_.lpConstraint, exchangeRate); if ( @@ -716,19 +716,19 @@ library LenderActions { ) { // depositConstraint is binding constraint removedAmount_ = params_.depositConstraint; - redeemedLPs_ = Maths.wdiv(removedAmount_, exchangeRate); + redeemedLP_ = Maths.wdiv(removedAmount_, exchangeRate); } else if (scaledDepositAvailable < scaledLpConstraint) { // scaledDeposit is binding constraint removedAmount_ = scaledDepositAvailable; - redeemedLPs_ = Maths.wdiv(removedAmount_, exchangeRate); + redeemedLP_ = Maths.wdiv(removedAmount_, exchangeRate); } else { - // redeeming all LPs - redeemedLPs_ = params_.lpConstraint; - removedAmount_ = Maths.wmul(redeemedLPs_, exchangeRate); + // redeeming all LP + redeemedLP_ = params_.lpConstraint; + removedAmount_ = Maths.wmul(redeemedLP_, exchangeRate); } // If clearing out the bucket deposit, ensure it's zeroed out - if (redeemedLPs_ == params_.bucketLPs) { + if (redeemedLP_ == params_.bucketLP) { removedAmount_ = scaledDepositAvailable; } diff --git a/src/libraries/external/SettlerActions.sol b/src/libraries/external/SettlerActions.sol index 2e262de00..ec7933571 100644 --- a/src/libraries/external/SettlerActions.sol +++ b/src/libraries/external/SettlerActions.sol @@ -51,7 +51,7 @@ library SettlerActions { uint256 depositToRemove; // [WAD] deposit used by settle auction uint256 hpbCollateral; // [WAD] amount of collateral in HPB bucket uint256 hpbUnscaledDeposit; // [WAD] unscaled amount of of quote tokens in HPB bucket before settle - uint256 hpbLPs; // [WAD] amount of LP in HPB bucket + uint256 hpbLP; // [WAD] amount of LP in HPB bucket uint256 index; // index of settling bucket uint256 maxSettleableDebt; // [WAD] max amount that can be settled with existing collateral uint256 price; // [WAD] price of settling bucket @@ -66,7 +66,7 @@ library SettlerActions { // See `IPoolEvents` for descriptions event AuctionSettle(address indexed borrower, uint256 collateral); - event AuctionNFTSettle(address indexed borrower, uint256 collateral, uint256 lps, uint256 index); + event AuctionNFTSettle(address indexed borrower, uint256 collateral, uint256 lp, uint256 index); event BucketBankruptcy(uint256 indexed index, uint256 lpForfeited); event Settle(address indexed borrower, uint256 settledDebt); @@ -161,7 +161,7 @@ library SettlerActions { borrower.collateral -= vars.collateralUsed; Bucket storage hpb = buckets_[vars.index]; - vars.hpbLPs = hpb.lps; + vars.hpbLP = hpb.lps; vars.hpbCollateral = hpb.collateral + vars.collateralUsed; // set amount to remove as min of calculated amount and available deposit (to prevent rounding issues) @@ -171,14 +171,14 @@ library SettlerActions { // remove amount to settle debt from bucket (could be entire deposit or only the settled debt) Deposits.unscaledRemove(deposits_, vars.index, vars.unscaledDeposit); - // check if bucket healthy - set bankruptcy if collateral is 0 and entire deposit was used to settle and there's still LPs - if (vars.hpbCollateral == 0 && vars.hpbUnscaledDeposit == 0 && vars.hpbLPs != 0) { + // check if bucket healthy - set bankruptcy if collateral is 0 and entire deposit was used to settle and there's still LP + if (vars.hpbCollateral == 0 && vars.hpbUnscaledDeposit == 0 && vars.hpbLP != 0) { hpb.lps = 0; hpb.bankruptcyTime = block.timestamp; emit BucketBankruptcy( vars.index, - vars.hpbLPs + vars.hpbLP ); } else { // add settled collateral into bucket @@ -302,7 +302,7 @@ library SettlerActions { ) internal returns (uint256 remainingCollateral_, uint256 compensatedCollateral_) { if (poolType_ == uint8(PoolType.ERC721)) { - uint256 lps; + uint256 lp; uint256 bucketIndex; remainingCollateral_ = (borrowerCollateral_ / Maths.WAD) * Maths.WAD; // floor collateral of borrower @@ -323,7 +323,7 @@ library SettlerActions { bucketIndex = auctionPrice > MIN_PRICE ? _indexOf(auctionPrice) : MAX_FENWICK_INDEX; // deposit collateral in bucket and reward LP to compensate fractional collateral - lps = Buckets.addCollateral( + lp = Buckets.addCollateral( buckets_[bucketIndex], borrowerAddress_, Deposits.valueAt(deposits_, bucketIndex), @@ -335,7 +335,7 @@ library SettlerActions { emit AuctionNFTSettle( borrowerAddress_, remainingCollateral_, - lps, + lp, bucketIndex ); diff --git a/src/libraries/external/TakerActions.sol b/src/libraries/external/TakerActions.sol index 19934e8b0..eb59d6705 100644 --- a/src/libraries/external/TakerActions.sol +++ b/src/libraries/external/TakerActions.sol @@ -619,25 +619,25 @@ library TakerActions { ); uint256 bankruptcyTime = bucket.bankruptcyTime; - uint256 totalLPsReward; + uint256 totalLPReward; // if arb take - taker is awarded collateral * (bucket price - auction price) worth (in quote token terms) units of LPB in the bucket if (!depositTake_) { uint256 takerReward = Maths.wmul(vars.collateralAmount, vars.bucketPrice - vars.auctionPrice); - totalLPsReward = Maths.wdiv(takerReward, exchangeRate); + totalLPReward = Maths.wdiv(takerReward, exchangeRate); - Buckets.addLenderLP(bucket, bankruptcyTime, msg.sender, totalLPsReward); + Buckets.addLenderLP(bucket, bankruptcyTime, msg.sender, totalLPReward); } - uint256 kickerLPsReward; + uint256 kickerLPReward; // the bondholder/kicker is awarded bond change worth of LPB in the bucket if (vars.isRewarded) { - kickerLPsReward = Maths.wdiv(vars.bondChange, exchangeRate); - totalLPsReward += kickerLPsReward; + kickerLPReward = Maths.wdiv(vars.bondChange, exchangeRate); + totalLPReward += kickerLPReward; - Buckets.addLenderLP(bucket, bankruptcyTime, vars.kicker, kickerLPsReward); + Buckets.addLenderLP(bucket, bankruptcyTime, vars.kicker, kickerLPReward); } else { // take is above neutralPrice, Kicker is penalized vars.bondChange = Maths.min(liquidation_.bondSize, vars.bondChange); @@ -651,7 +651,7 @@ library TakerActions { Deposits.unscaledRemove(deposits_, bucketIndex_, vars.unscaledQuoteTokenAmount); // remove quote tokens from bucket’s deposit // total rewarded LP are added to the bucket LP balance - bucket.lps += totalLPsReward; + bucket.lps += totalLPReward; // collateral is added to the bucket’s claimable collateral bucket.collateral += vars.collateralAmount; @@ -659,8 +659,8 @@ library TakerActions { emit BucketTakeLPAwarded( msg.sender, vars.kicker, - totalLPsReward - kickerLPsReward, - kickerLPsReward + totalLPReward - kickerLPReward, + kickerLPReward ); } diff --git a/src/libraries/helpers/PoolHelper.sol b/src/libraries/helpers/PoolHelper.sol index d526896bc..3125d365b 100644 --- a/src/libraries/helpers/PoolHelper.sol +++ b/src/libraries/helpers/PoolHelper.sol @@ -187,7 +187,7 @@ import { Maths } from '../internal/Maths.sol'; * @param bucketCollateral_ Amount of collateral in bucket. * @param bucketLP_ Amount of `LP` in bucket. * @param deposit_ Current bucket deposit (quote tokens). Used to calculate bucket's exchange rate / `LP`. - * @param lenderLPsBalance_ The amount of LP to calculate collateral for. + * @param lenderLPBalance_ The amount of `LP` to calculate collateral for. * @param bucketPrice_ Bucket's price. * @return collateralAmount_ Amount of collateral calculated for the given `LP `amount. */ @@ -195,13 +195,13 @@ import { Maths } from '../internal/Maths.sol'; uint256 bucketCollateral_, uint256 bucketLP_, uint256 deposit_, - uint256 lenderLPsBalance_, + uint256 lenderLPBalance_, uint256 bucketPrice_ ) pure returns (uint256 collateralAmount_) { - // max collateral to lps + // max collateral to lp uint256 rate = Buckets.getExchangeRate(bucketCollateral_, bucketLP_, deposit_, bucketPrice_); - collateralAmount_ = Maths.wdiv(Maths.wmul(lenderLPsBalance_, rate), bucketPrice_); + collateralAmount_ = Maths.wdiv(Maths.wmul(lenderLPBalance_, rate), bucketPrice_); if (collateralAmount_ > bucketCollateral_) { // user is owed more collateral than is available in the bucket @@ -214,7 +214,7 @@ import { Maths } from '../internal/Maths.sol'; * @param bucketLP_ Amount of `LP` in bucket. * @param bucketCollateral_ Amount of collateral in bucket. * @param deposit_ Current bucket deposit (quote tokens). Used to calculate bucket's exchange rate / `LP`. - * @param lenderLPsBalance_ The amount of `LP` to calculate quote token amount for. + * @param lenderLPBalance_ The amount of `LP` to calculate quote token amount for. * @param maxQuoteToken_ The max quote token amount to calculate `LP` for. * @param bucketPrice_ Bucket's price. * @return quoteTokenAmount_ Amount of quote tokens calculated for the given `LP` amount. @@ -223,13 +223,13 @@ import { Maths } from '../internal/Maths.sol'; uint256 bucketLP_, uint256 bucketCollateral_, uint256 deposit_, - uint256 lenderLPsBalance_, + uint256 lenderLPBalance_, uint256 maxQuoteToken_, uint256 bucketPrice_ ) pure returns (uint256 quoteTokenAmount_) { uint256 rate = Buckets.getExchangeRate(bucketCollateral_, bucketLP_, deposit_, bucketPrice_); - quoteTokenAmount_ = Maths.wmul(lenderLPsBalance_, rate); + quoteTokenAmount_ = Maths.wmul(lenderLPBalance_, rate); if (quoteTokenAmount_ > deposit_) quoteTokenAmount_ = deposit_; if (quoteTokenAmount_ > maxQuoteToken_) quoteTokenAmount_ = maxQuoteToken_; diff --git a/tests/forge/unit/ERC20Pool/ERC20PoolInfoUtils.t.sol b/tests/forge/unit/ERC20Pool/ERC20PoolInfoUtils.t.sol index bd0d09337..ebd6ab799 100644 --- a/tests/forge/unit/ERC20Pool/ERC20PoolInfoUtils.t.sol +++ b/tests/forge/unit/ERC20Pool/ERC20PoolInfoUtils.t.sol @@ -101,7 +101,7 @@ contract ERC20PoolInfoUtilsTest is ERC20HelperContract { uint256 price, uint256 quoteTokens, uint256 collateral, - uint256 bucketLPs, + uint256 bucketLP, uint256 scale, uint256 exchangeRate ) = _poolUtils.bucketInfo(address(_pool), 5000); @@ -109,7 +109,7 @@ contract ERC20PoolInfoUtilsTest is ERC20HelperContract { assertEq(price, 0.014854015662334135 * 1e18); assertEq(quoteTokens, 0); assertEq(collateral, 0); - assertEq(bucketLPs, 0); + assertEq(bucketLP, 0); assertEq(scale, 1 * 1e18); assertEq(exchangeRate, 1 * 1e18); @@ -117,14 +117,14 @@ contract ERC20PoolInfoUtilsTest is ERC20HelperContract { price, quoteTokens, collateral, - bucketLPs, + bucketLP, scale, exchangeRate ) = _poolUtils.bucketInfo(address(_pool), high); assertEq(price, 2_995.912459898389633881 * 1e18); assertEq(quoteTokens, 10_000 * 1e18); assertEq(collateral, 0); - assertEq(bucketLPs, 10_000 * 1e18); + assertEq(bucketLP, 10_000 * 1e18); assertEq(scale, 1 * 1e18); assertEq(exchangeRate, 1 * 1e18); } @@ -227,7 +227,7 @@ contract ERC20PoolInfoUtilsTest is ERC20HelperContract { assertEq(_poolUtils.unutilizedDepositFeeRate(address(_pool)), 0.000136986301369863 * 1e18); } - function testPoolInfoUtilsLPsToCollateralAndQuote() external { + function testPoolInfoUtilsLPToCollateralAndQuote() external { assertEq( _poolUtils.lpToCollateral( address(_pool), diff --git a/tests/forge/unit/ERC20Pool/ERC20PoolLiquidationsScaled.t.sol b/tests/forge/unit/ERC20Pool/ERC20PoolLiquidationsScaled.t.sol index c2bfed467..9d42ca489 100644 --- a/tests/forge/unit/ERC20Pool/ERC20PoolLiquidationsScaled.t.sol +++ b/tests/forge/unit/ERC20Pool/ERC20PoolLiquidationsScaled.t.sol @@ -266,21 +266,21 @@ contract ERC20PoolLiquidationsScaledTest is ERC20DSTestPlus { } function _kickWithDeposit(address lender, uint256 bucketId) internal { - (uint256 lastLenderLPs, ) = _pool.lenderInfo(bucketId, lender); - (, uint256 lastBucketDeposit, , uint256 lastBucketLPs, , ) = _poolUtils.bucketInfo(address(_pool), bucketId); + (uint256 lastLenderLP, ) = _pool.lenderInfo(bucketId, lender); + (, uint256 lastBucketDeposit, , uint256 lastBucketLP, , ) = _poolUtils.bucketInfo(address(_pool), bucketId); changePrank(lender); _pool.kickWithDeposit(bucketId, MAX_FENWICK_INDEX); _checkAuctionStateUponKick(lender); - // confirm user has redeemed some of their LPs to post liquidation bond - (uint256 lenderLPs, ) = _pool.lenderInfo(bucketId, lender); - assertLt(lenderLPs, lastLenderLPs); + // confirm user has redeemed some of their LP to post liquidation bond + (uint256 lenderLP, ) = _pool.lenderInfo(bucketId, lender); + assertLt(lenderLP, lastLenderLP); // confirm deposit has been removed from bucket - (, uint256 bucketDeposit, , uint256 bucketLPs, , ) = _poolUtils.bucketInfo(address(_pool), bucketId); + (, uint256 bucketDeposit, , uint256 bucketLP, , ) = _poolUtils.bucketInfo(address(_pool), bucketId); assertLt(bucketDeposit, lastBucketDeposit); - assertLt(bucketLPs, lastBucketLPs); + assertLt(bucketLP, lastBucketLP); } function _checkAuctionStateUponKick(address kicker) internal { @@ -326,15 +326,15 @@ contract ERC20PoolLiquidationsScaledTest is ERC20DSTestPlus { (uint256 lastAuctionDebt, uint256 lastAuctionCollateral, ) = _poolUtils.borrowerInfo(address(_pool), _borrower); assertGt(lastAuctionDebt, 0); assertGt(lastAuctionCollateral, 0); - (, uint256 lastBucketDeposit, uint256 lastBucketCollateral, uint256 lastBucketLPs, , ) = _poolUtils.bucketInfo(address(_pool), bucketId); - uint256 lastKickerLPs = _kickerLP(bucketId); + (, uint256 lastBucketDeposit, uint256 lastBucketCollateral, uint256 lastBucketLP, , ) = _poolUtils.bucketInfo(address(_pool), bucketId); + uint256 lastKickerLP = _kickerLP(bucketId); assertGt(lastAuctionDebt, 0); assertGt(lastAuctionCollateral, 0); _pool.bucketTake(_borrower, true, bucketId); // confirm auction debt and collateral have decremented - uint256 bucketLPs; + uint256 bucketLP; { (uint256 auctionDebt, uint256 auctionCollateral, ) = _poolUtils.borrowerInfo(address(_pool), _borrower); assertLt(auctionDebt, lastAuctionDebt); @@ -344,7 +344,7 @@ contract ERC20PoolLiquidationsScaledTest is ERC20DSTestPlus { // confirm bucket deposit was exchanged for collateral uint256 bucketDeposit; uint256 bucketCollateral; - (, bucketDeposit, bucketCollateral, bucketLPs, , ) = _poolUtils.bucketInfo(address(_pool), bucketId); + (, bucketDeposit, bucketCollateral, bucketLP, , ) = _poolUtils.bucketInfo(address(_pool), bucketId); assertLt(bucketDeposit, lastBucketDeposit); assertEq(bucketCollateral, lastBucketCollateral + collateralTaken); } @@ -353,10 +353,10 @@ contract ERC20PoolLiquidationsScaledTest is ERC20DSTestPlus { (address kicker, , , uint256 kickTime, uint256 kickMomp, uint256 neutralPrice, , , , ) = _pool.auctionInfo(_borrower); uint256 auctionPrice = _auctionPrice(kickMomp, neutralPrice, kickTime); if (auctionPrice < neutralPrice) { - uint256 kickerLPs = _kickerLP(bucketId); - assertGt(kickerLPs, lastKickerLPs); - uint256 kickerLpChange = kickerLPs - lastKickerLPs; - assertEq(bucketLPs, lastBucketLPs + kickerLpChange); + uint256 kickerLP = _kickerLP(bucketId); + assertGt(kickerLP, lastKickerLP); + uint256 kickerLpChange = kickerLP - lastKickerLP; + assertEq(bucketLP, lastBucketLP + kickerLpChange); } // Add for tearDown @@ -370,7 +370,7 @@ contract ERC20PoolLiquidationsScaledTest is ERC20DSTestPlus { assertGt(lastAuctionDebt, 0); assertGt(lastAuctionCollateral, 0); (, uint256 lastBucketDeposit, uint256 lastBucketCollateral, , , ) = _poolUtils.bucketInfo(address(_pool), bucketId); - (uint256 lastBidderLPs, ) = _pool.lenderInfo(bucketId, bidder); + (uint256 lastBidderLP, ) = _pool.lenderInfo(bucketId, bidder); uint256 lastBidderQuoteBalance = _quote.balanceOf(bidder); changePrank(bidder); @@ -382,10 +382,10 @@ contract ERC20PoolLiquidationsScaledTest is ERC20DSTestPlus { assertLt(auctionCollateral, lastAuctionCollateral); uint256 collateralTaken = lastAuctionCollateral - auctionCollateral; - // confirm bidder was awarded LPs without spending any quote token + // confirm bidder was awarded LP without spending any quote token { - (uint256 bidderLPs, ) = _pool.lenderInfo(bucketId, bidder); - assertGt(bidderLPs, lastBidderLPs); + (uint256 bidderLP, ) = _pool.lenderInfo(bucketId, bidder); + assertGt(bidderLP, lastBidderLP); assertEq(_quote.balanceOf(bidder), lastBidderQuoteBalance); } @@ -448,7 +448,7 @@ contract ERC20PoolLiquidationsScaledTest is ERC20DSTestPlus { function _kickerLP(uint256 bucketId) internal view returns (uint256) { (address kicker, , , , , , , , , ) = _pool.auctionInfo(_borrower); - (uint256 kickerLPs, ) = _pool.lenderInfo(bucketId, kicker); - return kickerLPs; + (uint256 kickerLP, ) = _pool.lenderInfo(bucketId, kicker); + return kickerLP; } } diff --git a/tests/forge/unit/ERC20Pool/ERC20PoolPrecision.t.sol b/tests/forge/unit/ERC20Pool/ERC20PoolPrecision.t.sol index ada3d5b55..cc963ce0b 100644 --- a/tests/forge/unit/ERC20Pool/ERC20PoolPrecision.t.sol +++ b/tests/forge/unit/ERC20Pool/ERC20PoolPrecision.t.sol @@ -551,9 +551,9 @@ contract ERC20PoolPrecisionTest is ERC20DSTestPlus { // check bucket uint256 quoteScale = _pool.quoteTokenScale(); - (, uint256 curDeposit, , uint256 bucketLPs,,) = _poolUtils.bucketInfo(address(_pool), bucketId); + (, uint256 curDeposit, , uint256 bucketLP,,) = _poolUtils.bucketInfo(address(_pool), bucketId); assertEq(curDeposit, _roundToScale(quoteAmount1, quoteScale) + _roundToScale(quoteAmount2, quoteScale)); - assertEq(bucketLPs, lpBalance1 + lpBalance2); + assertEq(bucketLP, lpBalance1 + lpBalance2); } function testMoveQuoteToken( diff --git a/tests/forge/unit/ERC20Pool/ERC20PoolTransferLPs.t.sol b/tests/forge/unit/ERC20Pool/ERC20PoolTransferLPs.t.sol index 1a403d726..d0bc50a5f 100644 --- a/tests/forge/unit/ERC20Pool/ERC20PoolTransferLPs.t.sol +++ b/tests/forge/unit/ERC20Pool/ERC20PoolTransferLPs.t.sol @@ -186,7 +186,7 @@ contract ERC20PoolTransferLPTest is ERC20HelperContract { }); } - function testIncreaseDecreaseLPsWithInvalidInput() external tearDown { + function testIncreaseDecreaseLPWithInvalidInput() external tearDown { uint256[] memory indexes = new uint256[](3); indexes[0] = 2550; indexes[1] = 2551; diff --git a/tests/forge/unit/PositionManager.t.sol b/tests/forge/unit/PositionManager.t.sol index b6d25ac21..72833270e 100644 --- a/tests/forge/unit/PositionManager.t.sol +++ b/tests/forge/unit/PositionManager.t.sol @@ -178,12 +178,12 @@ contract PositionManagerERC20PoolTest is PositionManagerERC20PoolHelperContract _positionManager.memorializePositions(memorializeParams); // check memorialization success - uint256 positionAtPriceOneLPs = _positionManager.getLP(tokenId, indexes[0]); - assertGt(positionAtPriceOneLPs, 0); + uint256 positionAtPriceOneLP = _positionManager.getLP(tokenId, indexes[0]); + assertGt(positionAtPriceOneLP, 0); // check lps at non added to price - uint256 positionAtWrongPriceLPs = _positionManager.getLP(tokenId, uint256(MAX_BUCKET_INDEX)); - assertEq(positionAtWrongPriceLPs, 0); + uint256 positionAtWrongPriceLP = _positionManager.getLP(tokenId, uint256(MAX_BUCKET_INDEX)); + assertEq(positionAtWrongPriceLP, 0); assertTrue(_positionManager.isIndexInPosition(tokenId, 2550)); assertTrue(_positionManager.isIndexInPosition(tokenId, 2551)); From eb49affb5820295a0b7397702dea863337241218 Mon Sep 17 00:00:00 2001 From: grandizzy Date: Thu, 20 Apr 2023 10:09:17 +0300 Subject: [PATCH 09/11] Update SettlerActions LPs to LP --- src/libraries/external/SettlerActions.sol | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/libraries/external/SettlerActions.sol b/src/libraries/external/SettlerActions.sol index 0595e93ab..2075d668d 100644 --- a/src/libraries/external/SettlerActions.sol +++ b/src/libraries/external/SettlerActions.sol @@ -50,7 +50,7 @@ library SettlerActions { uint256 debt; // [WAD] debt to settle uint256 hpbCollateral; // [WAD] amount of collateral in HPB bucket uint256 hpbUnscaledDeposit; // [WAD] unscaled amount of of quote tokens in HPB bucket before settle - uint256 hpbLPs; // [WAD] amount of LP in HPB bucket + uint256 hpbLP; // [WAD] amount of LP in HPB bucket uint256 index; // index of settling bucket uint256 maxSettleableDebt; // [WAD] max amount that can be settled with existing collateral uint256 price; // [WAD] price of settling bucket @@ -65,7 +65,7 @@ library SettlerActions { // See `IPoolEvents` for descriptions event AuctionSettle(address indexed borrower, uint256 collateral); - event AuctionNFTSettle(address indexed borrower, uint256 collateral, uint256 lps, uint256 index); + event AuctionNFTSettle(address indexed borrower, uint256 collateral, uint256 lp, uint256 index); event BucketBankruptcy(uint256 indexed index, uint256 lpForfeited); event Settle(address indexed borrower, uint256 settledDebt); @@ -206,7 +206,7 @@ library SettlerActions { ) internal returns (uint256 remainingCollateral_, uint256 compensatedCollateral_) { if (poolType_ == uint8(PoolType.ERC721)) { - uint256 lps; + uint256 lp; uint256 bucketIndex; remainingCollateral_ = (borrowerCollateral_ / Maths.WAD) * Maths.WAD; // floor collateral of borrower @@ -227,7 +227,7 @@ library SettlerActions { bucketIndex = auctionPrice > MIN_PRICE ? _indexOf(auctionPrice) : MAX_FENWICK_INDEX; // deposit collateral in bucket and reward LP to compensate fractional collateral - lps = Buckets.addCollateral( + lp = Buckets.addCollateral( buckets_[bucketIndex], borrowerAddress_, Deposits.valueAt(deposits_, bucketIndex), @@ -239,7 +239,7 @@ library SettlerActions { emit AuctionNFTSettle( borrowerAddress_, remainingCollateral_, - lps, + lp, bucketIndex ); @@ -305,7 +305,7 @@ library SettlerActions { } /** - * @notice Called to settle debt using `HPB` deposits. + * @notice Called to settle debt using `HPB` deposits, up to the number of specified buckets depth. * @dev === Write state === * @dev - `Deposits.unscaledRemove()` (remove amount in `Fenwick` tree, from index): * @dev update `values` array state @@ -376,7 +376,7 @@ library SettlerActions { // use HPB bucket to swap loan collateral for loan debt Bucket storage hpb = buckets_[vars.index]; - vars.hpbLPs = hpb.lps; + vars.hpbLP = hpb.lps; vars.hpbCollateral = hpb.collateral + vars.collateralUsed; // set amount to remove as min of calculated amount and available deposit (to prevent rounding issues) @@ -386,14 +386,14 @@ library SettlerActions { // remove amount to settle debt from bucket (could be entire deposit or only the settled debt) Deposits.unscaledRemove(deposits_, vars.index, vars.unscaledDeposit); - // check if bucket healthy - set bankruptcy if collateral is 0 and entire deposit was used to settle and there's still LPs - if (vars.hpbCollateral == 0 && vars.hpbUnscaledDeposit == 0 && vars.hpbLPs != 0) { + // check if bucket healthy - set bankruptcy if collateral is 0 and entire deposit was used to settle and there's still LP + if (vars.hpbCollateral == 0 && vars.hpbUnscaledDeposit == 0 && vars.hpbLP != 0) { hpb.lps = 0; hpb.bankruptcyTime = block.timestamp; emit BucketBankruptcy( vars.index, - vars.hpbLPs + vars.hpbLP ); } else { // add settled collateral into bucket @@ -418,7 +418,7 @@ library SettlerActions { } /** - * @notice Called to forgive bad debt starting from next `HPB`. + * @notice Called to forgive bad debt starting from next `HPB`, up to the number of remaining buckets depth. * @dev === Write state === * @dev - `Deposits.unscaledRemove()` (remove amount in `Fenwick` tree, from index): * @dev update `values` array state From 45debbf2bf5b268c168ae4845027c7512c656e60 Mon Sep 17 00:00:00 2001 From: grandizzy Date: Thu, 20 Apr 2023 10:26:44 +0300 Subject: [PATCH 10/11] Changes after review: fix typo, update comment of index --- src/libraries/internal/Deposits.sol | 10 +++++----- src/libraries/internal/Loans.sol | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/libraries/internal/Deposits.sol b/src/libraries/internal/Deposits.sol index af69d4c3b..2b2e64266 100644 --- a/src/libraries/internal/Deposits.sol +++ b/src/libraries/internal/Deposits.sol @@ -210,7 +210,7 @@ library Deposits { /** * @notice Get prefix sum of all indexes from provided index downwards. - * @dev Starts at tree root and decrements through range parent nodes summing from index `i_`'s range to index `0`. + * @dev Starts at tree root and decrements through range parent nodes summing from index `sumIndex_`'s range to index `0`. * @param sumIndex_ The index to receive the prefix sum. * @param sum_ The prefix sum from current index downwards. */ @@ -232,13 +232,13 @@ library Deposits { // Skip considering indices outside bounds of Fenwick tree if (index + j > SIZE) continue; - // We are considering whether to include node index_+j in the sum or not. Either way, we need to scaling[index_+j], + // We are considering whether to include node index + j in the sum or not. Either way, we need to scaling[index + j], // either to increment sum_ or to accumulate in runningScale - uint256 scaled = deposits_.scaling[index+j]; + uint256 scaled = deposits_.scaling[index + j]; if (sumIndex_ & j != 0) { - // node index+j of tree is included in sum - uint256 value = deposits_.values[index+j]; + // node index + j of tree is included in sum + uint256 value = deposits_.values[index + j]; // Accumulate in sum_, recall that scaled==0 means that the scale factor is actually 1 sum_ += scaled != 0 ? (runningScale * scaled * value + 5e35) / 1e36 : Maths.wmul(runningScale, value); diff --git a/src/libraries/internal/Loans.sol b/src/libraries/internal/Loans.sol index c62e80529..6cab47a6e 100644 --- a/src/libraries/internal/Loans.sol +++ b/src/libraries/internal/Loans.sol @@ -258,7 +258,7 @@ library Loans { /** * @notice Returns number of loans in pool. * @param loans_ Holds loans heap data. - * @return umber of loans in pool. + * @return Number of loans in pool. */ function noOfLoans(LoansState storage loans_) internal view returns (uint256) { return loans_.loans.length - 1; From c376a41816ec558b57eda9d21621e95c4bf7ba82 Mon Sep 17 00:00:00 2001 From: grandizzy Date: Thu, 20 Apr 2023 11:32:05 +0300 Subject: [PATCH 11/11] Add Documentation how to in README file --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index 9abab940a..4a1811fdd 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,13 @@ make all ### Implementation notes Pool external calls carry the `nonReentrant` modifier to prevent invocation from `flashLoan` and `take` callbacks. +## Documentation +Documentation can be generated as mdbook from Solidity NatSpecs by using `forge doc` command. +For example, to generate documentation and serve it locally on port 4000 (http://localhost:4000/): +```bash +forge doc --serve --port 4000 +``` + ## Tests ### Forge tests - run tests without the gas load tests (good for checking validity)