// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.18;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20Pool} from "@ajna-core/interfaces/pool/erc20/IERC20Pool.sol";
import {IWETH} from "../IWETH.sol";
interface IAjnaPoolUtilsInfo {
function priceToIndex(uint256 price_) external pure returns (uint256);
function borrowerInfo(address pool_, address borrower_)
external
view
returns (
uint256 debt_,
uint256 collateral_,
uint256 index_
);
function poolPricesInfo(address ajnaPool_)
external
view
returns (
uint256 hpb_,
uint256 hpbIndex_,
uint256 htp_,
uint256 htpIndex_,
uint256 lup_,
uint256 lupIndex_
);
function lpToQuoteTokens(
address ajnaPool_,
uint256 lp_,
uint256 index_
) external view returns (uint256 quoteAmount_);
function bucketInfo(address ajnaPool_, uint256 index_)
external
view
returns (
uint256 price_,
uint256 quoteTokens_,
uint256 collateral_,
uint256 bucketLP_,
uint256 scale_,
uint256 exchangeRate_
);
}
interface IAccountGuard {
function owners(address) external view returns (address);
function owner() external view returns (address);
function setWhitelist(address target, bool status) external;
function canCall(address proxy, address operator)
external
view
returns (bool);
function permit(
address caller,
address target,
bool allowance
) external;
function isWhitelisted(address target) external view returns (bool);
function isWhitelistedSend(address target) external view returns (bool);
}
contract AjnaProxyActions {
IAjnaPoolUtilsInfo public immutable poolInfoUtils;
IERC20 public immutable ajnaToken;
address public immutable WETH;
address public immutable GUARD;
address public immutable deployer;
/*
This configuration is applicable across all Layer 2 (L2) networks. However, on the Ethereum mainnet,
we continue to use 'Ajna_rc13'. Due to the nature of 'string' data type in Solidity, it cannot be
declared as 'immutable' and initialized within the constructor.
*/
string public constant ajnaVersion = "Ajna_rc14";
using SafeERC20 for IERC20;
constructor(
IAjnaPoolUtilsInfo _poolInfoUtils,
IERC20 _ajnaToken,
address _WETH,
address _GUARD
) {
require(
address(_poolInfoUtils) != address(0),
"apa/pool-info-utils-zero-address"
);
require(
address(_ajnaToken) != address(0) || block.chainid != 1,
"apa/ajna-token-zero-address"
);
require(_WETH != address(0), "apa/weth-zero-address");
require(_GUARD != address(0), "apa/guard-zero-address");
poolInfoUtils = _poolInfoUtils;
ajnaToken = _ajnaToken;
WETH = _WETH;
GUARD = _GUARD;
deployer = msg.sender;
}
/**
* @dev Emitted once an Operation has completed execution
* @param name Name of the operation
**/
event ProxyActionsOperation(bytes32 indexed name);
/**
* @dev Emitted when a new position is created
* @param proxyAddress The address of the newly created position proxy contract
* @param protocol The name of the protocol associated with the position
* @param positionType The type of position being created (e.g. borrow or earn)
* @param collateralToken The address of the collateral token being used for the position
* @param debtToken The address of the debt token being used for the position
**/
event CreatePosition(
address indexed proxyAddress,
string protocol,
string positionType,
address collateralToken,
address debtToken
);
function _send(address token, uint256 amount) internal {
if (token == WETH) {
IWETH(WETH).withdraw(amount);
payable(msg.sender).transfer(amount);
} else {
IERC20(token).safeTransfer(msg.sender, amount);
}
}
function _pull(address token, uint256 amount) internal {
if (token == WETH) {
IWETH(WETH).deposit{value: amount}();
} else {
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
}
}
function _stampLoan(IERC20Pool pool, bool stamploanEnabled) internal {
if (stamploanEnabled) {
pool.stampLoan();
}
}
/**
* @notice Called internally to add an amount of credit at a specified price bucket.
* @param pool Address of the Ajna Pool.
* @param amount The maximum amount of quote token to be moved by a lender.
* @param price The price the bucket to which the quote tokens will be added.
* @dev price of uint (10**decimals) collateral token in debt token (10**decimals) with 3 decimal points for instance
* @dev 1WBTC = 16,990.23 USDC translates to: 16990230
*/
function _supplyQuote(
IERC20Pool pool,
uint256 amount,
uint256 price
) internal returns (uint256 bucketLP, uint256 addedAmount) {
address debtToken = pool.quoteTokenAddress();
_pull(debtToken, amount);
uint256 index = convertPriceToIndex(price);
IERC20(debtToken).approve(address(pool), amount);
(bucketLP, addedAmount) = pool.addQuoteToken(
amount * pool.quoteTokenScale(),
index,
block.timestamp + 1
);
}
/**
* @notice Called internally to move max amount of credit from a specified price bucket to another specified price bucket.
* @param pool Address of the Ajna Pool.
* @param oldPrice The price of the bucket from which the quote tokens will be removed.
* @param newPrice The price of the bucket to which the quote tokens will be added.
*/
function _moveQuote(
IERC20Pool pool,
uint256 oldPrice,
uint256 newPrice
) internal {
uint256 oldIndex = convertPriceToIndex(oldPrice);
pool.moveQuoteToken(
type(uint256).max,
oldIndex,
convertPriceToIndex(newPrice),
block.timestamp + 1
);
}
/**
* @notice Called internally to remove an amount of credit at a specified price bucket.
* @param pool Address of the Ajna Pool.
* @param amount The maximum amount of quote token to be moved by a lender.
* @param price The price the bucket to which the quote tokens will be added.
* @dev price of uint (10**decimals) collateral token in debt token (10**decimals) with 3 decimal points for instance
* @dev 1WBTC = 16,990.23 USDC translates to: 16990230
*/
function _withdrawQuote(
IERC20Pool pool,
uint256 amount,
uint256 price
) internal {
address debtToken = pool.quoteTokenAddress();
uint256 index = convertPriceToIndex(price);
uint256 withdrawnBalanceWAD;
if (amount == type(uint256).max) {
(withdrawnBalanceWAD, ) = pool.removeQuoteToken(
type(uint256).max,
index
);
} else {
(withdrawnBalanceWAD, ) = pool.removeQuoteToken(
(amount * pool.quoteTokenScale()),
index
);
}
uint256 withdrawnBalance = _roundToScale(
withdrawnBalanceWAD,
pool.quoteTokenScale()
) / pool.quoteTokenScale();
_send(debtToken, withdrawnBalance);
}
/**
* @notice Reclaims collateral from liquidated bucket
* @param pool Address of the Ajna Pool.
* @param price Price of the bucket to redeem.
*/
function _removeCollateral(IERC20Pool pool, uint256 price)
internal
returns (uint256 withdrawnBalance)
{
address collateralToken = pool.collateralAddress();
uint256 index = convertPriceToIndex(price);
(uint256 withdrawnBalanceWAD, ) = pool.removeCollateral(
type(uint256).max,
index
);
withdrawnBalance =
_roundToScale(withdrawnBalanceWAD, pool.collateralScale()) /
pool.collateralScale();
_send(collateralToken, withdrawnBalance);
}
// BORROWER ACTIONS
/**
* @notice Deposit collateral
* @param pool Pool address
* @param collateralAmount Amount of collateral to deposit
* @param price Price of the bucket
* @param stamploanEnabled Whether to stamp the loan or not
*/
function depositCollateral(
IERC20Pool pool,
uint256 collateralAmount,
uint256 price,
bool stamploanEnabled
) public payable {
address collateralToken = pool.collateralAddress();
_pull(collateralToken, collateralAmount);
uint256 index = convertPriceToIndex(price);
IERC20(collateralToken).approve(address(pool), collateralAmount);
pool.drawDebt(
address(this),
0,
index,
collateralAmount * pool.collateralScale()
);
_stampLoan(pool, stamploanEnabled);
emit ProxyActionsOperation("AjnaDeposit");
}
/**
* @notice Draw debt
* @param pool Pool address
* @param debtAmount Amount of debt to draw
* @param price Price of the bucket
*/
function drawDebt(
IERC20Pool pool,
uint256 debtAmount,
uint256 price
) public {
address debtToken = pool.quoteTokenAddress();
uint256 index = convertPriceToIndex(price);
pool.drawDebt(
address(this),
debtAmount * pool.quoteTokenScale(),
index,
0
);
_send(debtToken, debtAmount);
emit ProxyActionsOperation("AjnaBorrow");
}
/**
* @notice Deposit collateral and draw debt
* @param pool Pool address
* @param debtAmount Amount of debt to draw
* @param collateralAmount Amount of collateral to deposit
* @param price Price of the bucket
*/
function depositCollateralAndDrawDebt(
IERC20Pool pool,
uint256 debtAmount,
uint256 collateralAmount,
uint256 price
) public {
address debtToken = pool.quoteTokenAddress();
address collateralToken = pool.collateralAddress();
uint256 index = convertPriceToIndex(price);
_pull(collateralToken, collateralAmount);
IERC20(collateralToken).approve(address(pool), collateralAmount);
pool.drawDebt(
address(this),
debtAmount * pool.quoteTokenScale(),
index,
collateralAmount * pool.collateralScale()
);
_send(debtToken, debtAmount);
emit ProxyActionsOperation("AjnaDepositBorrow");
}
/**
* @notice Deposit collateral and draw debt
* @param pool Pool address
* @param debtAmount Amount of debt to borrow
* @param collateralAmount Amount of collateral to deposit
* @param price Price of the bucket
* @param stamploanEnabled Whether to stamp the loan or not
*/
function depositAndDraw(
IERC20Pool pool,
uint256 debtAmount,
uint256 collateralAmount,
uint256 price,
bool stamploanEnabled
) public payable {
if (debtAmount > 0 && collateralAmount > 0) {
depositCollateralAndDrawDebt(
pool,
debtAmount,
collateralAmount,
price
);
} else if (debtAmount > 0) {
drawDebt(pool, debtAmount, price);
} else if (collateralAmount > 0) {
depositCollateral(pool, collateralAmount, price, stamploanEnabled);
}
}
/**
* @notice Repay debt
* @param pool Pool address
* @param amount Amount of debt to repay
* @param stamploanEnabled Whether to stamp the loan or not
*/
function repayDebt(
IERC20Pool pool,
uint256 amount,
bool stamploanEnabled
) public payable {
address debtToken = pool.quoteTokenAddress();
_pull(debtToken, amount);
IERC20(debtToken).approve(address(pool), amount);
(, , , , , uint256 lupIndex_) = poolInfoUtils.poolPricesInfo(
address(pool)
);
uint256 repaidAmountWAD = pool.repayDebt(
address(this),
amount * pool.quoteTokenScale(),
0,
address(this),
lupIndex_
);
_stampLoan(pool, stamploanEnabled);
uint256 repaidAmount = _roundUpToScale(
repaidAmountWAD,
pool.quoteTokenScale()
) / pool.quoteTokenScale();
uint256 leftoverBalance = amount - repaidAmount;
if (leftoverBalance > 0) {
_send(debtToken, leftoverBalance);
}
IERC20(debtToken).safeApprove(address(pool), 0);
emit ProxyActionsOperation("AjnaRepay");
}
/**
* @notice Withdraw collateral
* @param pool Pool address
* @param amount Amount of collateral to withdraw
*/
function withdrawCollateral(IERC20Pool pool, uint256 amount) public {
address collateralToken = pool.collateralAddress();
(, , , , , uint256 lupIndex_) = poolInfoUtils.poolPricesInfo(
address(pool)
);
pool.repayDebt(
address(this),
0,
amount * pool.collateralScale(),
address(this),
lupIndex_
);
_send(collateralToken, amount);
emit ProxyActionsOperation("AjnaWithdraw");
}
/**
* @notice Repay debt and withdraw collateral
* @param pool Pool address
* @param debtAmount Amount of debt to repay
* @param collateralAmount Amount of collateral to withdraw
*/
function repayDebtAndWithdrawCollateral(
IERC20Pool pool,
uint256 debtAmount,
uint256 collateralAmount
) public {
address debtToken = pool.quoteTokenAddress();
address collateralToken = pool.collateralAddress();
_pull(debtToken, debtAmount);
IERC20(debtToken).approve(address(pool), debtAmount);
(, , , , , uint256 lupIndex_) = poolInfoUtils.poolPricesInfo(
address(pool)
);
uint256 repaidAmountWAD = pool.repayDebt(
address(this),
debtAmount * pool.quoteTokenScale(),
collateralAmount * pool.collateralScale(),
address(this),
lupIndex_
);
_send(collateralToken, collateralAmount);
uint256 repaidAmount = _roundUpToScale(
repaidAmountWAD,
pool.quoteTokenScale()
) / pool.quoteTokenScale();
uint256 quoteLeftoverBalance = debtAmount - repaidAmount;
if (quoteLeftoverBalance > 0) {
_send(debtToken, quoteLeftoverBalance);
}
IERC20(debtToken).safeApprove(address(pool), 0);
emit ProxyActionsOperation("AjnaRepayWithdraw");
}
/**
* @notice Repay debt and withdraw collateral for msg.sender
* @param pool Pool address
* @param debtAmount Amount of debt to repay
* @param collateralAmount Amount of collateral to withdraw
* @param stamploanEnabled Whether to stamp the loan or not
*/
function repayWithdraw(
IERC20Pool pool,
uint256 debtAmount,
uint256 collateralAmount,
bool stamploanEnabled
) external payable {
if (debtAmount > 0 && collateralAmount > 0) {
repayDebtAndWithdrawCollateral(pool, debtAmount, collateralAmount);
} else if (debtAmount > 0) {
repayDebt(pool, debtAmount, stamploanEnabled);
} else if (collateralAmount > 0) {
withdrawCollateral(pool, collateralAmount);
}
}
/**
* @notice Repay debt and close position for msg.sender
* @param pool Pool address
*/
function repayAndClose(IERC20Pool pool) public payable {
address collateralToken = pool.collateralAddress();
address debtToken = pool.quoteTokenAddress();
(uint256 debt, uint256 collateral, ) = poolInfoUtils.borrowerInfo(
address(pool),
address(this)
);
uint256 debtPlusBuffer = _roundUpToScale(debt, pool.quoteTokenScale());
uint256 amountDebt = debtPlusBuffer / pool.quoteTokenScale();
_pull(debtToken, amountDebt);
IERC20(debtToken).approve(address(pool), amountDebt);
(, , , , , uint256 lupIndex_) = poolInfoUtils.poolPricesInfo(
address(pool)
);
pool.repayDebt(
address(this),
debtPlusBuffer,
collateral,
address(this),
lupIndex_
);
uint256 amountCollateral = collateral / pool.collateralScale();
_send(collateralToken, amountCollateral);
IERC20(debtToken).safeApprove(address(pool), 0);
emit ProxyActionsOperation("AjnaRepayAndClose");
}
/**
* @notice Open position for msg.sender
* @param pool Pool address
* @param debtAmount Amount of debt to borrow
* @param collateralAmount Amount of collateral to deposit
* @param price Price of the bucket
*/
function openPosition(
IERC20Pool pool,
uint256 debtAmount,
uint256 collateralAmount,
uint256 price
) public payable {
emit CreatePosition(
address(this),
ajnaVersion,
"Borrow",
pool.collateralAddress(),
pool.quoteTokenAddress()
);
depositAndDraw(pool, debtAmount, collateralAmount, price, false);
}
/**
* @notice Open Earn position for msg.sender
* @param pool Pool address
* @param depositAmount Amount of debt to borrow
* @param price Price of the bucket
*/
function openEarnPosition(
IERC20Pool pool,
uint256 depositAmount,
uint256 price
) public payable {
emit CreatePosition(
address(this),
ajnaVersion,
"Earn",
pool.collateralAddress(),
pool.quoteTokenAddress()
);
_validateBucketState(pool, convertPriceToIndex(price));
_supplyQuote(pool, depositAmount, price);
emit ProxyActionsOperation("AjnaSupplyQuote");
}
/**
* @notice Called by lenders to add an amount of credit at a specified price bucket.
* @param pool Address of the Ajna Pool.
* @param amount The maximum amount of quote token to be moved by a lender.
* @param price The price the bucket to which the quote tokens will be added.
* @dev price of uint (10**decimals) collateral token in debt token (10**decimals) with 3 decimal points for instance
* @dev 1WBTC = 16,990.23 USDC translates to: 16990230
*/
function supplyQuote(
IERC20Pool pool,
uint256 amount,
uint256 price
) public payable {
_validateBucketState(pool, convertPriceToIndex(price));
_supplyQuote(pool, amount, price);
emit ProxyActionsOperation("AjnaSupplyQuote");
}
/**
* @notice Called by lenders to remove an amount of credit at a specified price bucket.
* @param pool Address of the Ajna Pool.
* @param amount The maximum amount of quote token to be moved by a lender.
* @param price The price the bucket to which the quote tokens will be added.
* @dev price of uint (10**decimals) collateral token in debt token (10**decimals) with 3 decimal points for instance
* @dev 1WBTC = 16,990.23 USDC translates to: 16990230
*/
function withdrawQuote(
IERC20Pool pool,
uint256 amount,
uint256 price
) public {
_withdrawQuote(pool, amount, price);
emit ProxyActionsOperation("AjnaWithdrawQuote");
}
/**
* @notice Called by lenders to move max amount of credit from a specified price bucket to another specified price bucket.
* @param pool Address of the Ajna Pool.
* @param oldPrice The price of the bucket from which the quote tokens will be removed.
* @param newPrice The price of the bucket to which the quote tokens will be added.
*/
function moveQuote(
IERC20Pool pool,
uint256 oldPrice,
uint256 newPrice
) public {
_validateBucketState(pool, convertPriceToIndex(newPrice));
_moveQuote(pool, oldPrice, newPrice);
emit ProxyActionsOperation("AjnaMoveQuote");
}
/**
* @notice Called by lenders to move an amount of credit from a specified price bucket to another specified price bucket,
* @notice whilst adding additional amount.
* @param pool Address of the Ajna Pool.
* @param amountToAdd The maximum amount of quote token to be moved by a lender.
* @param oldPrice The price of the bucket from which the quote tokens will be removed.
* @param newPrice The price of the bucket to which the quote tokens will be added.
*/
function supplyAndMoveQuote(
IERC20Pool pool,
uint256 amountToAdd,
uint256 oldPrice,
uint256 newPrice
) public payable {
uint256 newIndex = convertPriceToIndex(newPrice);
_validateBucketState(pool, newIndex);
_supplyQuote(pool, amountToAdd, newPrice);
_validateBucketState(pool, newIndex);
_moveQuote(pool, oldPrice, newPrice);
emit ProxyActionsOperation("AjnaSupplyAndMoveQuote");
}
/**
* @notice Called by lenders to move an amount of credit from a specified price bucket to another specified price bucket,
* @notice whilst withdrawing additional amount.
* @param pool Address of the Ajna Pool.
* @param amountToWithdraw Amount of quote token to be withdrawn by a lender.
* @param oldPrice The price of the bucket from which the quote tokens will be removed.
* @param newPrice The price of the bucket to which the quote tokens will be added.
*/
function withdrawAndMoveQuote(
IERC20Pool pool,
uint256 amountToWithdraw,
uint256 oldPrice,
uint256 newPrice
) public {
_withdrawQuote(pool, amountToWithdraw, oldPrice);
_validateBucketState(pool, convertPriceToIndex(newPrice));
_moveQuote(pool, oldPrice, newPrice);
emit ProxyActionsOperation("AjnaWithdrawAndMoveQuote");
}
/**
* @notice Reclaims collateral from liquidated bucket
* @param pool Address of the Ajna Pool.
* @param price Price of the bucket to redeem.
*/
function removeCollateral(IERC20Pool pool, uint256 price) public {
_removeCollateral(pool, price);
emit ProxyActionsOperation("AjnaRemoveCollateral");
}
// VIEW FUNCTIONS
/**
* @notice Converts price to index
* @param price price of uint (10**decimals) collateral token in debt token (10**decimals) with 18 decimal points for instance
* @return index index of the bucket
* @dev price of uint (10**decimals) collateral token in debt token (10**decimals) with 18 decimal points for instance
* @dev 1WBTC = 16,990.23 USDC translates to: 16990230000000000000000
*/
function convertPriceToIndex(uint256 price) public view returns (uint256) {
return poolInfoUtils.priceToIndex(price);
}
/**
* @dev Validates the state of a bucket in an IERC20Pool contract.
* @param pool The IERC20Pool contract address.
* @param bucket The index of the bucket to validate.
*/
function _validateBucketState(IERC20Pool pool, uint256 bucket) public view {
(, , , uint256 bucketLP_, , ) = poolInfoUtils.bucketInfo(
address(pool),
bucket
);
require(
bucketLP_ == 0 || bucketLP_ > 1_000_000,
"apa/bucket-lps-invalid"
);
}
/**
* @notice Get the amount of quote token deposited to a specific bucket
* @param pool Address of the Ajna Pool.
* @param price Price of the bucket to query
* @return quoteAmount Amount of quote token deposited to dpecific bucket
* @dev price of uint (10**decimals) collateral token in debt token (10**decimals) with 18 decimal points for instance
* @dev 1WBTC = 16,990.23 USDC translates to: 16990230000000000000000
*/
function getQuoteAmount(IERC20Pool pool, uint256 price)
public
view
returns (uint256 quoteAmount)
{
uint256 index = convertPriceToIndex(price);
(uint256 lpCount, ) = pool.lenderInfo(index, address(this));
quoteAmount = poolInfoUtils.lpToQuoteTokens(
address(pool),
lpCount,
index
);
}
/**
* @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`.
* @return scaledAmount_ Rounded value.
*/
function _roundToScale(uint256 amount_, uint256 tokenScale_)
internal
pure
returns (uint256 scaledAmount_)
{
scaledAmount_ = (amount_ / tokenScale_) * tokenScale_;
}
/**
* @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`.
* @return scaledAmount_ Rounded value.
*/
function _roundUpToScale(uint256 amount_, uint256 tokenScale_)
internal
pure
returns (uint256 scaledAmount_)
{
if (amount_ % tokenScale_ == 0) scaledAmount_ = amount_;
else scaledAmount_ = _roundToScale(amount_, tokenScale_) + tokenScale_;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;
import {Maths} from "../libraries/Maths.sol";
import {Governance} from "../utils/Governance.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {ITaker} from "../interfaces/ITaker.sol";
/// @notice Interface that the optional `hook` contract should implement if the non-standard logic is desired.
interface IHook {
function kickable(address _fromToken) external view returns (uint256);
function auctionKicked(address _fromToken) external returns (uint256);
function preTake(
address _fromToken,
uint256 _amountToTake,
uint256 _amountToPay
) external;
function postTake(
address _toToken,
uint256 _amountTaken,
uint256 _amountPayed
) external;
}
/**
* @title Auction
* @author yearn.fi
* @notice General use dutch auction contract for token sales.
*/
contract Auction is Governance, ReentrancyGuard {
using SafeERC20 for ERC20;
/// @notice Emitted when a new auction is enabled
event AuctionEnabled(
bytes32 auctionId,
address indexed from,
address indexed to,
address indexed auctionAddress
);
/// @notice Emitted when an auction is disabled.
event AuctionDisabled(
bytes32 auctionId,
address indexed from,
address indexed to,
address indexed auctionAddress
);
/// @notice Emitted when auction has been kicked.
event AuctionKicked(bytes32 auctionId, uint256 available);
/// @notice Emitted when any amount of an active auction was taken.
event AuctionTaken(
bytes32 auctionId,
uint256 amountTaken,
uint256 amountLeft
);
/// @dev Store address and scaler in one slot.
struct TokenInfo {
address tokenAddress;
uint96 scaler;
}
/// @notice Store all the auction specific information.
struct AuctionInfo {
TokenInfo fromInfo;
uint96 kicked;
address receiver;
uint128 initialAvailable;
uint128 currentAvailable;
}
/// @notice Store the hook address and each flag in one slot.
struct Hook {
address hook;
bool kickable;
bool kick;
bool preTake;
bool postTake;
}
uint256 internal constant WAD = 1e18;
/// @notice Used for the price decay.
uint256 internal constant MINUTE_HALF_LIFE =
0.988514020352896135_356867505 * 1e27; // 0.5^(1/60)
/// @notice Struct to hold the info for `want`.
TokenInfo internal wantInfo;
/// @notice Contract to call during write functions.
Hook internal hook_;
/// @notice The amount to start the auction at.
uint256 public startingPrice;
/// @notice The time that each auction lasts.
uint256 public auctionLength;
/// @notice The minimum time to wait between auction 'kicks'.
uint256 public auctionCooldown;
/// @notice Mapping from an auction ID to its struct.
mapping(bytes32 => AuctionInfo) public auctions;
/// @notice Array of all the enabled auction for this contract.
bytes32[] public enabledAuctions;
constructor() Governance(msg.sender) {}
/**
* @notice Initializes the Auction contract with initial parameters.
* @param _want Address this auction is selling to.
* @param _hook Address of the hook contract (optional).
* @param _governance Address of the contract governance.
* @param _auctionLength Duration of each auction in seconds.
* @param _auctionCooldown Cooldown period between auctions in seconds.
* @param _startingPrice Starting price for each auction.
*/
function initialize(
address _want,
address _hook,
address _governance,
uint256 _auctionLength,
uint256 _auctionCooldown,
uint256 _startingPrice
) external virtual {
require(auctionLength == 0, "initialized");
require(_want != address(0), "ZERO ADDRESS");
require(_auctionLength != 0, "length");
require(_auctionLength < _auctionCooldown, "cooldown");
require(_startingPrice != 0, "starting price");
// Cannot have more than 18 decimals.
uint256 decimals = ERC20(_want).decimals();
require(decimals <= 18, "unsupported decimals");
// Set variables
wantInfo = TokenInfo({
tokenAddress: _want,
scaler: uint96(WAD / 10 ** decimals)
});
// If we are using a hook.
if (_hook != address(0)) {
// All flags default to true.
hook_ = Hook({
hook: _hook,
kickable: true,
kick: true,
preTake: true,
postTake: true
});
}
governance = _governance;
auctionLength = _auctionLength;
auctionCooldown = _auctionCooldown;
startingPrice = _startingPrice;
}
/*//////////////////////////////////////////////////////////////
VIEW METHODS
//////////////////////////////////////////////////////////////*/
/**
* @notice Get the address of this auctions want token.
* @return . The want token.
*/
function want() public view virtual returns (address) {
return wantInfo.tokenAddress;
}
/**
* @notice Get the address of the hook if any.
* @return . The hook.
*/
function hook() external view virtual returns (address) {
return hook_.hook;
}
/**
* @notice Get the current status of which hooks are being used.
* @return . If the kickable hook is used.
* @return . If the kick hook is used.
* @return . If the preTake hook is used.
* @return . If the postTake hook is used.
*/
function getHookFlags()
external
view
virtual
returns (bool, bool, bool, bool)
{
Hook memory _hook = hook_;
return (_hook.kickable, _hook.kick, _hook.preTake, _hook.postTake);
}
/**
* @notice Get the length of the enabled auctions array.
*/
function numberOfEnabledAuctions() external view virtual returns (uint256) {
return enabledAuctions.length;
}
/**
* @notice Get the unique auction identifier.
* @param _from The address of the token to sell.
* @return bytes32 A unique auction identifier.
*/
function getAuctionId(address _from) public view virtual returns (bytes32) {
return keccak256(abi.encodePacked(_from, want(), address(this)));
}
/**
* @notice Retrieves information about a specific auction.
* @param _auctionId The unique identifier of the auction.
* @return _from The address of the token to sell.
* @return _to The address of the token to buy.
* @return _kicked The timestamp of the last kick.
* @return _available The current available amount for the auction.
*/
function auctionInfo(
bytes32 _auctionId
)
public
view
virtual
returns (
address _from,
address _to,
uint256 _kicked,
uint256 _available
)
{
AuctionInfo memory auction = auctions[_auctionId];
return (
auction.fromInfo.tokenAddress,
want(),
auction.kicked,
auction.kicked + auctionLength > block.timestamp
? auction.currentAvailable
: 0
);
}
/**
* @notice Get the pending amount available for the next auction.
* @dev Defaults to the auctions balance of the from token if no hook.
* @param _auctionId The unique identifier of the auction.
* @return uint256 The amount that can be kicked into the auction.
*/
function kickable(
bytes32 _auctionId
) external view virtual returns (uint256) {
// If not enough time has passed then `kickable` is 0.
if (auctions[_auctionId].kicked + auctionCooldown > block.timestamp) {
return 0;
}
// Check if we have a hook to call.
Hook memory _hook = hook_;
if (_hook.kickable) {
// If so default to the hooks logic.
return
IHook(_hook.hook).kickable(
auctions[_auctionId].fromInfo.tokenAddress
);
} else {
// Else just use the full balance of this contract.
return
ERC20(auctions[_auctionId].fromInfo.tokenAddress).balanceOf(
address(this)
);
}
}
/**
* @notice Gets the amount of `want` needed to buy a specific amount of `from`.
* @param _auctionId The unique identifier of the auction.
* @param _amountToTake The amount of `from` to take in the auction.
* @return . The amount of `want` needed to fulfill the take amount.
*/
function getAmountNeeded(
bytes32 _auctionId,
uint256 _amountToTake
) external view virtual returns (uint256) {
return
_getAmountNeeded(
auctions[_auctionId],
_amountToTake,
block.timestamp
);
}
/**
* @notice Gets the amount of `want` needed to buy a specific amount of `from` at a specific timestamp.
* @param _auctionId The unique identifier of the auction.
* @param _amountToTake The amount `from` to take in the auction.
* @param _timestamp The specific timestamp for calculating the amount needed.
* @return . The amount of `want` needed to fulfill the take amount.
*/
function getAmountNeeded(
bytes32 _auctionId,
uint256 _amountToTake,
uint256 _timestamp
) external view virtual returns (uint256) {
return
_getAmountNeeded(auctions[_auctionId], _amountToTake, _timestamp);
}
/**
* @dev Return the amount of `want` needed to buy `_amountToTake`.
*/
function _getAmountNeeded(
AuctionInfo memory _auction,
uint256 _amountToTake,
uint256 _timestamp
) internal view virtual returns (uint256) {
return
// Scale _amountToTake to 1e18
(_amountToTake *
_auction.fromInfo.scaler *
// Price is always 1e18
_price(
_auction.kicked,
_auction.initialAvailable * _auction.fromInfo.scaler,
_timestamp
)) /
1e18 /
// Scale back down to want.
wantInfo.scaler;
}
/**
* @notice Gets the price of the auction at the current timestamp.
* @param _auctionId The unique identifier of the auction.
* @return . The price of the auction.
*/
function price(bytes32 _auctionId) external view virtual returns (uint256) {
return price(_auctionId, block.timestamp);
}
/**
* @notice Gets the price of the auction at a specific timestamp.
* @param _auctionId The unique identifier of the auction.
* @param _timestamp The specific timestamp for calculating the price.
* @return . The price of the auction.
*/
function price(
bytes32 _auctionId,
uint256 _timestamp
) public view virtual returns (uint256) {
// Get unscaled price and scale it down.
return
_price(
auctions[_auctionId].kicked,
auctions[_auctionId].initialAvailable *
auctions[_auctionId].fromInfo.scaler,
_timestamp
) / wantInfo.scaler;
}
/**
* @dev Internal function to calculate the scaled price based on auction parameters.
* @param _kicked The timestamp the auction was kicked.
* @param _available The initial available amount scaled 1e18.
* @param _timestamp The specific timestamp for calculating the price.
* @return . The calculated price scaled to 1e18.
*/
function _price(
uint256 _kicked,
uint256 _available,
uint256 _timestamp
) internal view virtual returns (uint256) {
if (_available == 0) return 0;
uint256 secondsElapsed = _timestamp - _kicked;
if (secondsElapsed > auctionLength) return 0;
// Exponential decay from https://github.com/ajna-finance/ajna-core/blob/master/src/libraries/helpers/PoolHelper.sol
uint256 hoursComponent = 1e27 >> (secondsElapsed / 3600);
uint256 minutesComponent = Maths.rpow(
MINUTE_HALF_LIFE,
(secondsElapsed % 3600) / 60
);
uint256 initialPrice = Maths.wdiv(startingPrice * 1e18, _available);
return
(initialPrice * Maths.rmul(hoursComponent, minutesComponent)) /
1e27;
}
/*//////////////////////////////////////////////////////////////
SETTERS
//////////////////////////////////////////////////////////////*/
/**
* @notice Enables a new auction.
* @dev Uses governance as the receiver.
* @param _from The address of the token to be auctioned.
* @return . The unique identifier of the enabled auction.
*/
function enable(address _from) external virtual returns (bytes32) {
return enable(_from, msg.sender);
}
/**
* @notice Enables a new auction.
* @param _from The address of the token to be auctioned.
* @param _receiver The address that will receive the funds in the auction.
* @return _auctionId The unique identifier of the enabled auction.
*/
function enable(
address _from,
address _receiver
) public virtual onlyGovernance returns (bytes32 _auctionId) {
address _want = want();
require(_from != address(0) && _from != _want, "ZERO ADDRESS");
require(
_receiver != address(0) && _receiver != address(this),
"receiver"
);
// Cannot have more than 18 decimals.
uint256 decimals = ERC20(_from).decimals();
require(decimals <= 18, "unsupported decimals");
// Calculate the id.
_auctionId = getAuctionId(_from);
require(
auctions[_auctionId].fromInfo.tokenAddress == address(0),
"already enabled"
);
// Store all needed info.
auctions[_auctionId].fromInfo = TokenInfo({
tokenAddress: _from,
scaler: uint96(WAD / 10 ** decimals)
});
auctions[_auctionId].receiver = _receiver;
// Add to the array.
enabledAuctions.push(_auctionId);
emit AuctionEnabled(_auctionId, _from, _want, address(this));
}
/**
* @notice Disables an existing auction.
* @dev Only callable by governance.
* @param _from The address of the token being sold.
*/
function disable(address _from) external virtual {
disable(_from, 0);
}
/**
* @notice Disables an existing auction.
* @dev Only callable by governance.
* @param _from The address of the token being sold.
* @param _index The index the auctionId is at in the array.
*/
function disable(
address _from,
uint256 _index
) public virtual onlyGovernance {
bytes32 _auctionId = getAuctionId(_from);
// Make sure the auction was enabled.
require(
auctions[_auctionId].fromInfo.tokenAddress != address(0),
"not enabled"
);
// Remove the struct.
delete auctions[_auctionId];
// Remove the auction ID from the array.
bytes32[] memory _enabledAuctions = enabledAuctions;
if (_enabledAuctions[_index] != _auctionId) {
// If the _index given is not the id find it.
for (uint256 i = 0; i < _enabledAuctions.length; ++i) {
if (_enabledAuctions[i] == _auctionId) {
_index = i;
break;
}
}
}
// Move the id to the last spot if not there.
if (_index < _enabledAuctions.length - 1) {
_enabledAuctions[_index] = _enabledAuctions[
_enabledAuctions.length - 1
];
// Update the array.
enabledAuctions = _enabledAuctions;
}
// Pop the id off the array.
enabledAuctions.pop();
emit AuctionDisabled(_auctionId, _from, want(), address(this));
}
/**
* @notice Set the flags to be used with hook.
* @param _kickable If the kickable hook should be used.
* @param _kick If the kick hook should be used.
* @param _preTake If the preTake hook should be used.
* @param _postTake If the postTake should be used.
*/
function setHookFlags(
bool _kickable,
bool _kick,
bool _preTake,
bool _postTake
) external virtual onlyGovernance {
address _hook = hook_.hook;
require(_hook != address(0), "no hook set");
hook_ = Hook({
hook: _hook,
kickable: _kickable,
kick: _kick,
preTake: _preTake,
postTake: _postTake
});
}
/*//////////////////////////////////////////////////////////////
PARTICIPATE IN AUCTION
//////////////////////////////////////////////////////////////*/
/**
* @notice Kicks off an auction, updating its status and making funds available for bidding.
* @param _auctionId The unique identifier of the auction.
* @return available The available amount for bidding on in the auction.
*/
function kick(
bytes32 _auctionId
) external virtual nonReentrant returns (uint256 available) {
address _fromToken = auctions[_auctionId].fromInfo.tokenAddress;
require(_fromToken != address(0), "not enabled");
require(
block.timestamp > auctions[_auctionId].kicked + auctionCooldown,
"too soon"
);
Hook memory _hook = hook_;
// Use hook if defined.
if (_hook.kick) {
available = IHook(_hook.hook).auctionKicked(_fromToken);
} else {
// Else just use current balance.
available = ERC20(_fromToken).balanceOf(address(this));
}
require(available != 0, "nothing to kick");
// Update the auctions status.
auctions[_auctionId].kicked = uint96(block.timestamp);
auctions[_auctionId].initialAvailable = uint128(available);
auctions[_auctionId].currentAvailable = uint128(available);
emit AuctionKicked(_auctionId, available);
}
/**
* @notice Take the token being sold in a live auction.
* @dev Defaults to taking the full amount and sending to the msg sender.
* @param _auctionId The unique identifier of the auction.
* @return . The amount of fromToken taken in the auction.
*/
function take(bytes32 _auctionId) external virtual returns (uint256) {
return _take(_auctionId, type(uint256).max, msg.sender, new bytes(0));
}
/**
* @notice Take the token being sold in a live auction with a specified maximum amount.
* @dev Uses the sender's address as the receiver.
* @param _auctionId The unique identifier of the auction.
* @param _maxAmount The maximum amount of fromToken to take in the auction.
* @return . The amount of fromToken taken in the auction.
*/
function take(
bytes32 _auctionId,
uint256 _maxAmount
) external virtual returns (uint256) {
return _take(_auctionId, _maxAmount, msg.sender, new bytes(0));
}
/**
* @notice Take the token being sold in a live auction.
* @param _auctionId The unique identifier of the auction.
* @param _maxAmount The maximum amount of fromToken to take in the auction.
* @param _receiver The address that will receive the fromToken.
* @return _amountTaken The amount of fromToken taken in the auction.
*/
function take(
bytes32 _auctionId,
uint256 _maxAmount,
address _receiver
) external virtual returns (uint256) {
return _take(_auctionId, _maxAmount, _receiver, new bytes(0));
}
/**
* @notice Take the token being sold in a live auction.
* @param _auctionId The unique identifier of the auction.
* @param _maxAmount The maximum amount of fromToken to take in the auction.
* @param _receiver The address that will receive the fromToken.
* @param _data The data signify the callback should be used and sent with it.
* @return _amountTaken The amount of fromToken taken in the auction.
*/
function take(
bytes32 _auctionId,
uint256 _maxAmount,
address _receiver,
bytes calldata _data
) external virtual returns (uint256) {
return _take(_auctionId, _maxAmount, _receiver, _data);
}
/// @dev Implements the take of the auction.
function _take(
bytes32 _auctionId,
uint256 _maxAmount,
address _receiver,
bytes memory _data
) internal virtual nonReentrant returns (uint256 _amountTaken) {
AuctionInfo memory auction = auctions[_auctionId];
// Make sure the auction is active.
require(
auction.kicked + auctionLength >= block.timestamp,
"not kicked"
);
// Max amount that can be taken.
_amountTaken = auction.currentAvailable > _maxAmount
? _maxAmount
: auction.currentAvailable;
// Get the amount needed
uint256 needed = _getAmountNeeded(
auction,
_amountTaken,
block.timestamp
);
require(needed != 0, "zero needed");
// How much is left in this auction.
uint256 left;
unchecked {
left = auction.currentAvailable - _amountTaken;
}
auctions[_auctionId].currentAvailable = uint128(left);
Hook memory _hook = hook_;
if (_hook.preTake) {
// Use hook if defined.
IHook(_hook.hook).preTake(
auction.fromInfo.tokenAddress,
_amountTaken,
needed
);
}
// Send `from`.
ERC20(auction.fromInfo.tokenAddress).safeTransfer(
_receiver,
_amountTaken
);
// If the caller has specified data.
if (_data.length != 0) {
// Do the callback.
ITaker(_receiver).auctionTakeCallback(
_auctionId,
msg.sender,
_amountTaken,
needed,
_data
);
}
// Cache the want address.
address _want = want();
// Pull `want`.
ERC20(_want).safeTransferFrom(msg.sender, auction.receiver, needed);
// Post take hook if defined.
if (_hook.postTake) {
IHook(_hook.hook).postTake(_want, _amountTaken, needed);
}
emit AuctionTaken(_auctionId, _amountTaken, left);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;
import {Auction} from "./Auction.sol";
import {Clonable} from "../utils/Clonable.sol";
/// @title AuctionFactory
/// @notice Deploy a new Auction.
contract AuctionFactory is Clonable {
event DeployedNewAuction(address indexed auction, address indexed want);
/// @notice The time that each auction lasts.
uint256 public constant DEFAULT_AUCTION_LENGTH = 1 days;
/// @notice The minimum time to wait between auction 'kicks'.
uint256 public constant DEFAULT_AUCTION_COOLDOWN = 5 days;
/// @notice The amount to start the auction with.
uint256 public constant DEFAULT_STARTING_PRICE = 1_000_000;
/// @notice Full array of all auctions deployed through this factory.
address[] public auctions;
constructor() {
// Deploy the original
original = address(new Auction());
}
/**
* @notice Creates a new auction contract.
* @param _want Address of the token users will bid with.
* @return _newAuction Address of the newly created auction contract.
*/
function createNewAuction(address _want) external returns (address) {
return
_createNewAuction(
_want,
address(0),
msg.sender,
DEFAULT_AUCTION_LENGTH,
DEFAULT_AUCTION_COOLDOWN,
DEFAULT_STARTING_PRICE
);
}
/**
* @notice Creates a new auction contract.
* @param _want Address of the token users will bid with.
* @param _hook Address of the hook contract if any.
* @return _newAuction Address of the newly created auction contract.
*/
function createNewAuction(
address _want,
address _hook
) external returns (address) {
return
_createNewAuction(
_want,
_hook,
msg.sender,
DEFAULT_AUCTION_LENGTH,
DEFAULT_AUCTION_COOLDOWN,
DEFAULT_STARTING_PRICE
);
}
/**
* @notice Creates a new auction contract.
* @param _want Address of the token users will bid with.
* @param _hook Address of the hook contract if any.
* @param _governance Address allowed to enable and disable auctions.
* @return _newAuction Address of the newly created auction contract.
*/
function createNewAuction(
address _want,
address _hook,
address _governance
) external returns (address) {
return
_createNewAuction(
_want,
_hook,
_governance,
DEFAULT_AUCTION_LENGTH,
DEFAULT_AUCTION_COOLDOWN,
DEFAULT_STARTING_PRICE
);
}
/**
* @notice Creates a new auction contract.
* @param _want Address of the token users will bid with.
* @param _hook Address of the hook contract if any.
* @param _governance Address allowed to enable and disable auctions.
* @param _auctionLength Length of the auction in seconds.
* @return _newAuction Address of the newly created auction contract.
*/
function createNewAuction(
address _want,
address _hook,
address _governance,
uint256 _auctionLength
) external returns (address) {
return
_createNewAuction(
_want,
_hook,
_governance,
_auctionLength,
DEFAULT_AUCTION_COOLDOWN,
DEFAULT_STARTING_PRICE
);
}
/**
* @notice Creates a new auction contract.
* @param _want Address of the token users will bid with.
* @param _hook Address of the hook contract if any.
* @param _governance Address allowed to enable and disable auctions.
* @param _auctionLength Length of the auction in seconds.
* @param _auctionCooldown Minimum time period between kicks in seconds.
* @return _newAuction Address of the newly created auction contract.
*/
function createNewAuction(
address _want,
address _hook,
address _governance,
uint256 _auctionLength,
uint256 _auctionCooldown
) external returns (address) {
return
_createNewAuction(
_want,
_hook,
_governance,
_auctionLength,
_auctionCooldown,
DEFAULT_STARTING_PRICE
);
}
/**
* @notice Creates a new auction contract.
* @param _want Address of the token users will bid with.
* @param _hook Address of the hook contract if any.
* @param _governance Address allowed to enable and disable auctions.
* @param _auctionLength Length of the auction in seconds.
* @param _auctionCooldown Minimum time period between kicks in seconds.
* @param _startingPrice Starting price for the auction (no decimals).
* NOTE: The starting price should be without decimals (1k == 1_000).
* @return _newAuction Address of the newly created auction contract.
*/
function createNewAuction(
address _want,
address _hook,
address _governance,
uint256 _auctionLength,
uint256 _auctionCooldown,
uint256 _startingPrice
) external returns (address) {
return
_createNewAuction(
_want,
_hook,
_governance,
_auctionLength,
_auctionCooldown,
_startingPrice
);
}
/**
* @dev Deploys and initializes a new Auction
*/
function _createNewAuction(
address _want,
address _hook,
address _governance,
uint256 _auctionLength,
uint256 _auctionCooldown,
uint256 _startingPrice
) internal returns (address _newAuction) {
_newAuction = _clone();
Auction(_newAuction).initialize(
_want,
_hook,
_governance,
_auctionLength,
_auctionCooldown,
_startingPrice
);
auctions.push(_newAuction);
emit DeployedNewAuction(_newAuction, _want);
}
/**
* @notice Get the full list of auctions deployed through this factory.
*/
function getAllAuctions() external view returns (address[] memory) {
return auctions;
}
/**
* @notice Get the total number of auctions deployed through this factory.
*/
function numberOfAuctions() external view returns (uint256) {
return auctions.length;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {AuctionFactory, Auction} from "../Auctions/AuctionFactory.sol";
/**
* @title AuctionSwapper
* @author yearn.fi
* @dev Helper contract for a strategy to use dutch auctions for token sales.
*
* This contract is meant to be inherited by a V3 strategy in order
* to easily integrate dutch auctions into a contract for token swaps.
*
* The strategist will need to implement a way to call `_enableAuction`
* for an token pair they want to use, or a setter to manually set the
* `auction` contract.
*
* The contract comes with all of the needed function to act as a `hook`
* contract for the specific auction contract with the ability to override
* any of the functions to implement custom hooks.
*
* NOTE: If any hooks are not desired, the strategist should also
* implement a way to call the {setHookFlags} on the auction contract
* to avoid unnecessary gas for unused functions.
*/
contract AuctionSwapper {
using SafeERC20 for ERC20;
modifier onlyAuction() {
_isAuction();
_;
}
/**
* @dev Check the caller is the auction contract for hooks.
*/
function _isAuction() internal view virtual {
require(msg.sender == auction, "!auction");
}
/// @notice The pre-deployed Auction factory for cloning.
address public constant auctionFactory =
0xE6aB098E8582178A76DC80d55ca304d1Dec11AD8;
/// @notice Address of the specific Auction this strategy uses.
address public auction;
/*//////////////////////////////////////////////////////////////
AUCTION STARTING AND STOPPING
//////////////////////////////////////////////////////////////*/
function _enableAuction(
address _from,
address _want
) internal virtual returns (bytes32) {
return _enableAuction(_from, _want, 1 days, 3 days, 1e6);
}
/**
* @dev Used to enable a new Auction to sell `_from` to `_want`.
* If this is the first auction enabled it will deploy a new `auction`
* contract to use from the factory.
*
* NOTE: This only supports one `_want` token per strategy.
*
* @param _from Token to sell
* @param _want Token to buy.
* @return .The auction ID.
*/
function _enableAuction(
address _from,
address _want,
uint256 _auctionLength,
uint256 _auctionCooldown,
uint256 _startingPrice
) internal virtual returns (bytes32) {
address _auction = auction;
// If this is the first auction.
if (_auction == address(0)) {
// Deploy a new auction
_auction = AuctionFactory(auctionFactory).createNewAuction(
_want,
address(this),
address(this),
_auctionLength,
_auctionCooldown,
_startingPrice
);
// Store it for future use.
auction = _auction;
} else {
// Can only use one `want` per auction contract.
require(Auction(_auction).want() == _want, "wrong want");
}
// Enable new auction for `_from` token.
return Auction(_auction).enable(_from);
}
/**
* @dev Disable an auction for a given token.
* @param _from The token that was being sold.
*/
function _disableAuction(address _from) internal virtual {
Auction(auction).disable(_from);
}
/*//////////////////////////////////////////////////////////////
OPTIONAL AUCTION HOOKS
//////////////////////////////////////////////////////////////*/
/**
* @notice Return how much `_token` could currently be kicked into auction.
* @dev This can be overridden by a strategist to implement custom logic.
* @param _token Address of the `_from` token.
* @return . The amount of `_token` ready to be auctioned off.
*/
function kickable(address _token) public view virtual returns (uint256) {
return ERC20(_token).balanceOf(address(this));
}
/**
* @dev To override if something other than just sending the loose balance
* of `_token` to the auction is desired, such as accruing and and claiming rewards.
*
* @param _token Address of the token being auctioned off
*/
function _auctionKicked(address _token) internal virtual returns (uint256) {
// Send any loose balance to the auction.
uint256 balance = ERC20(_token).balanceOf(address(this));
if (balance != 0) ERC20(_token).safeTransfer(auction, balance);
return ERC20(_token).balanceOf(auction);
}
/**
* @dev To override if something needs to be done before a take is completed.
* This can be used if the auctioned token only will be freed up when a `take`
* occurs.
* @param _token Address of the token being taken.
* @param _amountToTake Amount of `_token` needed.
* @param _amountToPay Amount of `want` that will be payed.
*/
function _preTake(
address _token,
uint256 _amountToTake,
uint256 _amountToPay
) internal virtual {}
/**
* @dev To override if a post take action is desired.
*
* This could be used to re-deploy the bought token back into the yield source,
* or in conjunction with {_preTake} to check that the price sold at was within
* some allowed range.
*
* @param _token Address of the token that the strategy was sent.
* @param _amountTaken Amount of the from token taken.
* @param _amountPayed Amount of `_token` that was sent to the strategy.
*/
function _postTake(
address _token,
uint256 _amountTaken,
uint256 _amountPayed
) internal virtual {}
/*//////////////////////////////////////////////////////////////
AUCTION HOOKS
//////////////////////////////////////////////////////////////*/
/**
* @notice External hook for the auction to call during a `kick`.
* @dev Will call the internal version for the strategist to override.
* @param _token Token being kicked into auction.
* @return . The amount of `_token` to be auctioned off.
*/
function auctionKicked(
address _token
) external virtual onlyAuction returns (uint256) {
return _auctionKicked(_token);
}
/**
* @notice External hook for the auction to call before a `take`.
* @dev Will call the internal version for the strategist to override.
* @param _token Token being taken in the auction.
* @param _amountToTake The amount of `_token` to be sent to the taker.
* @param _amountToPay Amount of `want` that will be payed.
*/
function preTake(
address _token,
uint256 _amountToTake,
uint256 _amountToPay
) external virtual onlyAuction {
_preTake(_token, _amountToTake, _amountToPay);
}
/**
* @notice External hook for the auction to call after a `take` completed.
* @dev Will call the internal version for the strategist to override.
* @param _token The `want` token that was sent to the strategy.
* @param _amountTaken Amount of the from token taken.
* @param _amountPayed Amount of `_token` that was sent to the strategy.
*/
function postTake(
address _token,
uint256 _amountTaken,
uint256 _amountPayed
) external virtual onlyAuction {
_postTake(_token, _amountTaken, _amountPayed);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;
import {BaseStrategy, ERC20} from "@tokenized-strategy/BaseStrategy.sol";
/**
* @title Base Health Check
* @author Yearn.finance
* @notice This contract can be inherited by any Yearn
* V3 strategy wishing to implement a health check during
* the `report` function in order to prevent any unexpected
* behavior from being permanently recorded as well as the
* `checkHealth` modifier.
*
* A strategist simply needs to inherit this contract. Set
* the limit ratios to the desired amounts and then
* override `_harvestAndReport()` just as they otherwise
* would. If the profit or loss that would be recorded is
* outside the acceptable bounds the tx will revert.
*
* The healthcheck does not prevent a strategy from reporting
* losses, but rather can make sure manual intervention is
* needed before reporting an unexpected loss or profit.
*/
abstract contract BaseHealthCheck is BaseStrategy {
// Can be used to determine if a healthcheck should be called.
// Defaults to true;
bool public doHealthCheck = true;
uint256 internal constant MAX_BPS = 10_000;
// Default profit limit to 100%.
uint16 private _profitLimitRatio = uint16(MAX_BPS);
// Defaults loss limit to 0.
uint16 private _lossLimitRatio;
constructor(
address _asset,
string memory _name
) BaseStrategy(_asset, _name) {}
/**
* @notice Returns the current profit limit ratio.
* @dev Use a getter function to keep the variable private.
* @return . The current profit limit ratio.
*/
function profitLimitRatio() public view returns (uint256) {
return _profitLimitRatio;
}
/**
* @notice Returns the current loss limit ratio.
* @dev Use a getter function to keep the variable private.
* @return . The current loss limit ratio.
*/
function lossLimitRatio() public view returns (uint256) {
return _lossLimitRatio;
}
/**
* @notice Set the `profitLimitRatio`.
* @dev Denominated in basis points. I.E. 1_000 == 10%.
* @param _newProfitLimitRatio The mew profit limit ratio.
*/
function setProfitLimitRatio(
uint256 _newProfitLimitRatio
) external onlyManagement {
_setProfitLimitRatio(_newProfitLimitRatio);
}
/**
* @dev Internally set the profit limit ratio. Denominated
* in basis points. I.E. 1_000 == 10%.
* @param _newProfitLimitRatio The mew profit limit ratio.
*/
function _setProfitLimitRatio(uint256 _newProfitLimitRatio) internal {
require(_newProfitLimitRatio > 0, "!zero profit");
require(_newProfitLimitRatio <= type(uint16).max, "!too high");
_profitLimitRatio = uint16(_newProfitLimitRatio);
}
/**
* @notice Set the `lossLimitRatio`.
* @dev Denominated in basis points. I.E. 1_000 == 10%.
* @param _newLossLimitRatio The new loss limit ratio.
*/
function setLossLimitRatio(
uint256 _newLossLimitRatio
) external onlyManagement {
_setLossLimitRatio(_newLossLimitRatio);
}
/**
* @dev Internally set the loss limit ratio. Denominated
* in basis points. I.E. 1_000 == 10%.
* @param _newLossLimitRatio The new loss limit ratio.
*/
function _setLossLimitRatio(uint256 _newLossLimitRatio) internal {
require(_newLossLimitRatio < MAX_BPS, "!loss limit");
_lossLimitRatio = uint16(_newLossLimitRatio);
}
/**
* @notice Turns the healthcheck on and off.
* @dev If turned off the next report will auto turn it back on.
* @param _doHealthCheck Bool if healthCheck should be done.
*/
function setDoHealthCheck(bool _doHealthCheck) public onlyManagement {
doHealthCheck = _doHealthCheck;
}
/**
* @notice OVerrides the default {harvestAndReport} to include a healthcheck.
* @return _totalAssets New totalAssets post report.
*/
function harvestAndReport()
external
override
onlySelf
returns (uint256 _totalAssets)
{
// Let the strategy report.
_totalAssets = _harvestAndReport();
// Run the healthcheck on the amount returned.
_executeHealthCheck(_totalAssets);
}
/**
* @dev To be called during a report to make sure the profit
* or loss being recorded is within the acceptable bound.
*
* @param _newTotalAssets The amount that will be reported.
*/
function _executeHealthCheck(uint256 _newTotalAssets) internal virtual {
if (!doHealthCheck) {
doHealthCheck = true;
return;
}
// Get the current total assets from the implementation.
uint256 currentTotalAssets = TokenizedStrategy.totalAssets();
if (_newTotalAssets > currentTotalAssets) {
require(
((_newTotalAssets - currentTotalAssets) <=
(currentTotalAssets * uint256(_profitLimitRatio)) /
MAX_BPS),
"healthCheck"
);
} else if (currentTotalAssets > _newTotalAssets) {
require(
(currentTotalAssets - _newTotalAssets <=
((currentTotalAssets * uint256(_lossLimitRatio)) /
MAX_BPS)),
"healthCheck"
);
}
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
// TokenizedStrategy interface used for internal view delegateCalls.
import {ITokenizedStrategy} from "./interfaces/ITokenizedStrategy.sol";
/**
* @title YearnV3 Base Strategy
* @author yearn.finance
* @notice
* BaseStrategy implements all of the required functionality to
* seamlessly integrate with the `TokenizedStrategy` implementation contract
* allowing anyone to easily build a fully permissionless ERC-4626 compliant
* Vault by inheriting this contract and overriding three simple functions.
* It utilizes an immutable proxy pattern that allows the BaseStrategy
* to remain simple and small. All standard logic is held within the
* `TokenizedStrategy` and is reused over any n strategies all using the
* `fallback` function to delegatecall the implementation so that strategists
* can only be concerned with writing their strategy specific code.
*
* This contract should be inherited and the three main abstract methods
* `_deployFunds`, `_freeFunds` and `_harvestAndReport` implemented to adapt
* the Strategy to the particular needs it has to generate yield. There are
* other optional methods that can be implemented to further customize
* the strategy if desired.
*
* All default storage for the strategy is controlled and updated by the
* `TokenizedStrategy`. The implementation holds a storage struct that
* contains all needed global variables in a manual storage slot. This
* means strategists can feel free to implement their own custom storage
* variables as they need with no concern of collisions. All global variables
* can be viewed within the Strategy by a simple call using the
* `TokenizedStrategy` variable. IE: TokenizedStrategy.globalVariable();.
*/
abstract contract BaseStrategy {
/*//////////////////////////////////////////////////////////////
MODIFIERS
//////////////////////////////////////////////////////////////*/
/**
* @dev Used on TokenizedStrategy callback functions to make sure it is post
* a delegateCall from this address to the TokenizedStrategy.
*/
modifier onlySelf() {
_onlySelf();
_;
}
/**
* @dev Use to assure that the call is coming from the strategies management.
*/
modifier onlyManagement() {
TokenizedStrategy.requireManagement(msg.sender);
_;
}
/**
* @dev Use to assure that the call is coming from either the strategies
* management or the keeper.
*/
modifier onlyKeepers() {
TokenizedStrategy.requireKeeperOrManagement(msg.sender);
_;
}
/**
* @dev Use to assure that the call is coming from either the strategies
* management or the emergency admin.
*/
modifier onlyEmergencyAuthorized() {
TokenizedStrategy.requireEmergencyAuthorized(msg.sender);
_;
}
/**
* @dev Require that the msg.sender is this address.
*/
function _onlySelf() internal view {
require(msg.sender == address(this), "!self");
}
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/**
* @dev This is the address of the TokenizedStrategy implementation
* contract that will be used by all strategies to handle the
* accounting, logic, storage etc.
*
* Any external calls to the that don't hit one of the functions
* defined in this base or the strategy will end up being forwarded
* through the fallback function, which will delegateCall this address.
*
* This address should be the same for every strategy, never be adjusted
* and always be checked before any integration with the Strategy.
*/
address public constant tokenizedStrategyAddress =
0xBB51273D6c746910C7C06fe718f30c936170feD0;
/*//////////////////////////////////////////////////////////////
IMMUTABLES
//////////////////////////////////////////////////////////////*/
/**
* @dev Underlying asset the Strategy is earning yield on.
* Stored here for cheap retrievals within the strategy.
*/
ERC20 internal immutable asset;
/**
* @dev This variable is set to address(this) during initialization of each strategy.
*
* This can be used to retrieve storage data within the strategy
* contract as if it were a linked library.
*
* i.e. uint256 totalAssets = TokenizedStrategy.totalAssets()
*
* Using address(this) will mean any calls using this variable will lead
* to a call to itself. Which will hit the fallback function and
* delegateCall that to the actual TokenizedStrategy.
*/
ITokenizedStrategy internal immutable TokenizedStrategy;
/**
* @notice Used to initialize the strategy on deployment.
*
* This will set the `TokenizedStrategy` variable for easy
* internal view calls to the implementation. As well as
* initializing the default storage variables based on the
* parameters and using the deployer for the permissioned roles.
*
* @param _asset Address of the underlying asset.
* @param _name Name the strategy will use.
*/
constructor(address _asset, string memory _name) {
asset = ERC20(_asset);
// Set instance of the implementation for internal use.
TokenizedStrategy = ITokenizedStrategy(address(this));
// Initialize the strategy's storage variables.
_delegateCall(
abi.encodeCall(
ITokenizedStrategy.initialize,
(_asset, _name, msg.sender, msg.sender, msg.sender)
)
);
// Store the tokenizedStrategyAddress at the standard implementation
// address storage slot so etherscan picks up the interface. This gets
// stored on initialization and never updated.
assembly {
sstore(
// keccak256('eip1967.proxy.implementation' - 1)
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc,
tokenizedStrategyAddress
)
}
}
/*//////////////////////////////////////////////////////////////
NEEDED TO BE OVERRIDDEN BY STRATEGIST
//////////////////////////////////////////////////////////////*/
/**
* @dev Can deploy up to '_amount' of 'asset' in the yield source.
*
* This function is called at the end of a {deposit} or {mint}
* call. Meaning that unless a whitelist is implemented it will
* be entirely permissionless and thus can be sandwiched or otherwise
* manipulated.
*
* @param _amount The amount of 'asset' that the strategy can attempt
* to deposit in the yield source.
*/
function _deployFunds(uint256 _amount) internal virtual;
/**
* @dev Should attempt to free the '_amount' of 'asset'.
*
* NOTE: The amount of 'asset' that is already loose has already
* been accounted for.
*
* This function is called during {withdraw} and {redeem} calls.
* Meaning that unless a whitelist is implemented it will be
* entirely permissionless and thus can be sandwiched or otherwise
* manipulated.
*
* Should not rely on asset.balanceOf(address(this)) calls other than
* for diff accounting purposes.
*
* Any difference between `_amount` and what is actually freed will be
* counted as a loss and passed on to the withdrawer. This means
* care should be taken in times of illiquidity. It may be better to revert
* if withdraws are simply illiquid so not to realize incorrect losses.
*
* @param _amount, The amount of 'asset' to be freed.
*/
function _freeFunds(uint256 _amount) internal virtual;
/**
* @dev Internal function to harvest all rewards, redeploy any idle
* funds and return an accurate accounting of all funds currently
* held by the Strategy.
*
* This should do any needed harvesting, rewards selling, accrual,
* redepositing etc. to get the most accurate view of current assets.
*
* NOTE: All applicable assets including loose assets should be
* accounted for in this function.
*
* Care should be taken when relying on oracles or swap values rather
* than actual amounts as all Strategy profit/loss accounting will
* be done based on this returned value.
*
* This can still be called post a shutdown, a strategist can check
* `TokenizedStrategy.isShutdown()` to decide if funds should be
* redeployed or simply realize any profits/losses.
*
* @return _totalAssets A trusted and accurate account for the total
* amount of 'asset' the strategy currently holds including idle funds.
*/
function _harvestAndReport()
internal
virtual
returns (uint256 _totalAssets);
/*//////////////////////////////////////////////////////////////
OPTIONAL TO OVERRIDE BY STRATEGIST
//////////////////////////////////////////////////////////////*/
/**
* @dev Optional function for strategist to override that can
* be called in between reports.
*
* If '_tend' is used tendTrigger() will also need to be overridden.
*
* This call can only be called by a permissioned role so may be
* through protected relays.
*
* This can be used to harvest and compound rewards, deposit idle funds,
* perform needed position maintenance or anything else that doesn't need
* a full report for.
*
* EX: A strategy that can not deposit funds without getting
* sandwiched can use the tend when a certain threshold
* of idle to totalAssets has been reached.
*
* This will have no effect on PPS of the strategy till report() is called.
*
* @param _totalIdle The current amount of idle funds that are available to deploy.
*/
function _tend(uint256 _totalIdle) internal virtual {}
/**
* @dev Optional trigger to override if tend() will be used by the strategy.
* This must be implemented if the strategy hopes to invoke _tend().
*
* @return . Should return true if tend() should be called by keeper or false if not.
*/
function _tendTrigger() internal view virtual returns (bool) {
return false;
}
/**
* @notice Returns if tend() should be called by a keeper.
*
* @return . Should return true if tend() should be called by keeper or false if not.
* @return . Calldata for the tend call.
*/
function tendTrigger() external view virtual returns (bool, bytes memory) {
return (
// Return the status of the tend trigger.
_tendTrigger(),
// And the needed calldata either way.
abi.encodeWithSelector(ITokenizedStrategy.tend.selector)
);
}
/**
* @notice Gets the max amount of `asset` that an address can deposit.
* @dev Defaults to an unlimited amount for any address. But can
* be overridden by strategists.
*
* This function will be called before any deposit or mints to enforce
* any limits desired by the strategist. This can be used for either a
* traditional deposit limit or for implementing a whitelist etc.
*
* EX:
* if(isAllowed[_owner]) return super.availableDepositLimit(_owner);
*
* This does not need to take into account any conversion rates
* from shares to assets. But should know that any non max uint256
* amounts may be converted to shares. So it is recommended to keep
* custom amounts low enough as not to cause overflow when multiplied
* by `totalSupply`.
*
* @param . The address that is depositing into the strategy.
* @return . The available amount the `_owner` can deposit in terms of `asset`
*/
function availableDepositLimit(
address /*_owner*/
) public view virtual returns (uint256) {
return type(uint256).max;
}
/**
* @notice Gets the max amount of `asset` that can be withdrawn.
* @dev Defaults to an unlimited amount for any address. But can
* be overridden by strategists.
*
* This function will be called before any withdraw or redeem to enforce
* any limits desired by the strategist. This can be used for illiquid
* or sandwichable strategies. It should never be lower than `totalIdle`.
*
* EX:
* return TokenIzedStrategy.totalIdle();
*
* This does not need to take into account the `_owner`'s share balance
* or conversion rates from shares to assets.
*
* @param . The address that is withdrawing from the strategy.
* @return . The available amount that can be withdrawn in terms of `asset`
*/
function availableWithdrawLimit(
address /*_owner*/
) public view virtual returns (uint256) {
return type(uint256).max;
}
/**
* @dev Optional function for a strategist to override that will
* allow management to manually withdraw deployed funds from the
* yield source if a strategy is shutdown.
*
* This should attempt to free `_amount`, noting that `_amount` may
* be more than is currently deployed.
*
* NOTE: This will not realize any profits or losses. A separate
* {report} will be needed in order to record any profit/loss. If
* a report may need to be called after a shutdown it is important
* to check if the strategy is shutdown during {_harvestAndReport}
* so that it does not simply re-deploy all funds that had been freed.
*
* EX:
* if(freeAsset > 0 && !TokenizedStrategy.isShutdown()) {
* depositFunds...
* }
*
* @param _amount The amount of asset to attempt to free.
*/
function _emergencyWithdraw(uint256 _amount) internal virtual {}
/*//////////////////////////////////////////////////////////////
TokenizedStrategy HOOKS
//////////////////////////////////////////////////////////////*/
/**
* @notice Can deploy up to '_amount' of 'asset' in yield source.
* @dev Callback for the TokenizedStrategy to call during a {deposit}
* or {mint} to tell the strategy it can deploy funds.
*
* Since this can only be called after a {deposit} or {mint}
* delegateCall to the TokenizedStrategy msg.sender == address(this).
*
* Unless a whitelist is implemented this will be entirely permissionless
* and thus can be sandwiched or otherwise manipulated.
*
* @param _amount The amount of 'asset' that the strategy can
* attempt to deposit in the yield source.
*/
function deployFunds(uint256 _amount) external virtual onlySelf {
_deployFunds(_amount);
}
/**
* @notice Should attempt to free the '_amount' of 'asset'.
* @dev Callback for the TokenizedStrategy to call during a withdraw
* or redeem to free the needed funds to service the withdraw.
*
* This can only be called after a 'withdraw' or 'redeem' delegateCall
* to the TokenizedStrategy so msg.sender == address(this).
*
* @param _amount The amount of 'asset' that the strategy should attempt to free up.
*/
function freeFunds(uint256 _amount) external virtual onlySelf {
_freeFunds(_amount);
}
/**
* @notice Returns the accurate amount of all funds currently
* held by the Strategy.
* @dev Callback for the TokenizedStrategy to call during a report to
* get an accurate accounting of assets the strategy controls.
*
* This can only be called after a report() delegateCall to the
* TokenizedStrategy so msg.sender == address(this).
*
* @return . A trusted and accurate account for the total amount
* of 'asset' the strategy currently holds including idle funds.
*/
function harvestAndReport() external virtual onlySelf returns (uint256) {
return _harvestAndReport();
}
/**
* @notice Will call the internal '_tend' when a keeper tends the strategy.
* @dev Callback for the TokenizedStrategy to initiate a _tend call in the strategy.
*
* This can only be called after a tend() delegateCall to the TokenizedStrategy
* so msg.sender == address(this).
*
* We name the function `tendThis` so that `tend` calls are forwarded to
* the TokenizedStrategy.
* @param _totalIdle The amount of current idle funds that can be
* deployed during the tend
*/
function tendThis(uint256 _totalIdle) external virtual onlySelf {
_tend(_totalIdle);
}
/**
* @notice Will call the internal '_emergencyWithdraw' function.
* @dev Callback for the TokenizedStrategy during an emergency withdraw.
*
* This can only be called after a emergencyWithdraw() delegateCall to
* the TokenizedStrategy so msg.sender == address(this).
*
* We name the function `shutdownWithdraw` so that `emergencyWithdraw`
* calls are forwarded to the TokenizedStrategy.
*
* @param _amount The amount of asset to attempt to free.
*/
function shutdownWithdraw(uint256 _amount) external virtual onlySelf {
_emergencyWithdraw(_amount);
}
/**
* @dev Function used to delegate call the TokenizedStrategy with
* certain `_calldata` and return any return values.
*
* This is used to setup the initial storage of the strategy, and
* can be used by strategist to forward any other call to the
* TokenizedStrategy implementation.
*
* @param _calldata The abi encoded calldata to use in delegatecall.
* @return . The return value if the call was successful in bytes.
*/
function _delegateCall(
bytes memory _calldata
) internal returns (bytes memory) {
// Delegate call the tokenized strategy with provided calldata.
(bool success, bytes memory result) = tokenizedStrategyAddress
.delegatecall(_calldata);
// If the call reverted. Return the error.
if (!success) {
assembly {
let ptr := mload(0x40)
let size := returndatasize()
returndatacopy(ptr, 0, size)
revert(ptr, size)
}
}
// Return the result.
return result;
}
/**
* @dev Execute a function on the TokenizedStrategy and return any value.
*
* This fallback function will be executed when any of the standard functions
* defined in the TokenizedStrategy are called since they wont be defined in
* this contract.
*
* It will delegatecall the TokenizedStrategy implementation with the exact
* calldata and return any relevant values.
*
*/
fallback() external {
// load our target address
address _tokenizedStrategyAddress = tokenizedStrategyAddress;
// Execute external function using delegatecall and return any value.
assembly {
// Copy function selector and any arguments.
calldatacopy(0, 0, calldatasize())
// Execute function delegatecall.
let result := delegatecall(
gas(),
_tokenizedStrategyAddress,
0,
calldatasize(),
0,
0
)
// Get any return value
returndatacopy(0, 0, returndatasize())
// Return any return value or error back to the caller
switch result
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.18;
import { Math } from '@openzeppelin/contracts/utils/math/Math.sol';
import { Bucket, Lender } from '../../interfaces/pool/commons/IPoolState.sol';
import { Maths } from './Maths.sol';
/**
@title Buckets library
@notice Internal library containing common logic for buckets management.
*/
library Buckets {
/**************/
/*** Events ***/
/**************/
// See `IPoolError` for descriptions
error BucketBankruptcyBlock();
/***********************************/
/*** Bucket Management Functions ***/
/***********************************/
/**
* @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 collateralAmountToAdd_ Additional collateral amount to add to bucket.
* @param bucketPrice_ Bucket price.
* @return addedLP_ Amount of bucket `LP` for the collateral amount added.
*/
function addCollateral(
Bucket storage bucket_,
address lender_,
uint256 deposit_,
uint256 collateralAmountToAdd_,
uint256 bucketPrice_
) 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
addedLP_ = collateralToLP(
bucket_.collateral,
bucket_.lps,
deposit_,
collateralAmountToAdd_,
bucketPrice_,
Math.Rounding.Down
);
// update bucket LP balance and collateral
// update bucket collateral
bucket_.collateral += collateralAmountToAdd_;
// update bucket and lender LP balance and deposit timestamp
bucket_.lps += addedLP_;
addLenderLP(bucket_, bankruptcyTime, lender_, addedLP_);
}
/**
* @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 bankruptcyTime_ Time when bucket become insolvent.
* @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 lpAmount_
) internal {
if (lpAmount_ != 0) {
Lender storage lender = bucket_.lenders[lender_];
if (bankruptcyTime_ >= lender.depositTime) lender.lps = lpAmount_;
else lender.lps += lpAmount_;
lender.depositTime = block.timestamp;
}
}
/**********************/
/*** View Functions ***/
/**********************/
/****************************/
/*** Assets to LP helpers ***/
/****************************/
/**
* @notice Returns the amount of bucket `LP` calculated for the given amount of collateral.
* @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 collateral_ The amount of collateral to calculate bucket LP for.
* @param bucketPrice_ Bucket's price.
* @param rounding_ The direction of rounding when calculating LP (down when adding, up when removing collateral from pool).
* @return Amount of `LP` calculated for the amount of collateral.
*/
function collateralToLP(
uint256 bucketCollateral_,
uint256 bucketLP_,
uint256 deposit_,
uint256 collateral_,
uint256 bucketPrice_,
Math.Rounding rounding_
) internal pure returns (uint256) {
// case when there's no deposit nor collateral in bucket
if (deposit_ == 0 && bucketCollateral_ == 0) return Maths.wmul(collateral_, bucketPrice_);
// case when there's deposit or collateral in bucket but no LP to cover
if (bucketLP_ == 0) return Maths.wmul(collateral_, bucketPrice_);
// case when there's deposit or collateral and bucket has LP balance
return Math.mulDiv(
bucketLP_,
collateral_ * bucketPrice_,
deposit_ * Maths.WAD + bucketCollateral_ * bucketPrice_,
rounding_
);
}
/**
* @notice Returns the amount of `LP` calculated for the given amount of quote tokens.
* @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 quoteTokens_ The amount of quote tokens to calculate `LP` amount for.
* @param bucketPrice_ Bucket's price.
* @param rounding_ The direction of rounding when calculating LP (down when adding, up when removing quote tokens from pool).
* @return The amount of `LP` coresponding to the given quote tokens in current bucket.
*/
function quoteTokensToLP(
uint256 bucketCollateral_,
uint256 bucketLP_,
uint256 deposit_,
uint256 quoteTokens_,
uint256 bucketPrice_,
Math.Rounding rounding_
) internal pure returns (uint256) {
// case when there's no deposit nor collateral in bucket
if (deposit_ == 0 && bucketCollateral_ == 0) return quoteTokens_;
// case when there's deposit or collateral in bucket but no LP to cover
if (bucketLP_ == 0) return quoteTokens_;
// case when there's deposit or collateral and bucket has LP balance
return Math.mulDiv(
bucketLP_,
quoteTokens_ * Maths.WAD,
deposit_ * Maths.WAD + bucketCollateral_ * bucketPrice_,
rounding_
);
}
/****************************/
/*** LP to Assets helpers ***/
/****************************/
/**
* @notice Returns the amount of collateral calculated for the given amount of lp
* @dev The value returned is not capped at collateral amount available in bucket.
* @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 lp_ The amount of LP to calculate collateral amount for.
* @param bucketPrice_ Bucket's price.
* @return The amount of collateral coresponding to the given `LP` in current bucket.
*/
function lpToCollateral(
uint256 bucketCollateral_,
uint256 bucketLP_,
uint256 deposit_,
uint256 lp_,
uint256 bucketPrice_,
Math.Rounding rounding_
) internal pure returns (uint256) {
// case when there's no deposit nor collateral in bucket
if (deposit_ == 0 && bucketCollateral_ == 0) return Maths.wdiv(lp_, bucketPrice_);
// case when there's deposit or collateral in bucket but no LP to cover
if (bucketLP_ == 0) return Maths.wdiv(lp_, bucketPrice_);
// case when there's deposit or collateral and bucket has LP balance
return Math.mulDiv(
deposit_ * Maths.WAD + bucketCollateral_ * bucketPrice_,
lp_,
bucketLP_ * bucketPrice_,
rounding_
);
}
/**
* @notice Returns the amount of quote token (in value) calculated for the given amount of `LP`.
* @dev The value returned is not capped at available bucket deposit.
* @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 lp_ The amount of LP to calculate quote tokens amount for.
* @param bucketPrice_ Bucket's price.
* @return The amount coresponding to the given quote tokens in current bucket.
*/
function lpToQuoteTokens(
uint256 bucketCollateral_,
uint256 bucketLP_,
uint256 deposit_,
uint256 lp_,
uint256 bucketPrice_,
Math.Rounding rounding_
) internal pure returns (uint256) {
// case when there's no deposit nor collateral in bucket
if (deposit_ == 0 && bucketCollateral_ == 0) return lp_;
// case when there's deposit or collateral in bucket but no LP to cover
if (bucketLP_ == 0) return lp_;
// case when there's deposit or collateral and bucket has LP balance
return Math.mulDiv(
deposit_ * Maths.WAD + bucketCollateral_ * bucketPrice_,
lp_,
bucketLP_ * Maths.WAD,
rounding_
);
}
/****************************/
/*** Exchange Rate helper ***/
/****************************/
/**
* @notice Returns the exchange rate for a given bucket (conversion of 1 lp to quote token).
* @param bucketCollateral_ Amount of collateral 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 bucketLP_,
uint256 bucketDeposit_,
uint256 bucketPrice_
) internal pure returns (uint256) {
return lpToQuoteTokens(
bucketCollateral_,
bucketLP_,
bucketDeposit_,
Maths.WAD,
bucketPrice_,
Math.Rounding.Up
);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;
contract Clonable {
/// @notice Set to the address to auto clone from.
address public original;
/**
* @notice Clone the contracts default `original` contract.
* @return Address of the new Minimal Proxy clone.
*/
function _clone() internal virtual returns (address) {
return _clone(original);
}
/**
* @notice Clone any `_original` contract.
* @return _newContract Address of the new Minimal Proxy clone.
*/
function _clone(
address _original
) internal virtual returns (address _newContract) {
// Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
bytes20 addressBytes = bytes20(_original);
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(
clone_code,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
mstore(add(clone_code, 0x14), addressBytes)
mstore(
add(clone_code, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
_newContract := create(0, clone_code, 0x37)
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.18;
import { Math } from '@openzeppelin/contracts/utils/math/Math.sol';
import { DepositsState } from '../../interfaces/pool/commons/IPoolState.sol';
import { _priceAt, MAX_FENWICK_INDEX } from '../helpers/PoolHelper.sol';
import { Maths } from './Maths.sol';
/**
@title Deposits library
@notice Internal library containing common logic for deposits management.
@dev Implemented as `Fenwick Tree` data structure.
*/
library Deposits {
/// @dev Max index supported in the `Fenwick` tree
uint256 internal constant SIZE = 8192;
/**************/
/*** Errors ***/
/**************/
// See `IPoolErrors` for descriptions
error InvalidAmount();
/**
* @notice Increase a value in the FenwickTree at an index.
* @dev Starts at leaf/target and moved up towards root
* @dev === Reverts on ===
* @dev unscaled amount to add is 0 `InvalidAmount()`
* @param deposits_ Deposits state struct.
* @param index_ The deposit index.
* @param unscaledAddAmount_ The unscaled amount to increase deposit by.
*/
function unscaledAdd(
DepositsState storage deposits_,
uint256 index_,
uint256 unscaledAddAmount_
) internal {
// revert if 0 amount is added.
if (unscaledAddAmount_ == 0) revert InvalidAmount();
// price buckets are indexed starting at 0, Fenwick bit logic is more elegant starting at 1
++index_;
// unscaledAddAmount_ is the raw amount to add directly to the value at index_, unaffected by the scale array
// For example, to denote an amount of deposit added to the array, we would need to call unscaledAdd with
// (deposit amount) / scale(index). There are two reasons for this:
// 1- scale(index) is often already known in the context of where unscaledAdd(..) is called, and we want to avoid
// redundant iterations through the Fenwick tree.
// 2- We often need to precisely change the value in the tree, avoiding the rounding that dividing by scale(index).
// This is more relevant to unscaledRemove(...), where we need to ensure the value is precisely set to 0, but we
// also prefer it here for consistency.
uint256 value;
uint256 scaling;
uint256 newValue;
while (index_ <= SIZE) {
value = deposits_.values[index_];
scaling = deposits_.scaling[index_];
// Compute the new value to be put in location index_
newValue = value + unscaledAddAmount_;
// Update unscaledAddAmount to propogate up the Fenwick tree
// Note: we can't just multiply addAmount_ by scaling[i_] due to rounding
// We need to track the precice change in values[i_] in order to ensure
// obliterated indices remain zero after subsequent adding to related indices
// if scaling==0, the actual scale value is 1, otherwise it is scaling
if (scaling != 0) unscaledAddAmount_ = Maths.wmul(newValue, scaling) - Maths.wmul(value, scaling);
deposits_.values[index_] = newValue;
// traverse upwards through tree via "update" route
index_ += lsb(index_);
}
}
/**
* @notice Finds index and sum of first bucket that EXCEEDS the given sum
* @dev Used in `LUP` calculation
* @param deposits_ Struct for deposits state.
* @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_`.
*/
function findIndexAndSumOfSum(
DepositsState storage deposits_,
uint256 targetSum_
) internal view returns (uint256 sumIndex_, uint256 sumIndexSum_, uint256 sumIndexScale_) {
// i iterates over bits from MSB to LSB. We check at each stage if the target sum is to the left or right of sumIndex_+i
uint256 i = 4096; // 1 << (_numBits - 1) = 1 << (13 - 1) = 4096
uint256 runningScale = Maths.WAD;
// We construct the target sumIndex_ bit by bit, from MSB to LSB. lowerIndexSum_ always maintains the sum
// up to the current value of sumIndex_
uint256 lowerIndexSum;
uint256 curIndex;
uint256 value;
uint256 scaling;
uint256 scaledValue;
while (i > 0) {
// Consider if the target index is less than or greater than sumIndex_ + i
curIndex = sumIndex_ + i;
value = deposits_.values[curIndex];
scaling = deposits_.scaling[curIndex];
// Compute sum up to sumIndex_ + i
scaledValue =
lowerIndexSum +
(
scaling != 0 ? Math.mulDiv(
runningScale * scaling,
value,
1e36
) : Maths.wmul(runningScale, value)
);
if (scaledValue < targetSum_) {
// Target value is too small, need to consider increasing sumIndex_ still
if (curIndex <= MAX_FENWICK_INDEX) {
// sumIndex_+i is in range of Fenwick prices. Target index has this bit set to 1.
sumIndex_ = curIndex;
lowerIndexSum = scaledValue;
}
} else {
// Target index has this bit set to 0
// scaling == 0 means scale factor == 1, otherwise scale factor == scaling
if (scaling != 0) runningScale = Maths.floorWmul(runningScale, scaling);
// Current scaledValue is <= targetSum_, it's a candidate value for sumIndexSum_
sumIndexSum_ = scaledValue;
sumIndexScale_ = runningScale;
}
// Shift i to next less significant bit
i = i >> 1;
}
}
/**
* @notice Finds index of passed sum. Helper function for `findIndexAndSumOfSum`.
* @dev Used in `LUP` calculation
* @param deposits_ Deposits state struct.
* @param sum_ The sum to find index for.
* @return sumIndex_ Smallest index where prefixsum greater than the sum.
*/
function findIndexOfSum(
DepositsState storage deposits_,
uint256 sum_
) internal view returns (uint256 sumIndex_) {
(sumIndex_,,) = findIndexAndSumOfSum(deposits_, sum_);
}
/**
* @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`.
*/
function lsb(
uint256 i_
) internal pure returns (uint256 lsb_) {
if (i_ != 0) {
// "i & (-i)"
lsb_ = i_ & ((i_ ^ 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) + 1);
}
}
/**
* @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`.
* @param deposits_ Deposits state struct.
* @param index_ The index to start scaling from.
* @param factor_ The factor to scale the values by.
*/
function mult(
DepositsState storage deposits_,
uint256 index_,
uint256 factor_
) internal {
// price buckets are indexed starting at 0, Fenwick bit logic is more elegant starting at 1
++index_;
uint256 sum;
uint256 value;
uint256 scaling;
uint256 bit = lsb(index_);
// Starting with the LSB of index, we iteratively move up towards the MSB of SIZE
// Case 1: the bit of index_ is set to 1. In this case, the entire subtree below index_
// is scaled. So, we include factor_ into scaling[index_], and remember in sum how much
// we increased the subtree by, so that we can use it in case we encounter 0 bits (below).
// Case 2: The bit of index_ is set to 0. In this case, consider the subtree below the node
// index_+bit. The subtree below that is not entirely scaled, but it does contain the
// 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) {
// Case 1 as described above
value = deposits_.values[index_];
scaling = deposits_.scaling[index_];
// Calc sum, will only be stored in range parents of starting node, index_
if (scaling != 0) {
// Note: we can't just multiply by factor_ - 1 in the following line, as rounding will
// cause obliterated indices to have nonzero values. Need to track the actual
// precise delta in the value array
uint256 scaledFactor = Maths.wmul(factor_, scaling);
sum += Maths.wmul(scaledFactor, value) - Maths.wmul(scaling, value);
// Apply scaling to all range parents less then starting node, index_
deposits_.scaling[index_] = scaledFactor;
} else {
// this node's scale factor is 1
sum += Maths.wmul(factor_, value) - value;
deposits_.scaling[index_] = factor_;
}
// Unset the bit in index to continue traversing up the Fenwick tree
index_ -= bit;
} else {
// Case 2 above. superRangeIndex is the index of the node to consider that
// contains the sub range that was already scaled in prior iteration
uint256 superRangeIndex = index_ + bit;
value = (deposits_.values[superRangeIndex] += sum);
scaling = deposits_.scaling[superRangeIndex];
// Need to be careful due to rounding to propagate actual changes upwards in tree.
// sum is always equal to the actual value we changed deposits_.values[] by
if (scaling != 0) sum = Maths.wmul(value, scaling) - Maths.wmul(value - sum, scaling);
}
// consider next most significant bit
bit = bit << 1;
}
}
/**
* @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 `sumIndex_`'s range to index `0`.
* @param deposits_ Deposits state struct.
* @param sumIndex_ The index to receive the prefix sum.
* @param sum_ The prefix sum from current index downwards.
*/
function prefixSum(
DepositsState storage deposits_,
uint256 sumIndex_
) internal view returns (uint256 sum_) {
// price buckets are indexed starting at 0, Fenwick bit logic is more elegant starting at 1
++sumIndex_;
uint256 runningScale = Maths.WAD; // Tracks scale(index_) as we move down Fenwick tree
uint256 j = SIZE; // bit that iterates from MSB to LSB
uint256 index = 0; // build up sumIndex bit by bit
// Used to terminate loop. We don't need to consider final 0 bits of sumIndex_
uint256 indexLSB = lsb(sumIndex_);
uint256 curIndex;
while (j >= indexLSB) {
curIndex = index + j;
// Skip considering indices outside bounds of Fenwick tree
if (curIndex > SIZE) continue;
// 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[curIndex];
if (sumIndex_ & j != 0) {
// node index + j of tree is included in sum
uint256 value = deposits_.values[curIndex];
// Accumulate in sum_, recall that scaled==0 means that the scale factor is actually 1
sum_ += scaled != 0 ? Math.mulDiv(
runningScale * scaled,
value,
1e36
) : Maths.wmul(runningScale, value);
// Build up index bit by bit
index = curIndex;
// terminate if we've already matched sumIndex_
if (index == sumIndex_) break;
} else {
// node is not included in sum, but its scale needs to be included for subsequent sums
if (scaled != 0) runningScale = Maths.floorWmul(runningScale, scaled);
}
// shift j to consider next less signficant bit
j = j >> 1;
}
}
/**
* @notice Decrease a node in the `FenwickTree` at an index.
* @dev Starts at leaf/target and moved up towards root.
* @dev === Reverts on ===
* @dev unscaled amount to remove is 0 `InvalidAmount()`
* @param deposits_ Deposits state struct.
* @param index_ The deposit index.
* @param unscaledRemoveAmount_ Unscaled amount to decrease deposit by.
*/
function unscaledRemove(
DepositsState storage deposits_,
uint256 index_,
uint256 unscaledRemoveAmount_
) internal {
// revert if 0 amount is removed.
if (unscaledRemoveAmount_ == 0) revert InvalidAmount();
// price buckets are indexed starting at 0, Fenwick bit logic is more elegant starting at 1
++index_;
// We operate with unscaledRemoveAmount_ here instead of a scaled quantity to avoid duplicate computation of scale factor
// (thus redundant iterations through the Fenwick tree), and ALSO so that we can set the value of a given deposit exactly
// to 0.
while (index_ <= SIZE) {
// Decrement deposits_ at index_ for removeAmount, storing new value in value
uint256 value = (deposits_.values[index_] -= unscaledRemoveAmount_);
uint256 scaling = deposits_.scaling[index_];
// If scale factor != 1, we need to adjust unscaledRemoveAmount by scale factor to adjust values further up in tree
// On the line below, it would be tempting to replace this with:
// unscaledRemoveAmount_ = Maths.wmul(unscaledRemoveAmount, scaling). This will introduce nonzero values up
// the tree due to rounding. It's important to compute the actual change in deposits_.values[index_]
// and propogate that upwards.
if (scaling != 0) unscaledRemoveAmount_ = Maths.wmul(value + unscaledRemoveAmount_, scaling) - Maths.wmul(value, scaling);
// Traverse upward through the "update" path of the Fenwick tree
index_ += lsb(index_);
}
}
/**
* @notice Scale tree starting from given index.
* @dev Starts at leaf/target and moved up towards root.
* @param deposits_ Deposits state struct.
* @param index_ The deposit index.
* @return scaled_ Scaled value.
*/
function scale(
DepositsState storage deposits_,
uint256 index_
) internal view returns (uint256 scaled_) {
// price buckets are indexed starting at 0, Fenwick bit logic is more elegant starting at 1
++index_;
// start with scaled_1 = 1
scaled_ = Maths.WAD;
while (index_ <= SIZE) {
// Traverse up through Fenwick tree via "update" path, accumulating scale factors as we go
uint256 scaling = deposits_.scaling[index_];
// scaling==0 means actual scale factor is 1
if (scaling != 0) scaled_ = Maths.wmul(scaled_, scaling);
index_ += lsb(index_);
}
}
/**
* @notice Returns sum of all deposits.
* @param deposits_ Deposits state struct.
* @return Sum of all deposits in tree.
*/
function treeSum(
DepositsState storage deposits_
) internal view returns (uint256) {
// In a scaled Fenwick tree, sum is at the root node and never scaled
return deposits_.values[SIZE];
}
/**
* @notice Returns deposit value for a given deposit index.
* @param deposits_ Deposits state struct.
* @param index_ The deposit index.
* @return depositValue_ Value of the deposit.
*/
function valueAt(
DepositsState storage deposits_,
uint256 index_
) internal view returns (uint256 depositValue_) {
// Get unscaled value at index and multiply by scale
depositValue_ = Maths.wmul(unscaledValueAt(deposits_, index_), scale(deposits_,index_));
}
/**
* @notice Returns unscaled (deposit without interest) deposit value for a given deposit index.
* @param deposits_ Deposits state struct.
* @param index_ The deposit index.
* @return unscaledDepositValue_ Value of unscaled deposit.
*/
function unscaledValueAt(
DepositsState storage deposits_,
uint256 index_
) internal view returns (uint256 unscaledDepositValue_) {
// In a scaled Fenwick tree, sum is at the root node, but needs to be scaled
++index_;
uint256 j = 1;
// Returns the unscaled value at the node. We consider the unscaled value for two reasons:
// 1- If we want to zero out deposit in bucket, we need to subtract the exact unscaled value
// 2- We may already have computed the scale factor, so we can avoid duplicate traversal
unscaledDepositValue_ = deposits_.values[index_];
uint256 curIndex;
uint256 value;
uint256 scaling;
while (j & index_ == 0) {
curIndex = index_ - j;
value = deposits_.values[curIndex];
scaling = deposits_.scaling[curIndex];
unscaledDepositValue_ -= scaling != 0 ? Maths.wmul(scaling, value) : value;
j = j << 1;
}
}
/**
* @notice Returns `LUP` for a given debt value (capped at min bucket price).
* @param deposits_ Deposits state struct.
* @param debt_ The debt amount to calculate `LUP` for.
* @return `LUP` for given debt.
*/
function getLup(
DepositsState storage deposits_,
uint256 debt_
) internal view returns (uint256) {
return _priceAt(findIndexOfSum(deposits_, debt_));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(address from, address to, uint256 amount) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
// Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
// decrementing then incrementing.
_balances[to] += amount;
}
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
unchecked {
// Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
_balances[account] += amount;
}
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
// Overflow not possible: amount <= accountBalance <= totalSupply.
_totalSupply -= amount;
}
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;
contract Governance {
/// @notice Emitted when the governance address is updated.
event GovernanceTransferred(
address indexed previousGovernance,
address indexed newGovernance
);
modifier onlyGovernance() {
_checkGovernance();
_;
}
/// @notice Checks if the msg sender is the governance.
function _checkGovernance() internal view virtual {
require(governance == msg.sender, "!governance");
}
/// @notice Address that can set the default base fee and provider
address public governance;
constructor(address _governance) {
governance = _governance;
emit GovernanceTransferred(address(0), _governance);
}
/**
* @notice Sets a new address as the governance of the contract.
* @dev Throws if the caller is not current governance.
* @param _newGovernance The new governance address.
*/
function transferGovernance(
address _newGovernance
) external virtual onlyGovernance {
require(_newGovernance != address(0), "ZERO ADDRESS");
address oldGovernance = governance;
governance = _newGovernance;
emit GovernanceTransferred(oldGovernance, _newGovernance);
}
}
pragma solidity ^0.8.18;
interface IAccount {
function send(address _target, bytes calldata _data) external payable;
function execute(address _target, bytes memory _data)
external
payable
returns (bytes32);
}
pragma solidity ^0.8.18;
interface IAccountFactory {
function createAccount() external returns (address);
function createAccount(address _user) external returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;
/**
* @title AjnaRedeemer
* @notice A contract that allows users to redeem their Ajna tokens for rewards. Pulls Ajan tokens from the Ajna Dripper contract.
*
* ROLES:
* - `OPERATOR_ROLE`: Can add weekly reward snapshot merkle tree roots.
* - `EMERGENCY_ROLE`: Can withdraw all the Ajna tokens to AjnaDripper contract in case of emergency.
*/
interface IAjnaRedeemer {
function deploymentWeek() external returns (uint256);
/**
* @dev Gets the current week number since the UNIX epoch.
*
* The week is defined as a 7 day period starting from Thursday at 00:00:00 UTC. This means that
* the week number changes on Thursdays, and that Thursday is always considered part of the current week.
*
* Effects:
* - Calculates the current week by dividing the block timestamp by 1 week.
*
* @return The current week number since the UNIX epoch as a uint256 value.
*/
function getCurrentWeek() external view returns (uint256);
/**
* @dev Adds a Merkle root for a given week.
*
* Requirements:
* - The caller must have the OPERATOR_ROLE.
* - The provided week number must be greater than or equal to the deployment week.
* - The provided week number must not be greater than the current week number.
* - The provided week must not already have a root set.
* - The drip call from the Ajna Dripper contract must succeed.
*
* Effects:
* - Sets the provided Merkle root for the given week.
*
* @param week The week number for which to add the Merkle root.
* @param root The Merkle root to be added for the specified week.
*/
function addRoot(uint256 week, bytes32 root) external;
/**
* @dev Retrieves the Merkle root for a given week.
*
* Requirements:
* - The provided week must have a root set.
*
* Effects:
* - None.
*
* @param week The week number for which to retrieve the Merkle root.
* @return The Merkle root associated with the specified week.
*
* @notice returns bytes32(0) if the provided week does not have a root set.
*/
function getRoot(uint256 week) external view returns (bytes32);
/**
* @dev Claims multiple rewards using Merkle proofs.
*
* Requirements:
* - The number of weeks, amounts, and proofs given must all match.
* - The caller must not have already claimed any of the specified weeks' rewards.
* - The provided proofs must be valid and eligible to claim a reward for their corresponding weeks and amounts.
*
* Effects:
* - Rewards will be transferred to the caller's account if the claims are successful.
* - Logs an event with the details of each successful claim.
*
* @param _weeks An array of week numbers for which to claim rewards.
* @param amounts An array of reward amounts to claim.
* @param proofs An array of Merkle proofs, one for each corresponding week and amount given.
*
* @notice This function throws an exception if the provided parameters are invalid or the caller has already claimed rewards for one or more of the specified weeks. Additionally, it transfers rewards to the caller if all claims are successful.
*/
function claimMultiple(
uint256[] calldata _weeks,
uint256[] calldata amounts,
bytes32[][] calldata proofs
) external;
/**
* @dev Determines if the caller is eligible to claim a reward for a specified week and amount using a Merkle proof.
*
* Requirements:
* - The provided Merkle proof must be valid for the given week and amount.
*
* @param proof A Merkle proof, which should be generated from the root of the Merkle tree for the corresponding week.
* @param week The number of the week for which to check eligibility.
* @param amount The amount of rewards to claim.
*
* @return A boolean indicating whether or not the caller is eligible to claim rewards for the given week and amount using the provided Merkle proof.
*
* @notice This function does not modify any state.
*/
function canClaim(
bytes32[] memory proof,
uint256 week,
uint256 amount
) external view returns (bool);
/**
* @dev Allows a user with the EMERGENCY_ROLE to withdraw all AjnaToken tokens held by this contract.
*
* Requirements:
* - The caller must have the EMERGENCY_ROLE.
* - The contract must hold a non-zero balance of AjnaToken tokens.
*
* Effects:
* - Transfers the entire balance of AjnaToken tokens held by this contract to the designated "drip" address.
*
* @notice This function should only be used in emergency situations and may result in significant loss of funds if used improperly.
*/
function emergencyWithdraw() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
interface IChainlinkAggregator {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
function latestRound() external view returns (uint256);
function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
event AnswerUpdated(
int256 indexed current,
uint256 indexed roundId,
uint256 updatedAt
);
event NewRound(
uint256 indexed roundId,
address indexed startedBy,
uint256 startedAt
);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;
import { IPool } from '../IPool.sol';
import { IERC20PoolBorrowerActions } from './IERC20PoolBorrowerActions.sol';
import { IERC20PoolLenderActions } from './IERC20PoolLenderActions.sol';
import { IERC20PoolImmutables } from './IERC20PoolImmutables.sol';
import { IERC20PoolEvents } from './IERC20PoolEvents.sol';
/**
* @title ERC20 Pool
*/
interface IERC20Pool is
IPool,
IERC20PoolLenderActions,
IERC20PoolBorrowerActions,
IERC20PoolImmutables,
IERC20PoolEvents
{
/**
* @notice Initializes a new pool, setting initial state variables.
* @param rate_ Initial interest rate of the pool (min accepted value 1%, max accepted value 10%).
*/
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_`.
*/
function bucketCollateralDust(
uint256 bucketIndex_
) external pure returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;
/**
* @title ERC20 Pool Borrower Actions
*/
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.
* @param borrowerAddress_ The borrower to whom collateral was pledged, and/or debt was drawn for.
* @param amountToBorrow_ The amount of quote tokens to borrow (`WAD` precision).
* @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 (`WAD` precision).
*/
function drawDebt(
address borrowerAddress_,
uint256 amountToBorrow_,
uint256 limitIndex_,
uint256 collateralToPledge_
) external;
/**
* @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.
* @param borrowerAddress_ The borrower whose loan is being interacted with.
* @param maxQuoteTokenAmountToRepay_ The max amount of quote tokens to repay (`WAD` precision).
* @param collateralAmountToPull_ The max amount of collateral to be puled from the pool (`WAD` precision).
* @param recipient_ The address to receive amount of pulled collateral.
* @param limitIndex_ Ensures `LUP` has not moved far from state when borrower pulls collateral.
* @return amountRepaid_ The amount of quote token repaid (`WAD` precision).
*/
function repayDebt(
address borrowerAddress_,
uint256 maxQuoteTokenAmountToRepay_,
uint256 collateralAmountToPull_,
address recipient_,
uint256 limitIndex_
) external returns (uint256 amountRepaid_);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;
/**
* @title ERC20 Pool Events
*/
interface IERC20PoolEvents {
/**
* @notice Emitted when actor adds claimable collateral to a bucket.
* @param actor Recipient that added collateral.
* @param index Index at which collateral were added.
* @param amount Amount of collateral added to the pool (`WAD` precision).
* @param lpAwarded Amount of `LP` awarded for the deposit (`WAD` precision).
*/
event AddCollateral(
address indexed actor,
uint256 indexed index,
uint256 amount,
uint256 lpAwarded
);
/**
* @notice Emitted when borrower draws debt from the pool, or adds collateral to the pool.
* @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 (`WAD` precision).
* @param collateralPledged Amount of collateral locked in the pool (`WAD` precision).
* @param lup `LUP` after borrow.
*/
event DrawDebt(
address indexed borrower,
uint256 amountBorrowed,
uint256 collateralPledged,
uint256 lup
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;
/**
* @title ERC20 Pool Immutables
*/
interface IERC20PoolImmutables {
/**
* @notice Returns the `collateralScale` immutable.
* @return The precision of the collateral `ERC20` token based on decimals.
*/
function collateralScale() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;
/**
* @title ERC20 Pool Lender Actions
*/
interface IERC20PoolLenderActions {
/**
* @notice Deposit claimable collateral into a specified bucket.
* @param amountToAdd_ Amount of collateral to deposit (`WAD` precision).
* @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 (`WAD` precision).
*/
function addCollateral(
uint256 amountToAdd_,
uint256 index_,
uint256 expiry_
) external returns (uint256 bucketLP_);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;
interface IERC3156FlashBorrower {
/**
* @dev Receive a flash loan.
* @param initiator The initiator of the loan.
* @param token The loan currency.
* @param amount The amount of tokens lent (token precision).
* @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`
*/
function onFlashLoan(
address initiator,
address token,
uint256 amount,
uint256 fee,
bytes calldata data
) external returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;
import { IERC3156FlashBorrower } from "./IERC3156FlashBorrower.sol";
interface IERC3156FlashLender {
/**
* @dev The amount of currency available to be lent.
* @param token_ The loan currency.
* @return The amount of `token` that can be borrowed (token precision).
*/
function maxFlashLoan(
address token_
) external view returns (uint256);
/**
* @dev The fee to be charged for a given loan.
* @param token_ The loan currency.
* @param amount_ The amount of tokens lent (token precision).
* @return The amount of `token` to be charged for the loan (token precision), on top of the returned principal .
*/
function flashFee(
address token_,
uint256 amount_
) external view returns (uint256);
/**
* @dev Initiate a flash loan.
* @param receiver_ The receiver of the tokens in the loan, and the receiver of the callback.
* @param token_ The loan currency.
* @param amount_ The amount of tokens lent (token precision).
* @param data_ Arbitrary data structure, intended to contain user-defined parameters.
* @return `True` when successful flashloan, `false` otherwise.
*/
function flashLoan(
IERC3156FlashBorrower receiver_,
address token_,
uint256 amount_,
bytes calldata data_
) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC4626.sol)
pragma solidity ^0.8.0;
import "../token/ERC20/IERC20.sol";
import "../token/ERC20/extensions/IERC20Metadata.sol";
/**
* @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in
* https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
*
* _Available since v4.7._
*/
interface IERC4626 is IERC20, IERC20Metadata {
event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);
event Withdraw(
address indexed sender,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
/**
* @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
*
* - MUST be an ERC-20 token contract.
* - MUST NOT revert.
*/
function asset() external view returns (address assetTokenAddress);
/**
* @dev Returns the total amount of the underlying asset that is “managed” by Vault.
*
* - SHOULD include any compounding that occurs from yield.
* - MUST be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT revert.
*/
function totalAssets() external view returns (uint256 totalManagedAssets);
/**
* @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToShares(uint256 assets) external view returns (uint256 shares);
/**
* @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToAssets(uint256 shares) external view returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
* through a deposit call.
*
* - MUST return a limited value if receiver is subject to some deposit limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
* - MUST NOT revert.
*/
function maxDeposit(address receiver) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
* call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
* in the same transaction.
* - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
* deposit would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewDeposit(uint256 assets) external view returns (uint256 shares);
/**
* @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* deposit execution, and are accounted for during deposit.
* - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function deposit(uint256 assets, address receiver) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
* - MUST return a limited value if receiver is subject to some mint limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
* - MUST NOT revert.
*/
function maxMint(address receiver) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
* in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
* same transaction.
* - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
* would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by minting.
*/
function previewMint(uint256 shares) external view returns (uint256 assets);
/**
* @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
* execution, and are accounted for during mint.
* - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function mint(uint256 shares, address receiver) external returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
* Vault, through a withdraw call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxWithdraw(address owner) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
* call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
* called
* in the same transaction.
* - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
* the withdrawal would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewWithdraw(uint256 assets) external view returns (uint256 shares);
/**
* @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* withdraw execution, and are accounted for during withdraw.
* - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
* through a redeem call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxRedeem(address owner) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
* in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
* same transaction.
* - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
* redemption would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by redeeming.
*/
function previewRedeem(uint256 shares) external view returns (uint256 assets);
/**
* @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* redeem execution, and are accounted for during redeem.
* - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;
import { IPoolBorrowerActions } from './commons/IPoolBorrowerActions.sol';
import { IPoolLPActions } from './commons/IPoolLPActions.sol';
import { IPoolLenderActions } from './commons/IPoolLenderActions.sol';
import { IPoolKickerActions } from './commons/IPoolKickerActions.sol';
import { IPoolTakerActions } from './commons/IPoolTakerActions.sol';
import { IPoolSettlerActions } from './commons/IPoolSettlerActions.sol';
import { IPoolImmutables } from './commons/IPoolImmutables.sol';
import { IPoolState } from './commons/IPoolState.sol';
import { IPoolDerivedState } from './commons/IPoolDerivedState.sol';
import { IPoolEvents } from './commons/IPoolEvents.sol';
import { IPoolErrors } from './commons/IPoolErrors.sol';
import { IERC3156FlashLender } from './IERC3156FlashLender.sol';
/**
* @title Base Pool Interface
*/
interface IPool is
IPoolBorrowerActions,
IPoolLPActions,
IPoolLenderActions,
IPoolKickerActions,
IPoolTakerActions,
IPoolSettlerActions,
IPoolImmutables,
IPoolState,
IPoolDerivedState,
IPoolEvents,
IPoolErrors,
IERC3156FlashLender
{
}
/// @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;
function decimals() external view returns (uint8);
}
/// @dev `ERC721` token interface.
interface IERC721Token {
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;
/**
* @title Pool Borrower Actions
*/
interface IPoolBorrowerActions {
/**
* @notice Called by fully collateralized borrowers to restamp the `Np to Tp ratio` of the loan (only if loan is fully collateralized and not in auction).
* The reason for stamping the `Np to Tp ratio` 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;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;
/**
* @title Pool Derived State
*/
interface IPoolDerivedState {
/**
* @notice Returns the exchange rate for a given bucket index.
* @param index_ The bucket index.
* @return exchangeRate_ Exchange rate of the bucket (`WAD` precision).
*/
function bucketExchangeRate(
uint256 index_
) external view returns (uint256 exchangeRate_);
/**
* @notice Returns the prefix sum of a given bucket.
* @param index_ The bucket index.
* @return The deposit up to given index (`WAD` precision).
*/
function depositUpToIndex(
uint256 index_
) external view returns (uint256);
/**
* @notice Returns the bucket index for a given debt amount.
* @param debt_ The debt amount to calculate bucket index for (`WAD` precision).
* @return Bucket index.
*/
function depositIndex(
uint256 debt_
) external view returns (uint256);
/**
* @notice Returns the total amount of quote tokens deposited in pool.
* @return Total amount of deposited quote tokens (`WAD` precision).
*/
function depositSize() external view returns (uint256);
/**
* @notice Returns the meaningful actual utilization of the pool.
* @return Deposit utilization (`WAD` precision).
*/
function depositUtilization() external view returns (uint256);
/**
* @notice Returns the scaling value of deposit at given index.
* @param index_ Deposit index.
* @return Deposit scaling (`WAD` precision).
*/
function depositScale(
uint256 index_
) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;
/**
* @title Pool Errors.
*/
interface IPoolErrors {
/**************************/
/*** Common Pool Errors ***/
/**************************/
/**
* @notice Adding liquidity above current auction price.
*/
error AddAboveAuctionPrice();
/**
* @notice The action cannot be executed on an active auction.
*/
error AuctionActive();
/**
* @notice Attempted auction to clear doesn't meet conditions.
*/
error AuctionNotClearable();
/**
* @notice Auction does not meet requirements to take liquidity.
*/
error AuctionNotTakeable();
/**
* @notice Head auction should be cleared prior of executing this action.
*/
error AuctionNotCleared();
/**
* @notice The auction price is greater than the arbed bucket price.
*/
error AuctionPriceGtBucketPrice();
/**
* @notice Pool already initialized.
*/
error AlreadyInitialized();
/**
* @notice Borrower is attempting to create or modify a loan such that their loan's quote token would be less than the pool's minimum debt amount.
*/
error AmountLTMinDebt();
/**
* @notice Recipient of borrowed quote tokens doesn't match the caller of the `drawDebt` function.
*/
error BorrowerNotSender();
/**
* @notice Borrower has a healthy over-collateralized position.
*/
error BorrowerOk();
/**
* @notice Borrower is attempting to borrow more quote token than they have collateral for.
*/
error BorrowerUnderCollateralized();
/**
* @notice Operation cannot be executed in the same block when bucket becomes insolvent.
*/
error BucketBankruptcyBlock();
/**
* @notice User attempted to merge collateral from a lower price bucket into a higher price bucket.
*/
error CannotMergeToHigherPrice();
/**
* @notice User attempted an operation which does not exceed the dust amount, or leaves behind less than the dust amount.
*/
error DustAmountNotExceeded();
/**
* @notice Callback invoked by `flashLoan` function did not return the expected hash (see `ERC-3156` spec).
*/
error FlashloanCallbackFailed();
/**
* @notice Balance of pool contract before flashloan is different than the balance after flashloan.
*/
error FlashloanIncorrectBalance();
/**
* @notice Pool cannot facilitate a flashloan for the specified token address.
*/
error FlashloanUnavailableForToken();
/**
* @notice User is attempting to move or pull more collateral than is available.
*/
error InsufficientCollateral();
/**
* @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.
*/
error InsufficientLP();
/**
* @notice Bucket must have more quote available in the bucket than the lender is attempting to claim.
*/
error InsufficientLiquidity();
/**
* @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.
*/
error InvalidIndex();
/**
* @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`.
*/
error LimitIndexExceeded();
/**
* @notice When moving quote token `HTP` must stay below `LUP`.
* @notice When removing quote token `HTP` must stay below `LUP`.
*/
error LUPBelowHTP();
/**
* @notice From index and to index arguments to move are the same.
*/
error MoveToSameIndex();
/**
* @notice Owner of the `LP` must have approved the new owner prior to transfer.
*/
error NoAllowance();
/**
* @notice Actor is attempting to take or clear an inactive auction.
*/
error NoAuction();
/**
* @notice No pool reserves are claimable.
*/
error NoReserves();
/**
* @notice Actor is attempting to take or clear an inactive reserves auction.
*/
error NoReservesAuction();
/**
* @notice Lender must have non-zero `LP` when attemptign to remove quote token from the pool.
*/
error NoClaim();
/**
* @notice Borrower has no debt to liquidate.
* @notice Borrower is attempting to repay when they have no outstanding debt.
*/
error NoDebt();
/**
* @notice Actor is attempting to kick with bucket price below the `LUP`.
*/
error PriceBelowLUP();
/**
* @notice Lender is attempting to remove quote tokens from a bucket that exists above active auction debt from top-of-book downward.
*/
error RemoveDepositLockedByAuctionDebt();
/**
* @notice User attempted to kick off a new auction less than `2` weeks since the last auction completed.
*/
error ReserveAuctionTooSoon();
/**
* @notice Current block timestamp has reached or exceeded a user-provided expiration.
*/
error TransactionExpired();
/**
* @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.
*/
error TransferToSameOwner();
/**
* @notice The DebtToCollateral of the loan to be inserted in loans heap is zero.
*/
error ZeroDebtToCollateral();
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;
/**
* @title Pool Events
*/
interface IPoolEvents {
/*********************/
/*** Lender events ***/
/*********************/
/**
* @notice Emitted when lender adds quote token to the pool.
* @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 (`WAD` precision).
* @param lpAwarded Amount of `LP` awarded for the deposit (`WAD` precision).
* @param lup `LUP` calculated after deposit.
*/
event AddQuoteToken(
address indexed lender,
uint256 indexed index,
uint256 amount,
uint256 lpAwarded,
uint256 lup
);
/**
* @notice Emitted when lender moves quote token from a bucket price to another.
* @param lender Recipient that moved quote tokens.
* @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 (`WAD` precision).
* @param lpRedeemedFrom Amount of `LP` removed from the `from` bucket (`WAD` precision).
* @param lpAwardedTo Amount of `LP` credited to the `to` bucket (`WAD` precision).
* @param lup `LUP` calculated after removal.
*/
event MoveQuoteToken(
address indexed lender,
uint256 indexed from,
uint256 indexed to,
uint256 amount,
uint256 lpRedeemedFrom,
uint256 lpAwardedTo,
uint256 lup
);
/**
* @notice Emitted when lender removes quote token from the pool.
* @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 (`WAD` precision).
* @param lpRedeemed Amount of `LP` exchanged for quote token (`WAD` precision).
* @param lup `LUP` calculated after removal.
*/
event RemoveQuoteToken(
address indexed lender,
uint256 indexed index,
uint256 amount,
uint256 lpRedeemed,
uint256 lup
);
/**
* @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 (`WAD` precision for `ERC20` pools, number of `NFT` tokens for `ERC721` pools) transferred to the claimer.
* @param lpRedeemed Amount of `LP` exchanged for quote token (`WAD` precision).
*/
event RemoveCollateral(
address indexed claimer,
uint256 indexed index,
uint256 amount,
uint256 lpRedeemed
);
/***********************/
/*** Borrower events ***/
/***********************/
/**
* @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 (`WAD` precision).
* @param collateralPulled The amount of collateral (`WAD` precision for `ERC20` pools, number of `NFT` tokens for `ERC721` pools) transferred to the claimer.
* @param lup `LUP` after repay.
*/
event RepayDebt(
address indexed borrower,
uint256 quoteRepaid,
uint256 collateralPulled,
uint256 lup
);
/**********************/
/*** Auction events ***/
/**********************/
/**
* @notice Emitted when a liquidation is initiated.
* @param borrower Identifies the loan being liquidated.
* @param debt Debt the liquidation will attempt to cover (`WAD` precision).
* @param collateral Amount of collateral up for liquidation (`WAD` precision for `ERC20` pools, number of `NFT` tokens for `ERC721` pools).
* @param bond Bond amount locked by kicker (`WAD` precision).
*/
event Kick(
address indexed borrower,
uint256 debt,
uint256 collateral,
uint256 bond
);
/**
* @notice Emitted when kickers are withdrawing funds posted as auction bonds.
* @param kicker The kicker withdrawing bonds.
* @param reciever The address receiving withdrawn bond amount.
* @param amount The bond amount that was withdrawn (`WAD` precision).
*/
event BondWithdrawn(
address indexed kicker,
address indexed reciever,
uint256 amount
);
/**
* @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 amount Amount of quote token used to purchase collateral (`WAD` precision).
* @param collateral Amount of collateral purchased with quote token (`WAD` precision).
* @param bondChange Impact of this take to the liquidation bond (`WAD` precision).
* @param isReward `True` if kicker was rewarded with `bondChange` amount, `false` if kicker was penalized.
* @dev amount / collateral implies the auction price.
*/
event BucketTake(
address indexed borrower,
uint256 index,
uint256 amount,
uint256 collateral,
uint256 bondChange,
bool isReward
);
/**
* @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 (`WAD` precision).
* @param lpAwardedKicker Amount of `LP` awarded to the actor who started the auction (`WAD` precision).
*/
event BucketTakeLPAwarded(
address indexed taker,
address indexed kicker,
uint256 lpAwardedTaker,
uint256 lpAwardedKicker
);
/**
* @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 (`WAD` precision).
* @param collateral Amount of collateral purchased with quote token (for `ERC20` pool, `WAD` precision) or number of `NFT`s purchased (for `ERC721` pool).
* @param bondChange Impact of this take to the liquidation bond (`WAD` precision).
* @param isReward `True` if kicker was rewarded with `bondChange` amount, `false` if kicker was penalized.
* @dev amount / collateral implies the auction price.
*/
event Take(
address indexed borrower,
uint256 amount,
uint256 collateral,
uint256 bondChange,
bool isReward
);
/**
* @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 (`WAD` precision).
* @dev When `amountRemaining_ == 0`, the auction has been completed cleared and removed from the queue.
*/
event Settle(
address indexed borrower,
uint256 settledDebt
);
/**
* @notice Emitted when auction is completed.
* @param borrower Address of borrower that exits auction.
* @param collateral Borrower's remaining collateral when auction completed (`WAD` precision).
*/
event AuctionSettle(
address indexed borrower,
uint256 collateral
);
/**
* @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 lp Amount of `LP` given to the borrower to compensate fractional collateral (if any, `WAD` precision).
* @param index Index of the bucket with `LP` to compensate fractional collateral.
*/
event AuctionNFTSettle(
address indexed borrower,
uint256 collateral,
uint256 lp,
uint256 index
);
/**
* @notice Emitted when a `Claimaible Reserve Auction` is started.
* @param claimableReservesRemaining Amount of claimable reserves which has not yet been taken (`WAD` precision).
* @param auctionPrice Current price at which `1` quote token may be purchased, denominated in `Ajna`.
* @param currentBurnEpoch Current burn epoch.
*/
event KickReserveAuction(
uint256 claimableReservesRemaining,
uint256 auctionPrice,
uint256 currentBurnEpoch
);
/**
* @notice Emitted when a `Claimaible Reserve Auction` is taken.
* @param claimableReservesRemaining Amount of claimable reserves which has not yet been taken (`WAD` precision).
* @param auctionPrice Current price at which `1` quote token may be purchased, denominated in `Ajna`.
* @param currentBurnEpoch Current burn epoch.
*/
event ReserveAuction(
uint256 claimableReservesRemaining,
uint256 auctionPrice,
uint256 currentBurnEpoch
);
/**************************/
/*** LP transfer events ***/
/**************************/
/**
* @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, `WAD` precision).
*/
event IncreaseLPAllowance(
address indexed owner,
address indexed spender,
uint256[] indexes,
uint256[] amounts
);
/**
* @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, `WAD` precision).
*/
event DecreaseLPAllowance(
address indexed owner,
address indexed spender,
uint256[] indexes,
uint256[] amounts
);
/**
* @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.
*/
event RevokeLPAllowance(
address indexed owner,
address indexed spender,
uint256[] indexes
);
/**
* @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,
address[] transferors
);
/**
* @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,
address[] transferors
);
/**
* @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 lp Amount of `LP` transferred (`WAD` precision).
*/
event TransferLP(
address owner,
address newOwner,
uint256[] indexes,
uint256 lp
);
/**************************/
/*** Pool common events ***/
/**************************/
/**
* @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 (`WAD` precision).
*/
event BucketBankruptcy(
uint256 indexed index,
uint256 lpForfeited
);
/**
* @notice Emitted when a flashloan is taken from pool.
* @param receiver The address receiving the flashloan.
* @param token The address of token flashloaned from pool.
* @param amount The amount of tokens flashloaned from pool (token precision).
*/
event Flashloan(
address indexed receiver,
address indexed token,
uint256 amount
);
/**
* @notice Emitted when a loan `Np to Tp ratio` is restamped.
* @param borrower Identifies the loan to update the `Np to Tp ratio`.
*/
event LoanStamped(
address indexed borrower
);
/**
* @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.
*/
event ResetInterestRate(
uint256 oldRate,
uint256 newRate
);
/**
* @notice Emitted when pool interest rate is updated.
* @param oldRate Old pool interest rate.
* @param newRate New pool interest rate.
*/
event UpdateInterestRate(
uint256 oldRate,
uint256 newRate
);
/**
* @notice Emitted when interest accural or update interest overflows.
*/
event InterestUpdateFailure();
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;
/**
* @title Pool Immutables
*/
interface IPoolImmutables {
/**
* @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.
*/
function collateralAddress() external pure returns (address);
/**
* @notice Returns the address of the pool's quote token.
*/
function quoteTokenAddress() external pure returns (address);
/**
* @notice Returns the `quoteTokenScale` state variable.
* @notice Token scale is also the minimum amount a lender may have in a bucket (dust amount).
* @return The precision of the quote `ERC20` token based on decimals.
*/
function quoteTokenScale() external pure returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;
/**
* @title Pool Kicker Actions
*/
interface IPoolKickerActions {
/********************/
/*** Liquidations ***/
/********************/
/**
* @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.
*/
function kick(
address borrower_,
uint256 npLimitIndex_
) external;
/**
* @notice Called by lenders to liquidate the top loan.
* @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 lenderKick(
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 (`WAD` precision). Constrained by claimable amounts and liquidity.
* @return withdrawnAmount_ The amount withdrawn (`WAD` precision).
*/
function withdrawBonds(
address recipient_,
uint256 maxAmount_
) external returns (uint256 withdrawnAmount_);
/***********************/
/*** Reserve Auction ***/
/***********************/
/**
* @notice Called by actor to start a `Claimable Reserve Auction` (`CRA`).
*/
function kickReserveAuction() external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;
/**
* @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 (`WAD` precision).
*/
function increaseLPAllowance(
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 (`WAD` precision).
*/
function decreaseLPAllowance(
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.
*/
function revokeLPAllowance(
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.
*/
function approveLPTransferors(
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.
*/
function revokeLPTransferors(
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.
*/
function transferLP(
address owner_,
address newOwner_,
uint256[] calldata indexes_
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;
/**
* @title Pool Lender Actions
*/
interface IPoolLenderActions {
/*********************************************/
/*** Quote/collateral management functions ***/
/*********************************************/
/**
* @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 (`WAD` precision).
* @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 (`WAD` precision).
* @return addedAmount_ The amount of quote token added (`WAD` precision).
*/
function addQuoteToken(
uint256 amount_,
uint256 index_,
uint256 expiry_
) external returns (uint256 bucketLP_, uint256 addedAmount_);
/**
* @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 (`WAD` precision).
* @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 (`WAD` precision).
* @return toBucketLP_ The amount of `LP` moved to destination bucket (`WAD` precision).
* @return movedAmount_ The amount of quote token moved (`WAD` precision).
*/
function moveQuoteToken(
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.
* @param maxAmount_ The amount of collateral (`WAD` precision for `ERC20` pools, number of `NFT` tokens for `ERC721` pools) to claim.
* @param index_ The bucket index from which collateral will be removed.
* @return removedAmount_ The amount of collateral removed (`WAD` precision).
* @return redeemedLP_ The amount of `LP` used for removing collateral amount (`WAD` precision).
*/
function removeCollateral(
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.
* @param maxAmount_ The max amount of quote token to be removed by a lender (`WAD` precision).
* @param index_ The bucket index from which quote tokens will be removed.
* @return removedAmount_ The amount of quote token removed (`WAD` precision).
* @return redeemedLP_ The amount of `LP` used for removing quote tokens amount (`WAD` precision).
*/
function removeQuoteToken(
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).
*/
function updateInterest() external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;
/**
* @title Pool Settler Actions
*/
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.
* @return collateralSettled_ Amount of collateral settled.
* @return isBorrowerSettled_ True if all borrower's debt is settled.
* @dev `maxDepth_` is used to prevent unbounded iteration clearing large liquidations.
*/
function settle(
address borrowerAddress_,
uint256 maxDepth_
) external returns (uint256 collateralSettled_, bool isBorrowerSettled_);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;
/**
* @title Pool State
*/
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 referencePrice_ Price used to determine auction start price.
* @return neutralPrice_ `Neutral Price` of auction.
* @return debtToCollateral_ Borrower debt to collateral, which is used in BPF for kicker's reward calculation.
* @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.
*/
function auctionInfo(address borrower_)
external
view
returns (
address kicker_,
uint256 bondFactor_,
uint256 bondSize_,
uint256 kickTime_,
uint256 referencePrice_,
uint256 neutralPrice_,
uint256 debtToCollateral_,
address head_,
address next_,
address prev_
);
/**
* @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 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_
);
/**
* @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 npTpRatio_ Np to Tp ratio of borrower at the time of last borrow or pull collateral.
*/
function borrowerInfo(address borrower_)
external
view
returns (
uint256 t0Debt_,
uint256 collateral_,
uint256 npTpRatio_
);
/**
* @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.
*/
function bucketInfo(uint256 index_)
external
view
returns (
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.
*/
function burnInfo(uint256 burnEventEpoch_) external view returns (uint256, uint256, uint256);
/**
* @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 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.
*/
function emasInfo()
external
view
returns (
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.
*/
function inflatorInfo()
external
view
returns (
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.
*/
function interestRateInfo()
external
view
returns (
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).
*/
function kickerInfo(address kicker_)
external
view
returns (
uint256 claimable_,
uint256 locked_
);
/**
* @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_,
address lender_
)
external
view
returns (
uint256 lpBalance_,
uint256 depositTime_
);
/**
* @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_
) 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 t0DebtToCollateral_ Borrower t0 debt to collateral.
*/
function loanInfo(
uint256 loanId_
)
external
view
returns (
address borrower_,
uint256 t0DebtToCollateral_
);
/**
* @notice Returns information about pool loans.
* @return maxBorrower_ Borrower address with highest t0 debt to collateral.
* @return maxT0DebtToCollateral_ Highest t0 debt to collateral in pool.
* @return noOfLoans_ Total number of loans.
*/
function loansInfo()
external
view
returns (
address maxBorrower_,
uint256 maxT0DebtToCollateral_,
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 lastKickedReserves_ Amount of reserves upon last kick, used to calculate price.
* @return totalInterestEarned_ Total interest earned by all lenders in the pool
*/
function reservesInfo()
external
view
returns (
uint256 liquidationBondEscrowed_,
uint256 reserveAuctionUnclaimed_,
uint256 reserveAuctionKicked_,
uint256 lastKickedReserves_,
uint256 totalInterestEarned_
);
/**
* @notice Returns the `pledgedCollateral` state variable.
* @return The total pledged collateral in the system, in WAD units.
*/
function pledgedCollateral() external view returns (uint256);
/**
* @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.
*/
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.
*/
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`.
* @return True if the transferor is approved by lender.
*/
function approvedTransferors(
address lender_,
address transferor_
) external view returns (bool);
}
/*********************/
/*** 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)
uint256 debt; // [WAD] previous update's debt
uint256 meaningfulDeposit; // [WAD] previous update's meaningfulDeposit
uint256 t0Debt2ToCollateral; // [WAD] utilization weight accumulator, tracks debt and collateral relationship accross borrowers
uint256 debtCol; // [WAD] previous debt squared to collateral
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
uint256 debtColEma; // [WAD] debt squared to collateral EMA, numerator to TU calculation
uint256 lupt0DebtEma; // [WAD] EMA of LUP * t0 debt, denominator to TU calculation
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
uint256 t0DebtInAuction; // [WAD] t0 debt in auction within pool
uint256 debt; // [WAD] total debt in pool, accrued in current block
uint256 collateral; // [WAD] total collateral pledged in pool
uint256 inflator; // [WAD] current pool inflator
bool isNewInterestAccrued; // true if new interest already accrued in current block
uint256 rate; // [WAD] pool's current interest rate
uint256 quoteTokenScale; // [WAD] quote token scale of the pool. Same as quote token dust.
}
/*********************/
/*** 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
uint256 bankruptcyTime; // Timestamp when bucket become insolvent, 0 if healthy
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 t0DebtToCollateral; // [WAD] Borrower t0 debt to collateral.
}
/// @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 npTpRatio; // [WAD] Np to Tp ratio at the time of last borrow or pull collateral.
}
/**********************/
/*** 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
address tail; // last address in auction queue
uint256 totalBondEscrowed; // [WAD] total amount of quote token posted as auction kick bonds
mapping(address => Liquidation) liquidations; // mapping of borrower address and auction details
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
uint96 kickTime; // timestamp when liquidation was started
address prev; // previous liquidated borrower in auctions queue
uint96 referencePrice; // [WAD] used to calculate auction start price
address next; // next liquidated borrower in auctions queue
uint160 bondSize; // [WAD] liquidation bond size
uint96 neutralPrice; // [WAD] Neutral Price when liquidation was started
uint256 debtToCollateral; // [WAD] Borrower debt to collateral, which is used in BPF for kicker's reward calculation
uint256 t0ReserveSettleAmount; // [WAD] Amount of t0Debt that could be settled via reserves in this 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 Auctions State ***/
/******************************/
/// @dev Struct holding reserve auction state.
struct ReserveAuctionState {
uint256 kicked; // Time a Claimable Reserve Auction was last kicked.
uint256 lastKickedReserves; // [WAD] Amount of reserves upon last kick, used to calculate price.
uint256 unclaimed; // [WAD] Amount of claimable reserves which has not been taken in the Claimable Reserve Auction.
uint256 latestBurnEventEpoch; // Latest burn event epoch.
uint256 totalAjnaBurned; // [WAD] Total ajna burned in the pool.
uint256 totalInterestEarned; // [WAD] Total interest earned by all lenders in the pool.
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`
uint256 totalBurned; // [WAD] burn amount accumulator
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;
/**
* @title Pool Taker Actions
*/
interface IPoolTakerActions {
/**
* @notice Called by actors to use quote token to arb higher-priced deposit off the book.
* @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(
address borrowerAddress_,
bool depositTake_,
uint256 index_
) external;
/**
* @notice Called by actors to purchase collateral from the auction in exchange for quote token.
* @param borrowerAddress_ Address of the borower take is being called upon.
* @param maxAmount_ Max amount of collateral that will be taken from the auction (`WAD` precision for `ERC20` pools, max number of `NFT`s for `ERC721` pools).
* @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.
* @return collateralTaken_ Amount of collateral taken from the auction (`WAD` precision for `ERC20` pools, max number of `NFT`s for `ERC721` pools).
*/
function take(
address borrowerAddress_,
uint256 maxAmount_,
address callee_,
bytes calldata data_
) external returns (uint256 collateralTaken_);
/***********************/
/*** Reserve Auction ***/
/***********************/
/**
* @notice Purchases claimable reserves during a `CRA` using `Ajna` token.
* @param maxAmount_ Maximum amount of quote token to purchase at the current auction price (`WAD` precision).
* @return amount_ Actual amount of reserves taken (`WAD` precision).
*/
function takeReserves(
uint256 maxAmount_
) external returns (uint256 amount_);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;
interface ITaker {
function auctionTakeCallback(
bytes32 _auctionId,
address _sender,
uint256 _amountTaken,
uint256 _amountNeeded,
bytes calldata _data
) external;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {IERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
// Interface that implements the 4626 standard and the implementation functions
interface ITokenizedStrategy is IERC4626, IERC20Permit {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event StrategyShutdown();
event NewTokenizedStrategy(
address indexed strategy,
address indexed asset,
string apiVersion
);
event Reported(
uint256 profit,
uint256 loss,
uint256 protocolFees,
uint256 performanceFees
);
event UpdatePerformanceFeeRecipient(
address indexed newPerformanceFeeRecipient
);
event UpdateKeeper(address indexed newKeeper);
event UpdatePerformanceFee(uint16 newPerformanceFee);
event UpdateManagement(address indexed newManagement);
event UpdateEmergencyAdmin(address indexed newEmergencyAdmin);
event UpdateProfitMaxUnlockTime(uint256 newProfitMaxUnlockTime);
event UpdatePendingManagement(address indexed newPendingManagement);
/*//////////////////////////////////////////////////////////////
INITIALIZATION
//////////////////////////////////////////////////////////////*/
function initialize(
address _asset,
string memory _name,
address _management,
address _performanceFeeRecipient,
address _keeper
) external;
/*//////////////////////////////////////////////////////////////
NON-STANDARD 4626 OPTIONS
//////////////////////////////////////////////////////////////*/
function withdraw(
uint256 assets,
address receiver,
address owner,
uint256 maxLoss
) external returns (uint256);
function redeem(
uint256 shares,
address receiver,
address owner,
uint256 maxLoss
) external returns (uint256);
/*//////////////////////////////////////////////////////////////
MODIFIER HELPERS
//////////////////////////////////////////////////////////////*/
function requireManagement(address _sender) external view;
function requireKeeperOrManagement(address _sender) external view;
function requireEmergencyAuthorized(address _sender) external view;
/*//////////////////////////////////////////////////////////////
KEEPERS FUNCTIONS
//////////////////////////////////////////////////////////////*/
function tend() external;
function report() external returns (uint256 _profit, uint256 _loss);
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
function MAX_FEE() external view returns (uint16);
function FACTORY() external view returns (address);
/*//////////////////////////////////////////////////////////////
GETTERS
//////////////////////////////////////////////////////////////*/
function apiVersion() external view returns (string memory);
function pricePerShare() external view returns (uint256);
function management() external view returns (address);
function pendingManagement() external view returns (address);
function keeper() external view returns (address);
function emergencyAdmin() external view returns (address);
function performanceFee() external view returns (uint16);
function performanceFeeRecipient() external view returns (address);
function fullProfitUnlockDate() external view returns (uint256);
function profitUnlockingRate() external view returns (uint256);
function profitMaxUnlockTime() external view returns (uint256);
function lastReport() external view returns (uint256);
function isShutdown() external view returns (bool);
function unlockedShares() external view returns (uint256);
/*//////////////////////////////////////////////////////////////
SETTERS
//////////////////////////////////////////////////////////////*/
function setPendingManagement(address) external;
function acceptManagement() external;
function setKeeper(address _keeper) external;
function setEmergencyAdmin(address _emergencyAdmin) external;
function setPerformanceFee(uint16 _performanceFee) external;
function setPerformanceFeeRecipient(
address _performanceFeeRecipient
) external;
function setProfitMaxUnlockTime(uint256 _profitMaxUnlockTime) external;
function shutdownStrategy() external;
function emergencyWithdraw(uint256 _amount) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for the Uniswap V3 Factory
/// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees
interface IUniswapV3Factory {
/// @notice Emitted when the owner of the factory is changed
/// @param oldOwner The owner before the owner was changed
/// @param newOwner The owner after the owner was changed
event OwnerChanged(address indexed oldOwner, address indexed newOwner);
/// @notice Emitted when a pool is created
/// @param token0 The first token of the pool by address sort order
/// @param token1 The second token of the pool by address sort order
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks
/// @param pool The address of the created pool
event PoolCreated(
address indexed token0,
address indexed token1,
uint24 indexed fee,
int24 tickSpacing,
address pool
);
/// @notice Emitted when a new fee amount is enabled for pool creation via the factory
/// @param fee The enabled fee, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee
event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);
/// @notice Returns the current owner of the factory
/// @dev Can be changed by the current owner via setOwner
/// @return The address of the factory owner
function owner() external view returns (address);
/// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled
/// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context
/// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee
/// @return The tick spacing
function feeAmountTickSpacing(uint24 fee) external view returns (int24);
/// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist
/// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @return pool The pool address
function getPool(
address tokenA,
address tokenB,
uint24 fee
) external view returns (address pool);
/// @notice Creates a pool for the given two tokens and fee
/// @param tokenA One of the two tokens in the desired pool
/// @param tokenB The other of the two tokens in the desired pool
/// @param fee The desired fee for the pool
/// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved
/// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments
/// are invalid.
/// @return pool The address of the newly created pool
function createPool(
address tokenA,
address tokenB,
uint24 fee
) external returns (address pool);
/// @notice Updates the owner of the factory
/// @dev Must be called by the current owner
/// @param _owner The new owner of the factory
function setOwner(address _owner) external;
/// @notice Enables a fee amount with the given tickSpacing
/// @dev Fee amounts may never be removed once enabled
/// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)
/// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount
function enableFeeAmount(uint24 fee, int24 tickSpacing) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import {IUniswapV3PoolImmutables} from './pool/IUniswapV3PoolImmutables.sol';
import {IUniswapV3PoolState} from './pool/IUniswapV3PoolState.sol';
import {IUniswapV3PoolDerivedState} from './pool/IUniswapV3PoolDerivedState.sol';
import {IUniswapV3PoolActions} from './pool/IUniswapV3PoolActions.sol';
import {IUniswapV3PoolOwnerActions} from './pool/IUniswapV3PoolOwnerActions.sol';
import {IUniswapV3PoolErrors} from './pool/IUniswapV3PoolErrors.sol';
import {IUniswapV3PoolEvents} from './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolErrors,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Errors emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolErrors {
error LOK();
error TLU();
error TLM();
error TUM();
error AI();
error M0();
error M1();
error AS();
error IIA();
error L();
error F0();
error F1();
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// @return tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// @return observationIndex The index of the last oracle observation that was written,
/// @return observationCardinality The current maximum number of observations stored in the pool,
/// @return observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// @return feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
/// @return The liquidity at the current price of the pool
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper
/// @return liquidityNet how much liquidity changes when the pool price crosses the tick,
/// @return feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// @return feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// @return tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// @return secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// @return secondsOutside the seconds spent on the other side of the tick from the current tick,
/// @return initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return liquidity The amount of liquidity in the position,
/// @return feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// @return feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// @return tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// @return tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// @return tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// @return secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// @return initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
pragma solidity ^0.8.18;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
}
pragma solidity ^0.8.18;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.18;
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { PRBMathSD59x18 } from "@prb-math/contracts/PRBMathSD59x18.sol";
import {
AuctionsState,
Borrower,
DepositsState,
Loan,
LoansState
} from '../../interfaces/pool/commons/IPoolState.sol';
import { _priceAt } from '../helpers/PoolHelper.sol';
import { Deposits } from './Deposits.sol';
import { Maths } from './Maths.sol';
/**
@title Loans library
@notice Internal library containing common logic for loans management.
@dev The `Loans` heap is a `Max Heap` data structure (complete binary tree), the root node is the loan with the highest t0 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 t0 threshold price of a loan's parent is always greater than or equal to the
t0 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 {
uint256 constant ROOT_INDEX = 1;
/**************/
/*** Errors ***/
/**************/
// See `IPoolErrors` for descriptions
error ZeroDebtToCollateral();
/***********************/
/*** Initialization ***/
/***********************/
/**
* @notice Initializes Loans Max Heap.
* @dev Organizes loans so `Highest t0 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));
}
/***********************************/
/*** Loans Management Functions ***/
/***********************************/
/**
* @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 borrower_ Borrower struct with borrower details.
* @param borrowerAddress_ Borrower's address to update.
* @param poolRate_ Pool's current rate.
* @param inAuction_ Whether the loan is in auction or not.
* @param npTpRatioUpdate_ Whether the Np to Tp ratio of borrower should be updated or not.
*/
function update(
LoansState storage loans_,
Borrower memory borrower_,
address borrowerAddress_,
uint256 poolRate_,
bool inAuction_,
bool npTpRatioUpdate_
) internal {
bool activeBorrower = borrower_.t0Debt != 0 && borrower_.collateral != 0;
uint256 t0DebtToCollateral = activeBorrower ? Maths.wdiv(borrower_.t0Debt, borrower_.collateral) : 0;
// loan not in auction, update t0 threshold price and position in heap
if (!inAuction_ ) {
// get the loan id inside the heap
uint256 loanId = loans_.indices[borrowerAddress_];
if (activeBorrower) {
// revert if t0 threshold price is zero
if (t0DebtToCollateral == 0) revert ZeroDebtToCollateral();
// update heap, insert if a new loan, update loan if already in heap
_upsert(loans_, borrowerAddress_, loanId, SafeCast.toUint96(t0DebtToCollateral));
// if loan is in heap and borrwer is no longer active (no debt, no collateral) then remove loan from heap
} else if (loanId != 0) {
remove(loans_, borrowerAddress_, loanId);
}
}
// update Np to Tp ratio of borrower
if (npTpRatioUpdate_) {
borrower_.npTpRatio = 1e18 + uint256(PRBMathSD59x18.sqrt(int256(poolRate_))) / 2;
}
// save borrower state
loans_.borrowers[borrowerAddress_] = borrower_;
}
/**************************************/
/*** Loans Heap Internal Functions ***/
/**************************************/
/**
* @notice Moves a `Loan` up the heap.
* @param loans_ Holds loans heap data.
* @param loan_ `Loan` to be moved.
* @param index_ Index of `Loan` to be moved to.
*/
function _bubbleUp(LoansState storage loans_, Loan memory loan_, uint index_) private {
uint256 count = loans_.loans.length;
if (index_ == ROOT_INDEX || loan_.t0DebtToCollateral <= loans_.loans[index_ / 2].t0DebtToCollateral){
_insert(loans_, loan_, index_, count);
} else {
_insert(loans_, loans_.loans[index_ / 2], index_, count);
_bubbleUp(loans_, loan_, index_ / 2);
}
}
/**
* @notice Moves a `Loan` down the heap.
* @param loans_ Holds loans heap data.
* @param loan_ `Loan` to be moved.
* @param index_ Index of `Loan` to be moved to.
*/
function _bubbleDown(LoansState storage loans_, Loan memory loan_, uint index_) private {
// Left child index.
uint cIndex = index_ * 2;
uint256 count = loans_.loans.length;
if (count <= cIndex) {
_insert(loans_, loan_, index_, count);
} else {
Loan memory largestChild = loans_.loans[cIndex];
if (count > cIndex + 1 && loans_.loans[cIndex + 1].t0DebtToCollateral > largestChild.t0DebtToCollateral) {
largestChild = loans_.loans[++cIndex];
}
if (largestChild.t0DebtToCollateral <= loan_.t0DebtToCollateral) {
_insert(loans_, loan_, index_, count);
} else {
_insert(loans_, largestChild, index_, count);
_bubbleDown(loans_, loan_, cIndex);
}
}
}
/**
* @notice Inserts a `Loan` in the heap.
* @param loans_ Holds loans heap data.
* @param loan_ `Loan` to be inserted.
* @param index_ Index of `Loan` to be inserted at.
*/
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] = 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 index_ Index of `Loan` to be removed.
*/
function remove(LoansState storage loans_, address borrower_, uint256 index_) internal {
delete loans_.indices[borrower_];
uint256 tailIndex = loans_.loans.length - 1;
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, index_);
_bubbleDown(loans_, loans_.loans[index_], index_);
}
}
/**
* @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 index_ Index of `Loan` to be upserted.
* @param t0DebtToCollateral_ Borrower t0 debt to collateral that is updated or inserted.
*/
function _upsert(
LoansState storage loans_,
address borrower_,
uint256 index_,
uint96 t0DebtToCollateral_
) internal {
// Loan exists, update in place.
if (index_ != 0) {
Loan memory currentLoan = loans_.loans[index_];
if (currentLoan.t0DebtToCollateral > t0DebtToCollateral_) {
currentLoan.t0DebtToCollateral = t0DebtToCollateral_;
_bubbleDown(loans_, currentLoan, index_);
} else {
currentLoan.t0DebtToCollateral = t0DebtToCollateral_;
_bubbleUp(loans_, currentLoan, index_);
}
// New loan, insert it
} else {
_bubbleUp(loans_, Loan(borrower_, t0DebtToCollateral_), loans_.loans.length);
}
}
/**********************/
/*** View Functions ***/
/**********************/
/**
* @notice Retreives `Loan` by index, `index_`.
* @param loans_ Holds loans heap data.
* @param index_ Index to retrieve `Loan`.
* @return `Loan` struct retrieved by index.
*/
function getByIndex(LoansState storage loans_, uint256 index_) internal view returns(Loan memory) {
return loans_.loans.length > index_ ? loans_.loans[index_] : Loan(address(0), 0);
}
/**
* @notice Retreives `Loan` with the highest t0 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);
}
/**
* @notice Returns number of loans in pool.
* @param loans_ Holds loans heap data.
* @return Number of loans in pool.
*/
function noOfLoans(LoansState storage loans_) internal view returns (uint256) {
return loans_.loans.length - 1;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.18;
/**
@title Maths library
@notice Internal library containing common maths.
*/
library Maths {
uint256 internal constant WAD = 1e18;
uint256 internal constant RAY = 1e27;
function wmul(uint256 x, uint256 y) internal pure returns (uint256) {
return (x * y + WAD / 2) / WAD;
}
function floorWmul(uint256 x, uint256 y) internal pure returns (uint256) {
return (x * y) / WAD;
}
function ceilWmul(uint256 x, uint256 y) internal pure returns (uint256) {
return (x * y + WAD - 1) / WAD;
}
function wdiv(uint256 x, uint256 y) internal pure returns (uint256) {
return (x * WAD + y / 2) / y;
}
function floorWdiv(uint256 x, uint256 y) internal pure returns (uint256) {
return (x * WAD) / y;
}
function ceilWdiv(uint256 x, uint256 y) internal pure returns (uint256) {
return (x * WAD + y - 1) / y;
}
function ceilDiv(uint256 x, uint256 y) internal pure returns (uint256) {
return (x + y - 1) / y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256) {
return x >= y ? x : y;
}
function min(uint256 x, uint256 y) internal pure returns (uint256) {
return x <= y ? x : y;
}
function wad(uint256 x) internal pure returns (uint256) {
return x * WAD;
}
function rmul(uint256 x, uint256 y) internal pure returns (uint256) {
return (x * y + RAY / 2) / RAY;
}
function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
/*************************/
/*** Integer Functions ***/
/*************************/
function maxInt(int256 x, int256 y) internal pure returns (int256) {
return x >= y ? x : y;
}
function minInt(int256 x, int256 y) internal pure returns (int256) {
return x <= y ? x : y;
}
}
// SPDX-License-Identifier: Unlicense
pragma solidity >=0.8.4;
/// @notice Emitted when the result overflows uint256.
error PRBMath__MulDivFixedPointOverflow(uint256 prod1);
/// @notice Emitted when the result overflows uint256.
error PRBMath__MulDivOverflow(uint256 prod1, uint256 denominator);
/// @notice Emitted when one of the inputs is type(int256).min.
error PRBMath__MulDivSignedInputTooSmall();
/// @notice Emitted when the intermediary absolute result overflows int256.
error PRBMath__MulDivSignedOverflow(uint256 rAbs);
/// @notice Emitted when the input is MIN_SD59x18.
error PRBMathSD59x18__AbsInputTooSmall();
/// @notice Emitted when ceiling a number overflows SD59x18.
error PRBMathSD59x18__CeilOverflow(int256 x);
/// @notice Emitted when one of the inputs is MIN_SD59x18.
error PRBMathSD59x18__DivInputTooSmall();
/// @notice Emitted when one of the intermediary unsigned results overflows SD59x18.
error PRBMathSD59x18__DivOverflow(uint256 rAbs);
/// @notice Emitted when the input is greater than 133.084258667509499441.
error PRBMathSD59x18__ExpInputTooBig(int256 x);
/// @notice Emitted when the input is greater than 192.
error PRBMathSD59x18__Exp2InputTooBig(int256 x);
/// @notice Emitted when flooring a number underflows SD59x18.
error PRBMathSD59x18__FloorUnderflow(int256 x);
/// @notice Emitted when converting a basic integer to the fixed-point format overflows SD59x18.
error PRBMathSD59x18__FromIntOverflow(int256 x);
/// @notice Emitted when converting a basic integer to the fixed-point format underflows SD59x18.
error PRBMathSD59x18__FromIntUnderflow(int256 x);
/// @notice Emitted when the product of the inputs is negative.
error PRBMathSD59x18__GmNegativeProduct(int256 x, int256 y);
/// @notice Emitted when multiplying the inputs overflows SD59x18.
error PRBMathSD59x18__GmOverflow(int256 x, int256 y);
/// @notice Emitted when the input is less than or equal to zero.
error PRBMathSD59x18__LogInputTooSmall(int256 x);
/// @notice Emitted when one of the inputs is MIN_SD59x18.
error PRBMathSD59x18__MulInputTooSmall();
/// @notice Emitted when the intermediary absolute result overflows SD59x18.
error PRBMathSD59x18__MulOverflow(uint256 rAbs);
/// @notice Emitted when the intermediary absolute result overflows SD59x18.
error PRBMathSD59x18__PowuOverflow(uint256 rAbs);
/// @notice Emitted when the input is negative.
error PRBMathSD59x18__SqrtNegativeInput(int256 x);
/// @notice Emitted when the calculating the square root overflows SD59x18.
error PRBMathSD59x18__SqrtOverflow(int256 x);
/// @notice Emitted when addition overflows UD60x18.
error PRBMathUD60x18__AddOverflow(uint256 x, uint256 y);
/// @notice Emitted when ceiling a number overflows UD60x18.
error PRBMathUD60x18__CeilOverflow(uint256 x);
/// @notice Emitted when the input is greater than 133.084258667509499441.
error PRBMathUD60x18__ExpInputTooBig(uint256 x);
/// @notice Emitted when the input is greater than 192.
error PRBMathUD60x18__Exp2InputTooBig(uint256 x);
/// @notice Emitted when converting a basic integer to the fixed-point format format overflows UD60x18.
error PRBMathUD60x18__FromUintOverflow(uint256 x);
/// @notice Emitted when multiplying the inputs overflows UD60x18.
error PRBMathUD60x18__GmOverflow(uint256 x, uint256 y);
/// @notice Emitted when the input is less than 1.
error PRBMathUD60x18__LogInputTooSmall(uint256 x);
/// @notice Emitted when the calculating the square root overflows UD60x18.
error PRBMathUD60x18__SqrtOverflow(uint256 x);
/// @notice Emitted when subtraction underflows UD60x18.
error PRBMathUD60x18__SubUnderflow(uint256 x, uint256 y);
/// @dev Common mathematical functions used in both PRBMathSD59x18 and PRBMathUD60x18. Note that this shared library
/// does not always assume the signed 59.18-decimal fixed-point or the unsigned 60.18-decimal fixed-point
/// representation. When it does not, it is explicitly mentioned in the NatSpec documentation.
library PRBMath {
/// STRUCTS ///
struct SD59x18 {
int256 value;
}
struct UD60x18 {
uint256 value;
}
/// STORAGE ///
/// @dev How many trailing decimals can be represented.
uint256 internal constant SCALE = 1e18;
/// @dev Largest power of two divisor of SCALE.
uint256 internal constant SCALE_LPOTD = 262144;
/// @dev SCALE inverted mod 2^256.
uint256 internal constant SCALE_INVERSE =
78156646155174841979727994598816262306175212592076161876661_508869554232690281;
/// FUNCTIONS ///
/// @notice Calculates the binary exponent of x using the binary fraction method.
/// @dev Has to use 192.64-bit fixed-point numbers.
/// See https://ethereum.stackexchange.com/a/96594/24693.
/// @param x The exponent as an unsigned 192.64-bit fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
function exp2(uint256 x) internal pure returns (uint256 result) {
unchecked {
// Start from 0.5 in the 192.64-bit fixed-point format.
result = 0x800000000000000000000000000000000000000000000000;
// Multiply the result by root(2, 2^-i) when the bit at position i is 1. None of the intermediary results overflows
// because the initial result is 2^191 and all magic factors are less than 2^65.
if (x & 0x8000000000000000 > 0) {
result = (result * 0x16A09E667F3BCC909) >> 64;
}
if (x & 0x4000000000000000 > 0) {
result = (result * 0x1306FE0A31B7152DF) >> 64;
}
if (x & 0x2000000000000000 > 0) {
result = (result * 0x1172B83C7D517ADCE) >> 64;
}
if (x & 0x1000000000000000 > 0) {
result = (result * 0x10B5586CF9890F62A) >> 64;
}
if (x & 0x800000000000000 > 0) {
result = (result * 0x1059B0D31585743AE) >> 64;
}
if (x & 0x400000000000000 > 0) {
result = (result * 0x102C9A3E778060EE7) >> 64;
}
if (x & 0x200000000000000 > 0) {
result = (result * 0x10163DA9FB33356D8) >> 64;
}
if (x & 0x100000000000000 > 0) {
result = (result * 0x100B1AFA5ABCBED61) >> 64;
}
if (x & 0x80000000000000 > 0) {
result = (result * 0x10058C86DA1C09EA2) >> 64;
}
if (x & 0x40000000000000 > 0) {
result = (result * 0x1002C605E2E8CEC50) >> 64;
}
if (x & 0x20000000000000 > 0) {
result = (result * 0x100162F3904051FA1) >> 64;
}
if (x & 0x10000000000000 > 0) {
result = (result * 0x1000B175EFFDC76BA) >> 64;
}
if (x & 0x8000000000000 > 0) {
result = (result * 0x100058BA01FB9F96D) >> 64;
}
if (x & 0x4000000000000 > 0) {
result = (result * 0x10002C5CC37DA9492) >> 64;
}
if (x & 0x2000000000000 > 0) {
result = (result * 0x1000162E525EE0547) >> 64;
}
if (x & 0x1000000000000 > 0) {
result = (result * 0x10000B17255775C04) >> 64;
}
if (x & 0x800000000000 > 0) {
result = (result * 0x1000058B91B5BC9AE) >> 64;
}
if (x & 0x400000000000 > 0) {
result = (result * 0x100002C5C89D5EC6D) >> 64;
}
if (x & 0x200000000000 > 0) {
result = (result * 0x10000162E43F4F831) >> 64;
}
if (x & 0x100000000000 > 0) {
result = (result * 0x100000B1721BCFC9A) >> 64;
}
if (x & 0x80000000000 > 0) {
result = (result * 0x10000058B90CF1E6E) >> 64;
}
if (x & 0x40000000000 > 0) {
result = (result * 0x1000002C5C863B73F) >> 64;
}
if (x & 0x20000000000 > 0) {
result = (result * 0x100000162E430E5A2) >> 64;
}
if (x & 0x10000000000 > 0) {
result = (result * 0x1000000B172183551) >> 64;
}
if (x & 0x8000000000 > 0) {
result = (result * 0x100000058B90C0B49) >> 64;
}
if (x & 0x4000000000 > 0) {
result = (result * 0x10000002C5C8601CC) >> 64;
}
if (x & 0x2000000000 > 0) {
result = (result * 0x1000000162E42FFF0) >> 64;
}
if (x & 0x1000000000 > 0) {
result = (result * 0x10000000B17217FBB) >> 64;
}
if (x & 0x800000000 > 0) {
result = (result * 0x1000000058B90BFCE) >> 64;
}
if (x & 0x400000000 > 0) {
result = (result * 0x100000002C5C85FE3) >> 64;
}
if (x & 0x200000000 > 0) {
result = (result * 0x10000000162E42FF1) >> 64;
}
if (x & 0x100000000 > 0) {
result = (result * 0x100000000B17217F8) >> 64;
}
if (x & 0x80000000 > 0) {
result = (result * 0x10000000058B90BFC) >> 64;
}
if (x & 0x40000000 > 0) {
result = (result * 0x1000000002C5C85FE) >> 64;
}
if (x & 0x20000000 > 0) {
result = (result * 0x100000000162E42FF) >> 64;
}
if (x & 0x10000000 > 0) {
result = (result * 0x1000000000B17217F) >> 64;
}
if (x & 0x8000000 > 0) {
result = (result * 0x100000000058B90C0) >> 64;
}
if (x & 0x4000000 > 0) {
result = (result * 0x10000000002C5C860) >> 64;
}
if (x & 0x2000000 > 0) {
result = (result * 0x1000000000162E430) >> 64;
}
if (x & 0x1000000 > 0) {
result = (result * 0x10000000000B17218) >> 64;
}
if (x & 0x800000 > 0) {
result = (result * 0x1000000000058B90C) >> 64;
}
if (x & 0x400000 > 0) {
result = (result * 0x100000000002C5C86) >> 64;
}
if (x & 0x200000 > 0) {
result = (result * 0x10000000000162E43) >> 64;
}
if (x & 0x100000 > 0) {
result = (result * 0x100000000000B1721) >> 64;
}
if (x & 0x80000 > 0) {
result = (result * 0x10000000000058B91) >> 64;
}
if (x & 0x40000 > 0) {
result = (result * 0x1000000000002C5C8) >> 64;
}
if (x & 0x20000 > 0) {
result = (result * 0x100000000000162E4) >> 64;
}
if (x & 0x10000 > 0) {
result = (result * 0x1000000000000B172) >> 64;
}
if (x & 0x8000 > 0) {
result = (result * 0x100000000000058B9) >> 64;
}
if (x & 0x4000 > 0) {
result = (result * 0x10000000000002C5D) >> 64;
}
if (x & 0x2000 > 0) {
result = (result * 0x1000000000000162E) >> 64;
}
if (x & 0x1000 > 0) {
result = (result * 0x10000000000000B17) >> 64;
}
if (x & 0x800 > 0) {
result = (result * 0x1000000000000058C) >> 64;
}
if (x & 0x400 > 0) {
result = (result * 0x100000000000002C6) >> 64;
}
if (x & 0x200 > 0) {
result = (result * 0x10000000000000163) >> 64;
}
if (x & 0x100 > 0) {
result = (result * 0x100000000000000B1) >> 64;
}
if (x & 0x80 > 0) {
result = (result * 0x10000000000000059) >> 64;
}
if (x & 0x40 > 0) {
result = (result * 0x1000000000000002C) >> 64;
}
if (x & 0x20 > 0) {
result = (result * 0x10000000000000016) >> 64;
}
if (x & 0x10 > 0) {
result = (result * 0x1000000000000000B) >> 64;
}
if (x & 0x8 > 0) {
result = (result * 0x10000000000000006) >> 64;
}
if (x & 0x4 > 0) {
result = (result * 0x10000000000000003) >> 64;
}
if (x & 0x2 > 0) {
result = (result * 0x10000000000000001) >> 64;
}
if (x & 0x1 > 0) {
result = (result * 0x10000000000000001) >> 64;
}
// We're doing two things at the same time:
//
// 1. Multiply the result by 2^n + 1, where "2^n" is the integer part and the one is added to account for
// the fact that we initially set the result to 0.5. This is accomplished by subtracting from 191
// rather than 192.
// 2. Convert the result to the unsigned 60.18-decimal fixed-point format.
//
// This works because 2^(191-ip) = 2^ip / 2^191, where "ip" is the integer part "2^n".
result *= SCALE;
result >>= (191 - (x >> 64));
}
}
/// @notice Finds the zero-based index of the first one in the binary representation of x.
/// @dev See the note on msb in the "Find First Set" Wikipedia article https://en.wikipedia.org/wiki/Find_first_set
/// @param x The uint256 number for which to find the index of the most significant bit.
/// @return msb The index of the most significant bit as an uint256.
function mostSignificantBit(uint256 x) internal pure returns (uint256 msb) {
if (x >= 2**128) {
x >>= 128;
msb += 128;
}
if (x >= 2**64) {
x >>= 64;
msb += 64;
}
if (x >= 2**32) {
x >>= 32;
msb += 32;
}
if (x >= 2**16) {
x >>= 16;
msb += 16;
}
if (x >= 2**8) {
x >>= 8;
msb += 8;
}
if (x >= 2**4) {
x >>= 4;
msb += 4;
}
if (x >= 2**2) {
x >>= 2;
msb += 2;
}
if (x >= 2**1) {
// No need to shift x any more.
msb += 1;
}
}
/// @notice Calculates floor(x*y÷denominator) with full precision.
///
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv.
///
/// Requirements:
/// - The denominator cannot be zero.
/// - The result must fit within uint256.
///
/// Caveats:
/// - This function does not work with fixed-point numbers.
///
/// @param x The multiplicand as an uint256.
/// @param y The multiplier as an uint256.
/// @param denominator The divisor as an uint256.
/// @return result The result as an uint256.
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
unchecked {
result = prod0 / denominator;
}
return result;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (prod1 >= denominator) {
revert PRBMath__MulDivOverflow(prod1, denominator);
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
unchecked {
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 lpotdod = denominator & (~denominator + 1);
assembly {
// Divide denominator by lpotdod.
denominator := div(denominator, lpotdod)
// Divide [prod1 prod0] by lpotdod.
prod0 := div(prod0, lpotdod)
// Flip lpotdod such that it is 2^256 / lpotdod. If lpotdod is zero, then it becomes one.
lpotdod := add(div(sub(0, lpotdod), lpotdod), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * lpotdod;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/// @notice Calculates floor(x*y÷1e18) with full precision.
///
/// @dev Variant of "mulDiv" with constant folding, i.e. in which the denominator is always 1e18. Before returning the
/// final result, we add 1 if (x * y) % SCALE >= HALF_SCALE. Without this, 6.6e-19 would be truncated to 0 instead of
/// being rounded to 1e-18. See "Listing 6" and text above it at https://accu.org/index.php/journals/1717.
///
/// Requirements:
/// - The result must fit within uint256.
///
/// Caveats:
/// - The body is purposely left uncommented; see the NatSpec comments in "PRBMath.mulDiv" to understand how this works.
/// - It is assumed that the result can never be type(uint256).max when x and y solve the following two equations:
/// 1. x * y = type(uint256).max * SCALE
/// 2. (x * y) % SCALE >= SCALE / 2
///
/// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number.
/// @param y The multiplier as an unsigned 60.18-decimal fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
function mulDivFixedPoint(uint256 x, uint256 y) internal pure returns (uint256 result) {
uint256 prod0;
uint256 prod1;
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
if (prod1 >= SCALE) {
revert PRBMath__MulDivFixedPointOverflow(prod1);
}
uint256 remainder;
uint256 roundUpUnit;
assembly {
remainder := mulmod(x, y, SCALE)
roundUpUnit := gt(remainder, 499999999999999999)
}
if (prod1 == 0) {
unchecked {
result = (prod0 / SCALE) + roundUpUnit;
return result;
}
}
assembly {
result := add(
mul(
or(
div(sub(prod0, remainder), SCALE_LPOTD),
mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, SCALE_LPOTD), SCALE_LPOTD), 1))
),
SCALE_INVERSE
),
roundUpUnit
)
}
}
/// @notice Calculates floor(x*y÷denominator) with full precision.
///
/// @dev An extension of "mulDiv" for signed numbers. Works by computing the signs and the absolute values separately.
///
/// Requirements:
/// - None of the inputs can be type(int256).min.
/// - The result must fit within int256.
///
/// @param x The multiplicand as an int256.
/// @param y The multiplier as an int256.
/// @param denominator The divisor as an int256.
/// @return result The result as an int256.
function mulDivSigned(
int256 x,
int256 y,
int256 denominator
) internal pure returns (int256 result) {
if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) {
revert PRBMath__MulDivSignedInputTooSmall();
}
// Get hold of the absolute values of x, y and the denominator.
uint256 ax;
uint256 ay;
uint256 ad;
unchecked {
ax = x < 0 ? uint256(-x) : uint256(x);
ay = y < 0 ? uint256(-y) : uint256(y);
ad = denominator < 0 ? uint256(-denominator) : uint256(denominator);
}
// Compute the absolute value of (x*y)÷denominator. The result must fit within int256.
uint256 rAbs = mulDiv(ax, ay, ad);
if (rAbs > uint256(type(int256).max)) {
revert PRBMath__MulDivSignedOverflow(rAbs);
}
// Get the signs of x, y and the denominator.
uint256 sx;
uint256 sy;
uint256 sd;
assembly {
sx := sgt(x, sub(0, 1))
sy := sgt(y, sub(0, 1))
sd := sgt(denominator, sub(0, 1))
}
// XOR over sx, sy and sd. This is checking whether there are one or three negative signs in the inputs.
// If yes, the result should be negative.
result = sx ^ sy ^ sd == 0 ? -int256(rAbs) : int256(rAbs);
}
/// @notice Calculates the square root of x, rounding down.
/// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Caveats:
/// - This function does not work with fixed-point numbers.
///
/// @param x The uint256 number for which to calculate the square root.
/// @return result The result as an uint256.
function sqrt(uint256 x) internal pure returns (uint256 result) {
if (x == 0) {
return 0;
}
// Set the initial guess to the least power of two that is greater than or equal to sqrt(x).
uint256 xAux = uint256(x);
result = 1;
if (xAux >= 0x100000000000000000000000000000000) {
xAux >>= 128;
result <<= 64;
}
if (xAux >= 0x10000000000000000) {
xAux >>= 64;
result <<= 32;
}
if (xAux >= 0x100000000) {
xAux >>= 32;
result <<= 16;
}
if (xAux >= 0x10000) {
xAux >>= 16;
result <<= 8;
}
if (xAux >= 0x100) {
xAux >>= 8;
result <<= 4;
}
if (xAux >= 0x10) {
xAux >>= 4;
result <<= 2;
}
if (xAux >= 0x8) {
result <<= 1;
}
// The operations can never overflow because the result is max 2^127 when it enters this block.
unchecked {
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1; // Seven iterations should be enough
uint256 roundedDownResult = x / result;
return result >= roundedDownResult ? roundedDownResult : result;
}
}
}
// SPDX-License-Identifier: Unlicense
pragma solidity >=0.8.4;
import "./PRBMath.sol";
/// @title PRBMathSD59x18
/// @author Paul Razvan Berg
/// @notice Smart contract library for advanced fixed-point math that works with int256 numbers considered to have 18
/// trailing decimals. We call this number representation signed 59.18-decimal fixed-point, since the numbers can have
/// a sign and there can be up to 59 digits in the integer part and up to 18 decimals in the fractional part. The numbers
/// are bound by the minimum and the maximum values permitted by the Solidity type int256.
library PRBMathSD59x18 {
/// @dev log2(e) as a signed 59.18-decimal fixed-point number.
int256 internal constant LOG2_E = 1_442695040888963407;
/// @dev Half the SCALE number.
int256 internal constant HALF_SCALE = 5e17;
/// @dev The maximum value a signed 59.18-decimal fixed-point number can have.
int256 internal constant MAX_SD59x18 =
57896044618658097711785492504343953926634992332820282019728_792003956564819967;
/// @dev The maximum whole value a signed 59.18-decimal fixed-point number can have.
int256 internal constant MAX_WHOLE_SD59x18 =
57896044618658097711785492504343953926634992332820282019728_000000000000000000;
/// @dev The minimum value a signed 59.18-decimal fixed-point number can have.
int256 internal constant MIN_SD59x18 =
-57896044618658097711785492504343953926634992332820282019728_792003956564819968;
/// @dev The minimum whole value a signed 59.18-decimal fixed-point number can have.
int256 internal constant MIN_WHOLE_SD59x18 =
-57896044618658097711785492504343953926634992332820282019728_000000000000000000;
/// @dev How many trailing decimals can be represented.
int256 internal constant SCALE = 1e18;
/// INTERNAL FUNCTIONS ///
/// @notice Calculate the absolute value of x.
///
/// @dev Requirements:
/// - x must be greater than MIN_SD59x18.
///
/// @param x The number to calculate the absolute value for.
/// @param result The absolute value of x.
function abs(int256 x) internal pure returns (int256 result) {
unchecked {
if (x == MIN_SD59x18) {
revert PRBMathSD59x18__AbsInputTooSmall();
}
result = x < 0 ? -x : x;
}
}
/// @notice Calculates the arithmetic average of x and y, rounding down.
/// @param x The first operand as a signed 59.18-decimal fixed-point number.
/// @param y The second operand as a signed 59.18-decimal fixed-point number.
/// @return result The arithmetic average as a signed 59.18-decimal fixed-point number.
function avg(int256 x, int256 y) internal pure returns (int256 result) {
// The operations can never overflow.
unchecked {
int256 sum = (x >> 1) + (y >> 1);
if (sum < 0) {
// If at least one of x and y is odd, we add 1 to the result. This is because shifting negative numbers to the
// right rounds down to infinity.
assembly {
result := add(sum, and(or(x, y), 1))
}
} else {
// If both x and y are odd, we add 1 to the result. This is because if both numbers are odd, the 0.5
// remainder gets truncated twice.
result = sum + (x & y & 1);
}
}
}
/// @notice Yields the least greatest signed 59.18 decimal fixed-point number greater than or equal to x.
///
/// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x must be less than or equal to MAX_WHOLE_SD59x18.
///
/// @param x The signed 59.18-decimal fixed-point number to ceil.
/// @param result The least integer greater than or equal to x, as a signed 58.18-decimal fixed-point number.
function ceil(int256 x) internal pure returns (int256 result) {
if (x > MAX_WHOLE_SD59x18) {
revert PRBMathSD59x18__CeilOverflow(x);
}
unchecked {
int256 remainder = x % SCALE;
if (remainder == 0) {
result = x;
} else {
// Solidity uses C fmod style, which returns a modulus with the same sign as x.
result = x - remainder;
if (x > 0) {
result += SCALE;
}
}
}
}
/// @notice Divides two signed 59.18-decimal fixed-point numbers, returning a new signed 59.18-decimal fixed-point number.
///
/// @dev Variant of "mulDiv" that works with signed numbers. Works by computing the signs and the absolute values separately.
///
/// Requirements:
/// - All from "PRBMath.mulDiv".
/// - None of the inputs can be MIN_SD59x18.
/// - The denominator cannot be zero.
/// - The result must fit within int256.
///
/// Caveats:
/// - All from "PRBMath.mulDiv".
///
/// @param x The numerator as a signed 59.18-decimal fixed-point number.
/// @param y The denominator as a signed 59.18-decimal fixed-point number.
/// @param result The quotient as a signed 59.18-decimal fixed-point number.
function div(int256 x, int256 y) internal pure returns (int256 result) {
if (x == MIN_SD59x18 || y == MIN_SD59x18) {
revert PRBMathSD59x18__DivInputTooSmall();
}
// Get hold of the absolute values of x and y.
uint256 ax;
uint256 ay;
unchecked {
ax = x < 0 ? uint256(-x) : uint256(x);
ay = y < 0 ? uint256(-y) : uint256(y);
}
// Compute the absolute value of (x*SCALE)÷y. The result must fit within int256.
uint256 rAbs = PRBMath.mulDiv(ax, uint256(SCALE), ay);
if (rAbs > uint256(MAX_SD59x18)) {
revert PRBMathSD59x18__DivOverflow(rAbs);
}
// Get the signs of x and y.
uint256 sx;
uint256 sy;
assembly {
sx := sgt(x, sub(0, 1))
sy := sgt(y, sub(0, 1))
}
// XOR over sx and sy. This is basically checking whether the inputs have the same sign. If yes, the result
// should be positive. Otherwise, it should be negative.
result = sx ^ sy == 1 ? -int256(rAbs) : int256(rAbs);
}
/// @notice Returns Euler's number as a signed 59.18-decimal fixed-point number.
/// @dev See https://en.wikipedia.org/wiki/E_(mathematical_constant).
function e() internal pure returns (int256 result) {
result = 2_718281828459045235;
}
/// @notice Calculates the natural exponent of x.
///
/// @dev Based on the insight that e^x = 2^(x * log2(e)).
///
/// Requirements:
/// - All from "log2".
/// - x must be less than 133.084258667509499441.
///
/// Caveats:
/// - All from "exp2".
/// - For any x less than -41.446531673892822322, the result is zero.
///
/// @param x The exponent as a signed 59.18-decimal fixed-point number.
/// @return result The result as a signed 59.18-decimal fixed-point number.
function exp(int256 x) internal pure returns (int256 result) {
// Without this check, the value passed to "exp2" would be less than -59.794705707972522261.
if (x < -41_446531673892822322) {
return 0;
}
// Without this check, the value passed to "exp2" would be greater than 192.
if (x >= 133_084258667509499441) {
revert PRBMathSD59x18__ExpInputTooBig(x);
}
// Do the fixed-point multiplication inline to save gas.
unchecked {
int256 doubleScaleProduct = x * LOG2_E;
result = exp2((doubleScaleProduct + HALF_SCALE) / SCALE);
}
}
/// @notice Calculates the binary exponent of x using the binary fraction method.
///
/// @dev See https://ethereum.stackexchange.com/q/79903/24693.
///
/// Requirements:
/// - x must be 192 or less.
/// - The result must fit within MAX_SD59x18.
///
/// Caveats:
/// - For any x less than -59.794705707972522261, the result is zero.
///
/// @param x The exponent as a signed 59.18-decimal fixed-point number.
/// @return result The result as a signed 59.18-decimal fixed-point number.
function exp2(int256 x) internal pure returns (int256 result) {
// This works because 2^(-x) = 1/2^x.
if (x < 0) {
// 2^59.794705707972522262 is the maximum number whose inverse does not truncate down to zero.
if (x < -59_794705707972522261) {
return 0;
}
// Do the fixed-point inversion inline to save gas. The numerator is SCALE * SCALE.
unchecked {
result = 1e36 / exp2(-x);
}
} else {
// 2^192 doesn't fit within the 192.64-bit format used internally in this function.
if (x >= 192e18) {
revert PRBMathSD59x18__Exp2InputTooBig(x);
}
unchecked {
// Convert x to the 192.64-bit fixed-point format.
uint256 x192x64 = (uint256(x) << 64) / uint256(SCALE);
// Safe to convert the result to int256 directly because the maximum input allowed is 192.
result = int256(PRBMath.exp2(x192x64));
}
}
}
/// @notice Yields the greatest signed 59.18 decimal fixed-point number less than or equal to x.
///
/// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x must be greater than or equal to MIN_WHOLE_SD59x18.
///
/// @param x The signed 59.18-decimal fixed-point number to floor.
/// @param result The greatest integer less than or equal to x, as a signed 58.18-decimal fixed-point number.
function floor(int256 x) internal pure returns (int256 result) {
if (x < MIN_WHOLE_SD59x18) {
revert PRBMathSD59x18__FloorUnderflow(x);
}
unchecked {
int256 remainder = x % SCALE;
if (remainder == 0) {
result = x;
} else {
// Solidity uses C fmod style, which returns a modulus with the same sign as x.
result = x - remainder;
if (x < 0) {
result -= SCALE;
}
}
}
}
/// @notice Yields the excess beyond the floor of x for positive numbers and the part of the number to the right
/// of the radix point for negative numbers.
/// @dev Based on the odd function definition. https://en.wikipedia.org/wiki/Fractional_part
/// @param x The signed 59.18-decimal fixed-point number to get the fractional part of.
/// @param result The fractional part of x as a signed 59.18-decimal fixed-point number.
function frac(int256 x) internal pure returns (int256 result) {
unchecked {
result = x % SCALE;
}
}
/// @notice Converts a number from basic integer form to signed 59.18-decimal fixed-point representation.
///
/// @dev Requirements:
/// - x must be greater than or equal to MIN_SD59x18 divided by SCALE.
/// - x must be less than or equal to MAX_SD59x18 divided by SCALE.
///
/// @param x The basic integer to convert.
/// @param result The same number in signed 59.18-decimal fixed-point representation.
function fromInt(int256 x) internal pure returns (int256 result) {
unchecked {
if (x < MIN_SD59x18 / SCALE) {
revert PRBMathSD59x18__FromIntUnderflow(x);
}
if (x > MAX_SD59x18 / SCALE) {
revert PRBMathSD59x18__FromIntOverflow(x);
}
result = x * SCALE;
}
}
/// @notice Calculates geometric mean of x and y, i.e. sqrt(x * y), rounding down.
///
/// @dev Requirements:
/// - x * y must fit within MAX_SD59x18, lest it overflows.
/// - x * y cannot be negative.
///
/// @param x The first operand as a signed 59.18-decimal fixed-point number.
/// @param y The second operand as a signed 59.18-decimal fixed-point number.
/// @return result The result as a signed 59.18-decimal fixed-point number.
function gm(int256 x, int256 y) internal pure returns (int256 result) {
if (x == 0) {
return 0;
}
unchecked {
// Checking for overflow this way is faster than letting Solidity do it.
int256 xy = x * y;
if (xy / x != y) {
revert PRBMathSD59x18__GmOverflow(x, y);
}
// The product cannot be negative.
if (xy < 0) {
revert PRBMathSD59x18__GmNegativeProduct(x, y);
}
// We don't need to multiply by the SCALE here because the x*y product had already picked up a factor of SCALE
// during multiplication. See the comments within the "sqrt" function.
result = int256(PRBMath.sqrt(uint256(xy)));
}
}
/// @notice Calculates 1 / x, rounding toward zero.
///
/// @dev Requirements:
/// - x cannot be zero.
///
/// @param x The signed 59.18-decimal fixed-point number for which to calculate the inverse.
/// @return result The inverse as a signed 59.18-decimal fixed-point number.
function inv(int256 x) internal pure returns (int256 result) {
unchecked {
// 1e36 is SCALE * SCALE.
result = 1e36 / x;
}
}
/// @notice Calculates the natural logarithm of x.
///
/// @dev Based on the insight that ln(x) = log2(x) / log2(e).
///
/// Requirements:
/// - All from "log2".
///
/// Caveats:
/// - All from "log2".
/// - This doesn't return exactly 1 for 2718281828459045235, for that we would need more fine-grained precision.
///
/// @param x The signed 59.18-decimal fixed-point number for which to calculate the natural logarithm.
/// @return result The natural logarithm as a signed 59.18-decimal fixed-point number.
function ln(int256 x) internal pure returns (int256 result) {
// Do the fixed-point multiplication inline to save gas. This is overflow-safe because the maximum value that log2(x)
// can return is 195205294292027477728.
unchecked {
result = (log2(x) * SCALE) / LOG2_E;
}
}
/// @notice Calculates the common logarithm of x.
///
/// @dev First checks if x is an exact power of ten and it stops if yes. If it's not, calculates the common
/// logarithm based on the insight that log10(x) = log2(x) / log2(10).
///
/// Requirements:
/// - All from "log2".
///
/// Caveats:
/// - All from "log2".
///
/// @param x The signed 59.18-decimal fixed-point number for which to calculate the common logarithm.
/// @return result The common logarithm as a signed 59.18-decimal fixed-point number.
function log10(int256 x) internal pure returns (int256 result) {
if (x <= 0) {
revert PRBMathSD59x18__LogInputTooSmall(x);
}
// Note that the "mul" in this block is the assembly mul operation, not the "mul" function defined in this contract.
// prettier-ignore
assembly {
switch x
case 1 { result := mul(SCALE, sub(0, 18)) }
case 10 { result := mul(SCALE, sub(1, 18)) }
case 100 { result := mul(SCALE, sub(2, 18)) }
case 1000 { result := mul(SCALE, sub(3, 18)) }
case 10000 { result := mul(SCALE, sub(4, 18)) }
case 100000 { result := mul(SCALE, sub(5, 18)) }
case 1000000 { result := mul(SCALE, sub(6, 18)) }
case 10000000 { result := mul(SCALE, sub(7, 18)) }
case 100000000 { result := mul(SCALE, sub(8, 18)) }
case 1000000000 { result := mul(SCALE, sub(9, 18)) }
case 10000000000 { result := mul(SCALE, sub(10, 18)) }
case 100000000000 { result := mul(SCALE, sub(11, 18)) }
case 1000000000000 { result := mul(SCALE, sub(12, 18)) }
case 10000000000000 { result := mul(SCALE, sub(13, 18)) }
case 100000000000000 { result := mul(SCALE, sub(14, 18)) }
case 1000000000000000 { result := mul(SCALE, sub(15, 18)) }
case 10000000000000000 { result := mul(SCALE, sub(16, 18)) }
case 100000000000000000 { result := mul(SCALE, sub(17, 18)) }
case 1000000000000000000 { result := 0 }
case 10000000000000000000 { result := SCALE }
case 100000000000000000000 { result := mul(SCALE, 2) }
case 1000000000000000000000 { result := mul(SCALE, 3) }
case 10000000000000000000000 { result := mul(SCALE, 4) }
case 100000000000000000000000 { result := mul(SCALE, 5) }
case 1000000000000000000000000 { result := mul(SCALE, 6) }
case 10000000000000000000000000 { result := mul(SCALE, 7) }
case 100000000000000000000000000 { result := mul(SCALE, 8) }
case 1000000000000000000000000000 { result := mul(SCALE, 9) }
case 10000000000000000000000000000 { result := mul(SCALE, 10) }
case 100000000000000000000000000000 { result := mul(SCALE, 11) }
case 1000000000000000000000000000000 { result := mul(SCALE, 12) }
case 10000000000000000000000000000000 { result := mul(SCALE, 13) }
case 100000000000000000000000000000000 { result := mul(SCALE, 14) }
case 1000000000000000000000000000000000 { result := mul(SCALE, 15) }
case 10000000000000000000000000000000000 { result := mul(SCALE, 16) }
case 100000000000000000000000000000000000 { result := mul(SCALE, 17) }
case 1000000000000000000000000000000000000 { result := mul(SCALE, 18) }
case 10000000000000000000000000000000000000 { result := mul(SCALE, 19) }
case 100000000000000000000000000000000000000 { result := mul(SCALE, 20) }
case 1000000000000000000000000000000000000000 { result := mul(SCALE, 21) }
case 10000000000000000000000000000000000000000 { result := mul(SCALE, 22) }
case 100000000000000000000000000000000000000000 { result := mul(SCALE, 23) }
case 1000000000000000000000000000000000000000000 { result := mul(SCALE, 24) }
case 10000000000000000000000000000000000000000000 { result := mul(SCALE, 25) }
case 100000000000000000000000000000000000000000000 { result := mul(SCALE, 26) }
case 1000000000000000000000000000000000000000000000 { result := mul(SCALE, 27) }
case 10000000000000000000000000000000000000000000000 { result := mul(SCALE, 28) }
case 100000000000000000000000000000000000000000000000 { result := mul(SCALE, 29) }
case 1000000000000000000000000000000000000000000000000 { result := mul(SCALE, 30) }
case 10000000000000000000000000000000000000000000000000 { result := mul(SCALE, 31) }
case 100000000000000000000000000000000000000000000000000 { result := mul(SCALE, 32) }
case 1000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 33) }
case 10000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 34) }
case 100000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 35) }
case 1000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 36) }
case 10000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 37) }
case 100000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 38) }
case 1000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 39) }
case 10000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 40) }
case 100000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 41) }
case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 42) }
case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 43) }
case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 44) }
case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 45) }
case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 46) }
case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 47) }
case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 48) }
case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 49) }
case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 50) }
case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 51) }
case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 52) }
case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 53) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 54) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 55) }
case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 56) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 57) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 58) }
default {
result := MAX_SD59x18
}
}
if (result == MAX_SD59x18) {
// Do the fixed-point division inline to save gas. The denominator is log2(10).
unchecked {
result = (log2(x) * SCALE) / 3_321928094887362347;
}
}
}
/// @notice Calculates the binary logarithm of x.
///
/// @dev Based on the iterative approximation algorithm.
/// https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation
///
/// Requirements:
/// - x must be greater than zero.
///
/// Caveats:
/// - The results are not perfectly accurate to the last decimal, due to the lossy precision of the iterative approximation.
///
/// @param x The signed 59.18-decimal fixed-point number for which to calculate the binary logarithm.
/// @return result The binary logarithm as a signed 59.18-decimal fixed-point number.
function log2(int256 x) internal pure returns (int256 result) {
if (x <= 0) {
revert PRBMathSD59x18__LogInputTooSmall(x);
}
unchecked {
// This works because log2(x) = -log2(1/x).
int256 sign;
if (x >= SCALE) {
sign = 1;
} else {
sign = -1;
// Do the fixed-point inversion inline to save gas. The numerator is SCALE * SCALE.
assembly {
x := div(1000000000000000000000000000000000000, x)
}
}
// Calculate the integer part of the logarithm and add it to the result and finally calculate y = x * 2^(-n).
uint256 n = PRBMath.mostSignificantBit(uint256(x / SCALE));
// The integer part of the logarithm as a signed 59.18-decimal fixed-point number. The operation can't overflow
// because n is maximum 255, SCALE is 1e18 and sign is either 1 or -1.
result = int256(n) * SCALE;
// This is y = x * 2^(-n).
int256 y = x >> n;
// If y = 1, the fractional part is zero.
if (y == SCALE) {
return result * sign;
}
// Calculate the fractional part via the iterative approximation.
// The "delta >>= 1" part is equivalent to "delta /= 2", but shifting bits is faster.
for (int256 delta = int256(HALF_SCALE); delta > 0; delta >>= 1) {
y = (y * y) / SCALE;
// Is y^2 > 2 and so in the range [2,4)?
if (y >= 2 * SCALE) {
// Add the 2^(-m) factor to the logarithm.
result += delta;
// Corresponds to z/2 on Wikipedia.
y >>= 1;
}
}
result *= sign;
}
}
/// @notice Multiplies two signed 59.18-decimal fixed-point numbers together, returning a new signed 59.18-decimal
/// fixed-point number.
///
/// @dev Variant of "mulDiv" that works with signed numbers and employs constant folding, i.e. the denominator is
/// always 1e18.
///
/// Requirements:
/// - All from "PRBMath.mulDivFixedPoint".
/// - None of the inputs can be MIN_SD59x18
/// - The result must fit within MAX_SD59x18.
///
/// Caveats:
/// - The body is purposely left uncommented; see the NatSpec comments in "PRBMath.mulDiv" to understand how this works.
///
/// @param x The multiplicand as a signed 59.18-decimal fixed-point number.
/// @param y The multiplier as a signed 59.18-decimal fixed-point number.
/// @return result The product as a signed 59.18-decimal fixed-point number.
function mul(int256 x, int256 y) internal pure returns (int256 result) {
if (x == MIN_SD59x18 || y == MIN_SD59x18) {
revert PRBMathSD59x18__MulInputTooSmall();
}
unchecked {
uint256 ax;
uint256 ay;
ax = x < 0 ? uint256(-x) : uint256(x);
ay = y < 0 ? uint256(-y) : uint256(y);
uint256 rAbs = PRBMath.mulDivFixedPoint(ax, ay);
if (rAbs > uint256(MAX_SD59x18)) {
revert PRBMathSD59x18__MulOverflow(rAbs);
}
uint256 sx;
uint256 sy;
assembly {
sx := sgt(x, sub(0, 1))
sy := sgt(y, sub(0, 1))
}
result = sx ^ sy == 1 ? -int256(rAbs) : int256(rAbs);
}
}
/// @notice Returns PI as a signed 59.18-decimal fixed-point number.
function pi() internal pure returns (int256 result) {
result = 3_141592653589793238;
}
/// @notice Raises x to the power of y.
///
/// @dev Based on the insight that x^y = 2^(log2(x) * y).
///
/// Requirements:
/// - All from "exp2", "log2" and "mul".
/// - z cannot be zero.
///
/// Caveats:
/// - All from "exp2", "log2" and "mul".
/// - Assumes 0^0 is 1.
///
/// @param x Number to raise to given power y, as a signed 59.18-decimal fixed-point number.
/// @param y Exponent to raise x to, as a signed 59.18-decimal fixed-point number.
/// @return result x raised to power y, as a signed 59.18-decimal fixed-point number.
function pow(int256 x, int256 y) internal pure returns (int256 result) {
if (x == 0) {
result = y == 0 ? SCALE : int256(0);
} else {
result = exp2(mul(log2(x), y));
}
}
/// @notice Raises x (signed 59.18-decimal fixed-point number) to the power of y (basic unsigned integer) using the
/// famous algorithm "exponentiation by squaring".
///
/// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring
///
/// Requirements:
/// - All from "abs" and "PRBMath.mulDivFixedPoint".
/// - The result must fit within MAX_SD59x18.
///
/// Caveats:
/// - All from "PRBMath.mulDivFixedPoint".
/// - Assumes 0^0 is 1.
///
/// @param x The base as a signed 59.18-decimal fixed-point number.
/// @param y The exponent as an uint256.
/// @return result The result as a signed 59.18-decimal fixed-point number.
function powu(int256 x, uint256 y) internal pure returns (int256 result) {
uint256 xAbs = uint256(abs(x));
// Calculate the first iteration of the loop in advance.
uint256 rAbs = y & 1 > 0 ? xAbs : uint256(SCALE);
// Equivalent to "for(y /= 2; y > 0; y /= 2)" but faster.
uint256 yAux = y;
for (yAux >>= 1; yAux > 0; yAux >>= 1) {
xAbs = PRBMath.mulDivFixedPoint(xAbs, xAbs);
// Equivalent to "y % 2 == 1" but faster.
if (yAux & 1 > 0) {
rAbs = PRBMath.mulDivFixedPoint(rAbs, xAbs);
}
}
// The result must fit within the 59.18-decimal fixed-point representation.
if (rAbs > uint256(MAX_SD59x18)) {
revert PRBMathSD59x18__PowuOverflow(rAbs);
}
// Is the base negative and the exponent an odd number?
bool isNegative = x < 0 && y & 1 == 1;
result = isNegative ? -int256(rAbs) : int256(rAbs);
}
/// @notice Returns 1 as a signed 59.18-decimal fixed-point number.
function scale() internal pure returns (int256 result) {
result = SCALE;
}
/// @notice Calculates the square root of x, rounding down.
/// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Requirements:
/// - x cannot be negative.
/// - x must be less than MAX_SD59x18 / SCALE.
///
/// @param x The signed 59.18-decimal fixed-point number for which to calculate the square root.
/// @return result The result as a signed 59.18-decimal fixed-point .
function sqrt(int256 x) internal pure returns (int256 result) {
unchecked {
if (x < 0) {
revert PRBMathSD59x18__SqrtNegativeInput(x);
}
if (x > MAX_SD59x18 / SCALE) {
revert PRBMathSD59x18__SqrtOverflow(x);
}
// Multiply x by the SCALE to account for the factor of SCALE that is picked up when multiplying two signed
// 59.18-decimal fixed-point numbers together (in this case, those two numbers are both the square root).
result = int256(PRBMath.sqrt(uint256(x * SCALE)));
}
}
/// @notice Converts a signed 59.18-decimal fixed-point number to basic integer form, rounding down in the process.
/// @param x The signed 59.18-decimal fixed-point number to convert.
/// @return result The same number in basic integer form.
function toInt(int256 x) internal pure returns (int256 result) {
unchecked {
result = x / SCALE;
}
}
}
// SPDX-License-Identifier: Unlicense
pragma solidity >=0.8.4;
import "./PRBMath.sol";
/// @title PRBMathUD60x18
/// @author Paul Razvan Berg
/// @notice Smart contract library for advanced fixed-point math that works with uint256 numbers considered to have 18
/// trailing decimals. We call this number representation unsigned 60.18-decimal fixed-point, since there can be up to 60
/// digits in the integer part and up to 18 decimals in the fractional part. The numbers are bound by the minimum and the
/// maximum values permitted by the Solidity type uint256.
library PRBMathUD60x18 {
/// @dev Half the SCALE number.
uint256 internal constant HALF_SCALE = 5e17;
/// @dev log2(e) as an unsigned 60.18-decimal fixed-point number.
uint256 internal constant LOG2_E = 1_442695040888963407;
/// @dev The maximum value an unsigned 60.18-decimal fixed-point number can have.
uint256 internal constant MAX_UD60x18 =
115792089237316195423570985008687907853269984665640564039457_584007913129639935;
/// @dev The maximum whole value an unsigned 60.18-decimal fixed-point number can have.
uint256 internal constant MAX_WHOLE_UD60x18 =
115792089237316195423570985008687907853269984665640564039457_000000000000000000;
/// @dev How many trailing decimals can be represented.
uint256 internal constant SCALE = 1e18;
/// @notice Calculates the arithmetic average of x and y, rounding down.
/// @param x The first operand as an unsigned 60.18-decimal fixed-point number.
/// @param y The second operand as an unsigned 60.18-decimal fixed-point number.
/// @return result The arithmetic average as an unsigned 60.18-decimal fixed-point number.
function avg(uint256 x, uint256 y) internal pure returns (uint256 result) {
// The operations can never overflow.
unchecked {
// The last operand checks if both x and y are odd and if that is the case, we add 1 to the result. We need
// to do this because if both numbers are odd, the 0.5 remainder gets truncated twice.
result = (x >> 1) + (y >> 1) + (x & y & 1);
}
}
/// @notice Yields the least unsigned 60.18 decimal fixed-point number greater than or equal to x.
///
/// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x must be less than or equal to MAX_WHOLE_UD60x18.
///
/// @param x The unsigned 60.18-decimal fixed-point number to ceil.
/// @param result The least integer greater than or equal to x, as an unsigned 60.18-decimal fixed-point number.
function ceil(uint256 x) internal pure returns (uint256 result) {
if (x > MAX_WHOLE_UD60x18) {
revert PRBMathUD60x18__CeilOverflow(x);
}
assembly {
// Equivalent to "x % SCALE" but faster.
let remainder := mod(x, SCALE)
// Equivalent to "SCALE - remainder" but faster.
let delta := sub(SCALE, remainder)
// Equivalent to "x + delta * (remainder > 0 ? 1 : 0)" but faster.
result := add(x, mul(delta, gt(remainder, 0)))
}
}
/// @notice Divides two unsigned 60.18-decimal fixed-point numbers, returning a new unsigned 60.18-decimal fixed-point number.
///
/// @dev Uses mulDiv to enable overflow-safe multiplication and division.
///
/// Requirements:
/// - The denominator cannot be zero.
///
/// @param x The numerator as an unsigned 60.18-decimal fixed-point number.
/// @param y The denominator as an unsigned 60.18-decimal fixed-point number.
/// @param result The quotient as an unsigned 60.18-decimal fixed-point number.
function div(uint256 x, uint256 y) internal pure returns (uint256 result) {
result = PRBMath.mulDiv(x, SCALE, y);
}
/// @notice Returns Euler's number as an unsigned 60.18-decimal fixed-point number.
/// @dev See https://en.wikipedia.org/wiki/E_(mathematical_constant).
function e() internal pure returns (uint256 result) {
result = 2_718281828459045235;
}
/// @notice Calculates the natural exponent of x.
///
/// @dev Based on the insight that e^x = 2^(x * log2(e)).
///
/// Requirements:
/// - All from "log2".
/// - x must be less than 133.084258667509499441.
///
/// @param x The exponent as an unsigned 60.18-decimal fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
function exp(uint256 x) internal pure returns (uint256 result) {
// Without this check, the value passed to "exp2" would be greater than 192.
if (x >= 133_084258667509499441) {
revert PRBMathUD60x18__ExpInputTooBig(x);
}
// Do the fixed-point multiplication inline to save gas.
unchecked {
uint256 doubleScaleProduct = x * LOG2_E;
result = exp2((doubleScaleProduct + HALF_SCALE) / SCALE);
}
}
/// @notice Calculates the binary exponent of x using the binary fraction method.
///
/// @dev See https://ethereum.stackexchange.com/q/79903/24693.
///
/// Requirements:
/// - x must be 192 or less.
/// - The result must fit within MAX_UD60x18.
///
/// @param x The exponent as an unsigned 60.18-decimal fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
function exp2(uint256 x) internal pure returns (uint256 result) {
// 2^192 doesn't fit within the 192.64-bit format used internally in this function.
if (x >= 192e18) {
revert PRBMathUD60x18__Exp2InputTooBig(x);
}
unchecked {
// Convert x to the 192.64-bit fixed-point format.
uint256 x192x64 = (x << 64) / SCALE;
// Pass x to the PRBMath.exp2 function, which uses the 192.64-bit fixed-point number representation.
result = PRBMath.exp2(x192x64);
}
}
/// @notice Yields the greatest unsigned 60.18 decimal fixed-point number less than or equal to x.
/// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
/// @param x The unsigned 60.18-decimal fixed-point number to floor.
/// @param result The greatest integer less than or equal to x, as an unsigned 60.18-decimal fixed-point number.
function floor(uint256 x) internal pure returns (uint256 result) {
assembly {
// Equivalent to "x % SCALE" but faster.
let remainder := mod(x, SCALE)
// Equivalent to "x - remainder * (remainder > 0 ? 1 : 0)" but faster.
result := sub(x, mul(remainder, gt(remainder, 0)))
}
}
/// @notice Yields the excess beyond the floor of x.
/// @dev Based on the odd function definition https://en.wikipedia.org/wiki/Fractional_part.
/// @param x The unsigned 60.18-decimal fixed-point number to get the fractional part of.
/// @param result The fractional part of x as an unsigned 60.18-decimal fixed-point number.
function frac(uint256 x) internal pure returns (uint256 result) {
assembly {
result := mod(x, SCALE)
}
}
/// @notice Converts a number from basic integer form to unsigned 60.18-decimal fixed-point representation.
///
/// @dev Requirements:
/// - x must be less than or equal to MAX_UD60x18 divided by SCALE.
///
/// @param x The basic integer to convert.
/// @param result The same number in unsigned 60.18-decimal fixed-point representation.
function fromUint(uint256 x) internal pure returns (uint256 result) {
unchecked {
if (x > MAX_UD60x18 / SCALE) {
revert PRBMathUD60x18__FromUintOverflow(x);
}
result = x * SCALE;
}
}
/// @notice Calculates geometric mean of x and y, i.e. sqrt(x * y), rounding down.
///
/// @dev Requirements:
/// - x * y must fit within MAX_UD60x18, lest it overflows.
///
/// @param x The first operand as an unsigned 60.18-decimal fixed-point number.
/// @param y The second operand as an unsigned 60.18-decimal fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
function gm(uint256 x, uint256 y) internal pure returns (uint256 result) {
if (x == 0) {
return 0;
}
unchecked {
// Checking for overflow this way is faster than letting Solidity do it.
uint256 xy = x * y;
if (xy / x != y) {
revert PRBMathUD60x18__GmOverflow(x, y);
}
// We don't need to multiply by the SCALE here because the x*y product had already picked up a factor of SCALE
// during multiplication. See the comments within the "sqrt" function.
result = PRBMath.sqrt(xy);
}
}
/// @notice Calculates 1 / x, rounding toward zero.
///
/// @dev Requirements:
/// - x cannot be zero.
///
/// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the inverse.
/// @return result The inverse as an unsigned 60.18-decimal fixed-point number.
function inv(uint256 x) internal pure returns (uint256 result) {
unchecked {
// 1e36 is SCALE * SCALE.
result = 1e36 / x;
}
}
/// @notice Calculates the natural logarithm of x.
///
/// @dev Based on the insight that ln(x) = log2(x) / log2(e).
///
/// Requirements:
/// - All from "log2".
///
/// Caveats:
/// - All from "log2".
/// - This doesn't return exactly 1 for 2.718281828459045235, for that we would need more fine-grained precision.
///
/// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the natural logarithm.
/// @return result The natural logarithm as an unsigned 60.18-decimal fixed-point number.
function ln(uint256 x) internal pure returns (uint256 result) {
// Do the fixed-point multiplication inline to save gas. This is overflow-safe because the maximum value that log2(x)
// can return is 196205294292027477728.
unchecked {
result = (log2(x) * SCALE) / LOG2_E;
}
}
/// @notice Calculates the common logarithm of x.
///
/// @dev First checks if x is an exact power of ten and it stops if yes. If it's not, calculates the common
/// logarithm based on the insight that log10(x) = log2(x) / log2(10).
///
/// Requirements:
/// - All from "log2".
///
/// Caveats:
/// - All from "log2".
///
/// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the common logarithm.
/// @return result The common logarithm as an unsigned 60.18-decimal fixed-point number.
function log10(uint256 x) internal pure returns (uint256 result) {
if (x < SCALE) {
revert PRBMathUD60x18__LogInputTooSmall(x);
}
// Note that the "mul" in this block is the assembly multiplication operation, not the "mul" function defined
// in this contract.
// prettier-ignore
assembly {
switch x
case 1 { result := mul(SCALE, sub(0, 18)) }
case 10 { result := mul(SCALE, sub(1, 18)) }
case 100 { result := mul(SCALE, sub(2, 18)) }
case 1000 { result := mul(SCALE, sub(3, 18)) }
case 10000 { result := mul(SCALE, sub(4, 18)) }
case 100000 { result := mul(SCALE, sub(5, 18)) }
case 1000000 { result := mul(SCALE, sub(6, 18)) }
case 10000000 { result := mul(SCALE, sub(7, 18)) }
case 100000000 { result := mul(SCALE, sub(8, 18)) }
case 1000000000 { result := mul(SCALE, sub(9, 18)) }
case 10000000000 { result := mul(SCALE, sub(10, 18)) }
case 100000000000 { result := mul(SCALE, sub(11, 18)) }
case 1000000000000 { result := mul(SCALE, sub(12, 18)) }
case 10000000000000 { result := mul(SCALE, sub(13, 18)) }
case 100000000000000 { result := mul(SCALE, sub(14, 18)) }
case 1000000000000000 { result := mul(SCALE, sub(15, 18)) }
case 10000000000000000 { result := mul(SCALE, sub(16, 18)) }
case 100000000000000000 { result := mul(SCALE, sub(17, 18)) }
case 1000000000000000000 { result := 0 }
case 10000000000000000000 { result := SCALE }
case 100000000000000000000 { result := mul(SCALE, 2) }
case 1000000000000000000000 { result := mul(SCALE, 3) }
case 10000000000000000000000 { result := mul(SCALE, 4) }
case 100000000000000000000000 { result := mul(SCALE, 5) }
case 1000000000000000000000000 { result := mul(SCALE, 6) }
case 10000000000000000000000000 { result := mul(SCALE, 7) }
case 100000000000000000000000000 { result := mul(SCALE, 8) }
case 1000000000000000000000000000 { result := mul(SCALE, 9) }
case 10000000000000000000000000000 { result := mul(SCALE, 10) }
case 100000000000000000000000000000 { result := mul(SCALE, 11) }
case 1000000000000000000000000000000 { result := mul(SCALE, 12) }
case 10000000000000000000000000000000 { result := mul(SCALE, 13) }
case 100000000000000000000000000000000 { result := mul(SCALE, 14) }
case 1000000000000000000000000000000000 { result := mul(SCALE, 15) }
case 10000000000000000000000000000000000 { result := mul(SCALE, 16) }
case 100000000000000000000000000000000000 { result := mul(SCALE, 17) }
case 1000000000000000000000000000000000000 { result := mul(SCALE, 18) }
case 10000000000000000000000000000000000000 { result := mul(SCALE, 19) }
case 100000000000000000000000000000000000000 { result := mul(SCALE, 20) }
case 1000000000000000000000000000000000000000 { result := mul(SCALE, 21) }
case 10000000000000000000000000000000000000000 { result := mul(SCALE, 22) }
case 100000000000000000000000000000000000000000 { result := mul(SCALE, 23) }
case 1000000000000000000000000000000000000000000 { result := mul(SCALE, 24) }
case 10000000000000000000000000000000000000000000 { result := mul(SCALE, 25) }
case 100000000000000000000000000000000000000000000 { result := mul(SCALE, 26) }
case 1000000000000000000000000000000000000000000000 { result := mul(SCALE, 27) }
case 10000000000000000000000000000000000000000000000 { result := mul(SCALE, 28) }
case 100000000000000000000000000000000000000000000000 { result := mul(SCALE, 29) }
case 1000000000000000000000000000000000000000000000000 { result := mul(SCALE, 30) }
case 10000000000000000000000000000000000000000000000000 { result := mul(SCALE, 31) }
case 100000000000000000000000000000000000000000000000000 { result := mul(SCALE, 32) }
case 1000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 33) }
case 10000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 34) }
case 100000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 35) }
case 1000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 36) }
case 10000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 37) }
case 100000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 38) }
case 1000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 39) }
case 10000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 40) }
case 100000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 41) }
case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 42) }
case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 43) }
case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 44) }
case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 45) }
case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 46) }
case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 47) }
case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 48) }
case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 49) }
case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 50) }
case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 51) }
case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 52) }
case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 53) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 54) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 55) }
case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 56) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 57) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 58) }
case 100000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 59) }
default {
result := MAX_UD60x18
}
}
if (result == MAX_UD60x18) {
// Do the fixed-point division inline to save gas. The denominator is log2(10).
unchecked {
result = (log2(x) * SCALE) / 3_321928094887362347;
}
}
}
/// @notice Calculates the binary logarithm of x.
///
/// @dev Based on the iterative approximation algorithm.
/// https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation
///
/// Requirements:
/// - x must be greater than or equal to SCALE, otherwise the result would be negative.
///
/// Caveats:
/// - The results are nor perfectly accurate to the last decimal, due to the lossy precision of the iterative approximation.
///
/// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the binary logarithm.
/// @return result The binary logarithm as an unsigned 60.18-decimal fixed-point number.
function log2(uint256 x) internal pure returns (uint256 result) {
if (x < SCALE) {
revert PRBMathUD60x18__LogInputTooSmall(x);
}
unchecked {
// Calculate the integer part of the logarithm and add it to the result and finally calculate y = x * 2^(-n).
uint256 n = PRBMath.mostSignificantBit(x / SCALE);
// The integer part of the logarithm as an unsigned 60.18-decimal fixed-point number. The operation can't overflow
// because n is maximum 255 and SCALE is 1e18.
result = n * SCALE;
// This is y = x * 2^(-n).
uint256 y = x >> n;
// If y = 1, the fractional part is zero.
if (y == SCALE) {
return result;
}
// Calculate the fractional part via the iterative approximation.
// The "delta >>= 1" part is equivalent to "delta /= 2", but shifting bits is faster.
for (uint256 delta = HALF_SCALE; delta > 0; delta >>= 1) {
y = (y * y) / SCALE;
// Is y^2 > 2 and so in the range [2,4)?
if (y >= 2 * SCALE) {
// Add the 2^(-m) factor to the logarithm.
result += delta;
// Corresponds to z/2 on Wikipedia.
y >>= 1;
}
}
}
}
/// @notice Multiplies two unsigned 60.18-decimal fixed-point numbers together, returning a new unsigned 60.18-decimal
/// fixed-point number.
/// @dev See the documentation for the "PRBMath.mulDivFixedPoint" function.
/// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number.
/// @param y The multiplier as an unsigned 60.18-decimal fixed-point number.
/// @return result The product as an unsigned 60.18-decimal fixed-point number.
function mul(uint256 x, uint256 y) internal pure returns (uint256 result) {
result = PRBMath.mulDivFixedPoint(x, y);
}
/// @notice Returns PI as an unsigned 60.18-decimal fixed-point number.
function pi() internal pure returns (uint256 result) {
result = 3_141592653589793238;
}
/// @notice Raises x to the power of y.
///
/// @dev Based on the insight that x^y = 2^(log2(x) * y).
///
/// Requirements:
/// - All from "exp2", "log2" and "mul".
///
/// Caveats:
/// - All from "exp2", "log2" and "mul".
/// - Assumes 0^0 is 1.
///
/// @param x Number to raise to given power y, as an unsigned 60.18-decimal fixed-point number.
/// @param y Exponent to raise x to, as an unsigned 60.18-decimal fixed-point number.
/// @return result x raised to power y, as an unsigned 60.18-decimal fixed-point number.
function pow(uint256 x, uint256 y) internal pure returns (uint256 result) {
if (x == 0) {
result = y == 0 ? SCALE : uint256(0);
} else {
result = exp2(mul(log2(x), y));
}
}
/// @notice Raises x (unsigned 60.18-decimal fixed-point number) to the power of y (basic unsigned integer) using the
/// famous algorithm "exponentiation by squaring".
///
/// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring
///
/// Requirements:
/// - The result must fit within MAX_UD60x18.
///
/// Caveats:
/// - All from "mul".
/// - Assumes 0^0 is 1.
///
/// @param x The base as an unsigned 60.18-decimal fixed-point number.
/// @param y The exponent as an uint256.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
function powu(uint256 x, uint256 y) internal pure returns (uint256 result) {
// Calculate the first iteration of the loop in advance.
result = y & 1 > 0 ? x : SCALE;
// Equivalent to "for(y /= 2; y > 0; y /= 2)" but faster.
for (y >>= 1; y > 0; y >>= 1) {
x = PRBMath.mulDivFixedPoint(x, x);
// Equivalent to "y % 2 == 1" but faster.
if (y & 1 > 0) {
result = PRBMath.mulDivFixedPoint(result, x);
}
}
}
/// @notice Returns 1 as an unsigned 60.18-decimal fixed-point number.
function scale() internal pure returns (uint256 result) {
result = SCALE;
}
/// @notice Calculates the square root of x, rounding down.
/// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Requirements:
/// - x must be less than MAX_UD60x18 / SCALE.
///
/// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the square root.
/// @return result The result as an unsigned 60.18-decimal fixed-point .
function sqrt(uint256 x) internal pure returns (uint256 result) {
unchecked {
if (x > MAX_UD60x18 / SCALE) {
revert PRBMathUD60x18__SqrtOverflow(x);
}
// Multiply x by the SCALE to account for the factor of SCALE that is picked up when multiplying two unsigned
// 60.18-decimal fixed-point numbers together (in this case, those two numbers are both the square root).
result = PRBMath.sqrt(x * SCALE);
}
}
/// @notice Converts a unsigned 60.18-decimal fixed-point number to basic integer form, rounding down in the process.
/// @param x The unsigned 60.18-decimal fixed-point number to convert.
/// @return result The same number in basic integer form.
function toUint(uint256 x) internal pure returns (uint256 result) {
unchecked {
result = x / SCALE;
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.18;
import { PRBMathSD59x18 } from "@prb-math/contracts/PRBMathSD59x18.sol";
import { PRBMathUD60x18 } from "@prb-math/contracts/PRBMathUD60x18.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {
DepositsState,
EmaState,
InflatorState,
InterestState,
PoolBalancesState,
PoolState
} from '../../interfaces/pool/commons/IPoolState.sol';
import { IERC3156FlashBorrower } from '../../interfaces/pool/IERC3156FlashBorrower.sol';
import {
_dwatp,
_htp,
_indexOf,
MAX_FENWICK_INDEX,
MIN_PRICE, MAX_PRICE
} from '../helpers/PoolHelper.sol';
import { Deposits } from '../internal/Deposits.sol';
import { Buckets } from '../internal/Buckets.sol';
import { Loans } from '../internal/Loans.sol';
import { Maths } from '../internal/Maths.sol';
/**
@title PoolCommons library
@notice External library containing logic for common pool functionality:
- interest rate accrual and interest rate params update
- pool utilization
*/
library PoolCommons {
using SafeERC20 for IERC20;
/*****************/
/*** Constants ***/
/*****************/
uint256 internal constant CUBIC_ROOT_1000000 = 100 * 1e18;
uint256 internal constant ONE_THIRD = 0.333333333333333334 * 1e18;
uint256 internal constant INCREASE_COEFFICIENT = 1.1 * 1e18;
uint256 internal constant DECREASE_COEFFICIENT = 0.9 * 1e18;
int256 internal constant PERCENT_102 = 1.02 * 1e18;
int256 internal constant NEG_H_MAU_HOURS = -0.057762265046662105 * 1e18; // -ln(2)/12
int256 internal constant NEG_H_TU_HOURS = -0.008251752149523158 * 1e18; // -ln(2)/84
/**************/
/*** Events ***/
/**************/
// See `IPoolEvents` for descriptions
event Flashloan(address indexed receiver, address indexed token, uint256 amount);
event ResetInterestRate(uint256 oldRate, uint256 newRate);
event UpdateInterestRate(uint256 oldRate, uint256 newRate);
/**************/
/*** Errors ***/
/**************/
// See `IPoolErrors` for descriptions
error FlashloanCallbackFailed();
error FlashloanIncorrectBalance();
/*************************/
/*** Local Var Structs ***/
/*************************/
/// @dev Struct used for `updateInterestState` function local vars.
struct UpdateInterestLocalVars {
uint256 debtEma;
uint256 depositEma;
uint256 debtColEma;
uint256 lupt0DebtEma;
uint256 t0Debt2ToCollateral;
uint256 newMeaningfulDeposit;
uint256 newDebt;
uint256 newDebtCol;
uint256 newLupt0Debt;
uint256 lastEmaUpdate;
int256 elapsed;
int256 weightMau;
int256 weightTu;
uint256 newInterestRate;
uint256 nonAuctionedT0Debt;
}
/**************************/
/*** External Functions ***/
/**************************/
/**
* @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 ===
* @dev `EMA`s state
* @dev interest rate accumulator and `interestRateUpdate` state
* @dev === Emit events ===
* @dev - `UpdateInterestRate` / `ResetInterestRate`
*/
function updateInterestState(
InterestState storage interestParams_,
EmaState storage emaParams_,
DepositsState storage deposits_,
PoolState memory poolState_,
uint256 lup_
) external {
UpdateInterestLocalVars memory vars;
// load existing EMA values
vars.debtEma = emaParams_.debtEma;
vars.depositEma = emaParams_.depositEma;
vars.debtColEma = emaParams_.debtColEma;
vars.lupt0DebtEma = emaParams_.lupt0DebtEma;
vars.lastEmaUpdate = emaParams_.emaUpdate;
vars.t0Debt2ToCollateral = interestParams_.t0Debt2ToCollateral;
// calculate new interest params
vars.nonAuctionedT0Debt = poolState_.t0Debt - poolState_.t0DebtInAuction;
vars.newDebt = Maths.wmul(vars.nonAuctionedT0Debt, poolState_.inflator);
// new meaningful deposit cannot be less than pool's debt
vars.newMeaningfulDeposit = Maths.max(
_meaningfulDeposit(
deposits_,
poolState_.t0DebtInAuction,
vars.nonAuctionedT0Debt,
poolState_.inflator,
vars.t0Debt2ToCollateral
),
vars.newDebt
);
vars.newDebtCol = Maths.wmul(poolState_.inflator, vars.t0Debt2ToCollateral);
vars.newLupt0Debt = Maths.wmul(lup_, vars.nonAuctionedT0Debt);
// update EMAs only once per block
if (vars.lastEmaUpdate != block.timestamp) {
// first time EMAs are updated, initialize EMAs
if (vars.lastEmaUpdate == 0) {
vars.debtEma = vars.newDebt;
vars.depositEma = vars.newMeaningfulDeposit;
vars.debtColEma = vars.newDebtCol;
vars.lupt0DebtEma = vars.newLupt0Debt;
} else {
vars.elapsed = int256(Maths.wdiv(block.timestamp - vars.lastEmaUpdate, 1 hours));
vars.weightMau = PRBMathSD59x18.exp(PRBMathSD59x18.mul(NEG_H_MAU_HOURS, vars.elapsed));
vars.weightTu = PRBMathSD59x18.exp(PRBMathSD59x18.mul(NEG_H_TU_HOURS, vars.elapsed));
// calculate the t0 debt EMA, used for MAU
vars.debtEma = uint256(
PRBMathSD59x18.mul(vars.weightMau, int256(vars.debtEma)) +
PRBMathSD59x18.mul(1e18 - vars.weightMau, int256(interestParams_.debt))
);
// update the meaningful deposit EMA, used for MAU
vars.depositEma = uint256(
PRBMathSD59x18.mul(vars.weightMau, int256(vars.depositEma)) +
PRBMathSD59x18.mul(1e18 - vars.weightMau, int256(interestParams_.meaningfulDeposit))
);
// calculate the debt squared to collateral EMA, used for TU
vars.debtColEma = uint256(
PRBMathSD59x18.mul(vars.weightTu, int256(vars.debtColEma)) +
PRBMathSD59x18.mul(1e18 - vars.weightTu, int256(interestParams_.debtCol))
);
// calculate the EMA of LUP * t0 debt
vars.lupt0DebtEma = uint256(
PRBMathSD59x18.mul(vars.weightTu, int256(vars.lupt0DebtEma)) +
PRBMathSD59x18.mul(1e18 - vars.weightTu, int256(interestParams_.lupt0Debt))
);
}
// save EMAs in storage
emaParams_.debtEma = vars.debtEma;
emaParams_.depositEma = vars.depositEma;
emaParams_.debtColEma = vars.debtColEma;
emaParams_.lupt0DebtEma = vars.lupt0DebtEma;
// save last EMA update time
emaParams_.emaUpdate = block.timestamp;
}
// reset interest rate if pool rate > 10% and debtEma < 5% of depositEma
if (
poolState_.rate > 0.1 * 1e18
&&
vars.debtEma < Maths.wmul(vars.depositEma, 0.05 * 1e18)
) {
interestParams_.interestRate = uint208(0.1 * 1e18);
interestParams_.interestRateUpdate = uint48(block.timestamp);
emit ResetInterestRate(
poolState_.rate,
0.1 * 1e18
);
}
// otherwise calculate and update interest rate if it has been more than 12 hours since the last update
else if (block.timestamp - interestParams_.interestRateUpdate > 12 hours) {
vars.newInterestRate = _calculateInterestRate(
poolState_,
vars.debtEma,
vars.depositEma,
vars.debtColEma,
vars.lupt0DebtEma
);
if (poolState_.rate != vars.newInterestRate) {
interestParams_.interestRate = uint208(vars.newInterestRate);
interestParams_.interestRateUpdate = uint48(block.timestamp);
emit UpdateInterestRate(
poolState_.rate,
vars.newInterestRate
);
}
}
// save new interest rate params to storage
interestParams_.debt = vars.newDebt;
interestParams_.meaningfulDeposit = vars.newMeaningfulDeposit;
interestParams_.debtCol = vars.newDebtCol;
interestParams_.lupt0Debt = vars.newLupt0Debt;
}
/**
* @notice Calculates new pool interest and scale the fenwick tree to update amount of debt owed to lenders (saved in storage).
* @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 maxT0DebtToCollateral_ Max t0 debt to collateral in Pool.
* @param elapsed_ Time elapsed since last inflator update.
* @return newInflator_ The new value of pool inflator.
* @return newInterest_ The new interest accrued.
*/
function accrueInterest(
EmaState storage emaParams_,
DepositsState storage deposits_,
PoolState calldata poolState_,
uint256 maxT0DebtToCollateral_,
uint256 elapsed_
) external returns (uint256 newInflator_, uint256 newInterest_) {
// Scale the borrower inflator to update amount of interest owed by borrowers
uint256 pendingFactor = PRBMathUD60x18.exp((poolState_.rate * elapsed_) / 365 days);
// calculate the highest threshold price
newInflator_ = Maths.wmul(poolState_.inflator, pendingFactor);
uint256 htp = _htp(maxT0DebtToCollateral_, poolState_.inflator);
uint256 accrualIndex;
if (htp > MAX_PRICE) accrualIndex = 1; // if HTP is over the highest price bucket then no buckets earn interest
else if (htp < MIN_PRICE) accrualIndex = MAX_FENWICK_INDEX; // if HTP is under the lowest price bucket then all buckets earn interest
else accrualIndex = _indexOf(htp); // else HTP bucket earn interest
uint256 lupIndex = Deposits.findIndexOfSum(deposits_, poolState_.debt);
// accrual price is less of lup and htp, and prices decrease as index increases
if (lupIndex > accrualIndex) accrualIndex = lupIndex;
uint256 interestEarningDeposit = Deposits.prefixSum(deposits_, accrualIndex);
if (interestEarningDeposit != 0) {
newInterest_ = Maths.wmul(
_lenderInterestMargin(_utilization(emaParams_.debtEma, emaParams_.depositEma)),
Maths.wmul(pendingFactor - Maths.WAD, poolState_.debt)
);
// lender factor computation, capped at 10x the interest factor for borrowers
uint256 lenderFactor = Maths.min(
Maths.floorWdiv(newInterest_, interestEarningDeposit),
Maths.wmul(pendingFactor - Maths.WAD, Maths.wad(10))
) + Maths.WAD;
// Scale the fenwick tree to update amount of debt owed to lenders
Deposits.mult(deposits_, accrualIndex, lenderFactor);
}
}
/**
* @notice Executes a flashloan from current pool.
* @dev === Reverts on ===
* @dev - `FlashloanCallbackFailed()` if receiver is not an `ERC3156FlashBorrower`
* @dev - `FlashloanIncorrectBalance()` if pool balance after flashloan is different than initial balance
* @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 amount_ The denormalized amount (dependent upon token precision) of tokens to borrow.
* @param data_ User-defined calldata passed to the receiver.
*/
function flashLoan(
IERC3156FlashBorrower receiver_,
address token_,
uint256 amount_,
bytes calldata data_
) external {
IERC20 tokenContract = IERC20(token_);
uint256 initialBalance = tokenContract.balanceOf(address(this));
tokenContract.safeTransfer(
address(receiver_),
amount_
);
if (receiver_.onFlashLoan(msg.sender, token_, amount_, 0, data_) !=
keccak256("ERC3156FlashBorrower.onFlashLoan")) revert FlashloanCallbackFailed();
tokenContract.safeTransferFrom(
address(receiver_),
address(this),
amount_
);
if (tokenContract.balanceOf(address(this)) != initialBalance) revert FlashloanIncorrectBalance();
emit Flashloan(address(receiver_), token_, amount_);
}
/**************************/
/*** Internal Functions ***/
/**************************/
/**
* @notice Calculates new pool interest rate.
*/
function _calculateInterestRate(
PoolState memory poolState_,
uint256 debtEma_,
uint256 depositEma_,
uint256 debtColEma_,
uint256 lupt0DebtEma_
) internal pure returns (uint256 newInterestRate_) {
// meaningful actual utilization
int256 mau;
// meaningful actual utilization * 1.02
int256 mau102;
if (poolState_.debt != 0) {
// calculate meaningful actual utilization for interest rate update
mau = int256(_utilization(debtEma_, depositEma_));
mau102 = (mau * PERCENT_102) / 1e18;
}
// calculate target utilization
int256 tu = (lupt0DebtEma_ != 0) ?
int256(Maths.wdiv(debtColEma_, lupt0DebtEma_)) : int(Maths.WAD);
newInterestRate_ = poolState_.rate;
// raise rates if 4*(tu-1.02*mau) < (tu+1.02*mau-1)^2-1
if (4 * (tu - mau102) < (((tu + mau102 - 1e18) / 1e9) ** 2) - 1e18) {
newInterestRate_ = Maths.wmul(poolState_.rate, INCREASE_COEFFICIENT);
// decrease rates if 4*(tu-mau) > 1-(tu+mau-1)^2
} else if (4 * (tu - mau) > 1e18 - ((tu + mau - 1e18) / 1e9) ** 2) {
newInterestRate_ = Maths.wmul(poolState_.rate, DECREASE_COEFFICIENT);
}
// bound rates between 10 bps and 400%
newInterestRate_ = Maths.min(4 * 1e18, Maths.max(0.001 * 1e18, newInterestRate_));
}
/**
* @notice Calculates pool meaningful actual utilization.
* @param debtEma_ `EMA` of pool debt.
* @param depositEma_ `EMA` of meaningful pool deposit.
* @return utilization_ Pool meaningful actual utilization value.
*/
function _utilization(
uint256 debtEma_,
uint256 depositEma_
) internal pure returns (uint256 utilization_) {
if (depositEma_ != 0) utilization_ = Maths.wdiv(debtEma_, depositEma_);
}
/**
* @notice Calculates lender interest margin.
* @param mau_ Meaningful actual utilization.
* @return The lender interest margin value.
*/
function _lenderInterestMargin(
uint256 mau_
) internal pure returns (uint256) {
// Net Interest Margin = ((1 - MAU1)^(1/3) * 0.15)
// Where MAU1 is MAU capped at 100% (min(MAU,1))
// Lender Interest Margin = 1 - Net Interest Margin
// PRBMath library forbids raising a number < 1e18 to a power. Using the product and quotient rules of
// exponents, rewrite the equation with a coefficient s which provides sufficient precision:
// Net Interest Margin = ((1 - MAU1) * s)^(1/3) / s^(1/3) * 0.15
uint256 base = 1_000_000 * 1e18 - Maths.min(mau_, 1e18) * 1_000_000;
// If unutilized deposit is infinitessimal, lenders get 100% of interest.
if (base < 1e18) {
return 1e18;
} else {
// cubic root of the percentage of meaningful unutilized deposit
uint256 crpud = PRBMathUD60x18.pow(base, ONE_THIRD);
// finish calculating Net Interest Margin, and then convert to Lender Interest Margin
return 1e18 - Maths.wdiv(Maths.wmul(crpud, 0.15 * 1e18), CUBIC_ROOT_1000000);
}
}
/**
* @notice Calculates pool's meaningful deposit.
* @param deposits_ Struct for pool deposits state.
* @param t0DebtInAuction_ Value of pool's t0 debt currently in auction.
* @param nonAuctionedT0Debt_ Value of pool's t0 debt that is not in auction.
* @param inflator_ Pool's current inflator.
* @param t0Debt2ToCollateral_ `t0Debt2ToCollateral` ratio.
* @return meaningfulDeposit_ Pool's meaningful deposit.
*/
function _meaningfulDeposit(
DepositsState storage deposits_,
uint256 t0DebtInAuction_,
uint256 nonAuctionedT0Debt_,
uint256 inflator_,
uint256 t0Debt2ToCollateral_
) internal view returns (uint256 meaningfulDeposit_) {
uint256 dwatp = _dwatp(nonAuctionedT0Debt_, inflator_, t0Debt2ToCollateral_);
if (dwatp == 0) {
meaningfulDeposit_ = Deposits.treeSum(deposits_);
} else {
if (dwatp >= MAX_PRICE) meaningfulDeposit_ = 0;
else if (dwatp >= MIN_PRICE) meaningfulDeposit_ = Deposits.prefixSum(deposits_, _indexOf(dwatp));
else meaningfulDeposit_ = Deposits.treeSum(deposits_);
}
meaningfulDeposit_ -= Maths.min(
meaningfulDeposit_,
Maths.wmul(t0DebtInAuction_, inflator_)
);
}
/**********************/
/*** View Functions ***/
/**********************/
/**
* @notice Calculates pool related debt values.
* @param poolBalances_ Pool debt
* @param inflatorState_ Interest inflator and last update time
* @param interestState_ Interest rate and t0Debt2ToCollateral accumulator
* @return Current amount of debt owed by borrowers in pool.
* @return Debt owed by borrowers based on last inflator snapshot.
* @return Total amount of debt in auction.
* @return t0debt accross all borrowers divided by their collateral, used in determining a collateralization weighted debt.
*/
function debtInfo(
PoolBalancesState memory poolBalances_,
InflatorState memory inflatorState_,
InterestState memory interestState_
) external view returns (uint256, uint256, uint256, uint256) {
uint256 t0Debt = poolBalances_.t0Debt;
uint256 inflator = inflatorState_.inflator;
return (
Maths.ceilWmul(
t0Debt,
pendingInflator(inflator, inflatorState_.inflatorUpdate, interestState_.interestRate)
),
Maths.ceilWmul(t0Debt, inflator),
Maths.ceilWmul(poolBalances_.t0DebtInAuction, inflator),
interestState_.t0Debt2ToCollateral
);
}
/**
* @notice Calculates pool interest factor for a given interest rate and time elapsed since last inflator update.
* @param interestRate_ Current pool interest rate.
* @param elapsed_ Time elapsed since last inflator update.
* @return The value of pool interest factor.
*/
function pendingInterestFactor(
uint256 interestRate_,
uint256 elapsed_
) external pure returns (uint256) {
return PRBMathUD60x18.exp((interestRate_ * elapsed_) / 365 days);
}
/**
* @notice Calculates pool pending inflator given the current inflator, time of last update and current interest rate.
* @param inflator_ Current pool inflator.
* @param inflatorUpdate Timestamp when inflator was updated.
* @param interestRate_ The interest rate of the pool.
* @return The pending value of pool inflator.
*/
function pendingInflator(
uint256 inflator_,
uint256 inflatorUpdate,
uint256 interestRate_
) public view returns (uint256) {
return Maths.wmul(
inflator_,
PRBMathUD60x18.exp((interestRate_ * (block.timestamp - inflatorUpdate)) / 365 days)
);
}
/**
* @notice Calculates lender interest margin for a given meaningful actual utilization.
* @dev Wrapper of the internal function.
*/
function lenderInterestMargin(
uint256 mau_
) external pure returns (uint256) {
return _lenderInterestMargin(mau_);
}
/**
* @notice Calculates pool meaningful actual utilization.
* @dev Wrapper of the internal function.
*/
function utilization(
EmaState storage emaParams_
) external view returns (uint256 utilization_) {
return _utilization(emaParams_.debtEma, emaParams_.depositEma);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.18;
import { PRBMathSD59x18 } from "@prb-math/contracts/PRBMathSD59x18.sol";
import { Math } from '@openzeppelin/contracts/utils/math/Math.sol';
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { PoolType } from '../../interfaces/pool/IPool.sol';
import { InflatorState, PoolState } from '../../interfaces/pool/commons/IPoolState.sol';
import { Buckets } from '../internal/Buckets.sol';
import { Maths } from '../internal/Maths.sol';
error BucketIndexOutOfBounds();
error BucketPriceOutOfBounds();
/*************************/
/*** Price Conversions ***/
/*************************/
/// @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;
uint256 constant MAX_INFLATED_PRICE = 50_248_449_380.325617709105488550 * 1e18; // 50 * MAX_PRICE
/// @dev deposit buffer (extra margin) used for calculating reserves
uint256 constant DEPOSIT_BUFFER = 1.000000001 * 1e18;
/// @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;
/// @dev collateralization factor used to calculate borrrower HTP/TP/collateralization.
uint256 constant COLLATERALIZATION_FACTOR = 1.04 * 1e18;
/**
* @notice Calculates the price (`WAD` precision) 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 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_
) pure returns (uint256) {
// Lowest Fenwick index is highest price, so invert the index and offset by highest bucket index.
int256 bucketIndex = MAX_BUCKET_INDEX - int256(index_);
if (bucketIndex < MIN_BUCKET_INDEX || bucketIndex > MAX_BUCKET_INDEX) revert BucketIndexOutOfBounds();
return uint256(
PRBMathSD59x18.exp2(
PRBMathSD59x18.mul(
PRBMathSD59x18.fromInt(bucketIndex),
PRBMathSD59x18.log2(FLOAT_STEP_INT)
)
)
);
}
/**
* @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_
) pure returns (uint256) {
if (price_ < MIN_PRICE || price_ > MAX_PRICE) revert BucketPriceOutOfBounds();
int256 index = PRBMathSD59x18.div(
PRBMathSD59x18.log2(int256(price_)),
PRBMathSD59x18.log2(FLOAT_STEP_INT)
);
int256 ceilIndex = PRBMathSD59x18.ceil(index);
if (index < 0 && ceilIndex - index > 0.5 * 1e18) {
return uint256(4157 - PRBMathSD59x18.toInt(ceilIndex));
}
return uint256(4156 - PRBMathSD59x18.toInt(ceilIndex));
}
/**********************/
/*** Pool Utilities ***/
/**********************/
/**
* @notice Calculates the minimum debt amount that can be borrowed or can remain in a loan in pool.
* @param debt_ The debt amount to calculate minimum debt amount for.
* @param loansCount_ The number of loans in pool.
* @return minDebtAmount_ Minimum debt amount value of the pool.
*/
function _minDebtAmount(
uint256 debt_,
uint256 loansCount_
) pure returns (uint256 minDebtAmount_) {
if (loansCount_ != 0) {
minDebtAmount_ = Maths.wdiv(Maths.wdiv(debt_, Maths.wad(loansCount_)), 10**19);
}
}
/**
* @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.
* @param interestRate_ The current interest rate.
* @return Fee rate based upon the given interest rate.
*/
function _borrowFeeRate(
uint256 interestRate_
) pure returns (uint256) {
// greater of the current annualized interest rate divided by 52 (one week of interest) or 5 bps
return Maths.max(Maths.wdiv(interestRate_, 52 * 1e18), 0.0005 * 1e18);
}
/**
* @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
*/
function _depositFeeRate(
uint256 interestRate_
) pure returns (uint256) {
// current annualized rate divided by 365 * 3 (8 hours of interest)
return Maths.wdiv(interestRate_, 365 * 3e18);
}
/**
* @notice Determines how the inflator state should be updated
* @param poolState_ State of the pool after updateInterestState was called.
* @param inflatorState_ Old inflator state.
* @return newInflator_ New inflator value.
* @return updateTimestamp_ `True` if timestamp of last update should be updated.
*/
function _determineInflatorState(
PoolState memory poolState_,
InflatorState memory inflatorState_
) view returns (uint208 newInflator_, bool updateTimestamp_) {
newInflator_ = inflatorState_.inflator;
// update pool inflator
if (poolState_.isNewInterestAccrued) {
newInflator_ = SafeCast.toUint208(poolState_.inflator);
updateTimestamp_ = true;
// if the debt in the current pool state is 0, also update the inflator and inflatorUpdate fields in inflatorState
// slither-disable-next-line incorrect-equality
} else if (poolState_.debt == 0) {
newInflator_ = SafeCast.toUint208(Maths.WAD);
updateTimestamp_ = true;
// if the first loan has just been drawn, update the inflator timestamp
// slither-disable-next-line incorrect-equality
} else if (inflatorState_.inflator == Maths.WAD && inflatorState_.inflatorUpdate != block.timestamp){
updateTimestamp_ = true;
}
}
/**
* @notice Calculates `HTP` price.
* @param maxT0DebtToCollateral_ Max t0 debt to collateral in pool.
* @param inflator_ Pool's inflator.
*/
function _htp(
uint256 maxT0DebtToCollateral_,
uint256 inflator_
) pure returns (uint256) {
return Maths.wmul(
Maths.wmul(maxT0DebtToCollateral_, inflator_),
COLLATERALIZATION_FACTOR
);
}
/**
* @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_,
uint256 inflator_,
uint256 t0Debt2ToCollateral_
) pure returns (uint256) {
return t0Debt_ == 0 ? 0 : Maths.wdiv(
Maths.wmul(
Maths.wmul(inflator_, t0Debt2ToCollateral_),
COLLATERALIZATION_FACTOR
),
t0Debt_
);
}
/**
* @notice Collateralization calculation.
* @param debt_ Debt to calculate collateralization for.
* @param collateral_ Collateral to calculate collateralization for.
* @param price_ Price to calculate collateralization for.
* @param type_ Type of the pool.
* @return `True` if value of collateral exceeds or equals debt.
*/
function _isCollateralized(
uint256 debt_,
uint256 collateral_,
uint256 price_,
uint8 type_
) pure returns (bool) {
// `False` if LUP = MIN_PRICE unless there is no debt
if (price_ == MIN_PRICE && debt_ != 0) return false;
// Use collateral floor for NFT pools
if (type_ == uint8(PoolType.ERC721)) {
//slither-disable-next-line divide-before-multiply
collateral_ = (collateral_ / Maths.WAD) * Maths.WAD; // use collateral floor
}
return Maths.wmul(collateral_, price_) >= Maths.wmul(COLLATERALIZATION_FACTOR, debt_);
}
/**
* @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.
* @return pricePrecisionAdjustment_ Unscaled integer of the minimum number of decimal places the dust limit requires.
*/
function _getCollateralDustPricePrecisionAdjustment(
uint256 bucketIndex_
) pure returns (uint256 pricePrecisionAdjustment_) {
// conditional is a gas optimization
if (bucketIndex_ > 3900) {
int256 bucketOffset = int256(bucketIndex_ - 3900);
int256 result = PRBMathSD59x18.sqrt(PRBMathSD59x18.div(bucketOffset * 1e18, int256(36 * 1e18)));
pricePrecisionAdjustment_ = uint256(result / 1e18);
}
}
/**
* @notice Returns the amount of collateral calculated for the given amount of `LP`.
* @dev The value returned is capped at collateral amount available in bucket.
* @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 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.
*/
function _lpToCollateral(
uint256 bucketCollateral_,
uint256 bucketLP_,
uint256 deposit_,
uint256 lenderLPBalance_,
uint256 bucketPrice_
) pure returns (uint256 collateralAmount_) {
collateralAmount_ = Buckets.lpToCollateral(
bucketCollateral_,
bucketLP_,
deposit_,
lenderLPBalance_,
bucketPrice_,
Math.Rounding.Down
);
if (collateralAmount_ > bucketCollateral_) {
// user is owed more collateral than is available in the bucket
collateralAmount_ = bucketCollateral_;
}
}
/**
* @notice Returns the amount of quote tokens calculated for the given amount of `LP`.
* @dev The value returned is capped at available bucket deposit.
* @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 lenderLPBalance_ The amount of `LP` to calculate quote token amount for.
* @param bucketPrice_ Bucket's price.
* @return quoteTokenAmount_ Amount of quote tokens calculated for the given `LP` amount, capped at available bucket deposit.
*/
function _lpToQuoteToken(
uint256 bucketLP_,
uint256 bucketCollateral_,
uint256 deposit_,
uint256 lenderLPBalance_,
uint256 bucketPrice_
) pure returns (uint256 quoteTokenAmount_) {
quoteTokenAmount_ = Buckets.lpToQuoteTokens(
bucketCollateral_,
bucketLP_,
deposit_,
lenderLPBalance_,
bucketPrice_,
Math.Rounding.Down
);
if (quoteTokenAmount_ > deposit_) quoteTokenAmount_ = deposit_;
}
/**
* @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`.
* @return scaledAmount_ Rounded value.
*/
function _roundToScale(
uint256 amount_,
uint256 tokenScale_
) pure returns (uint256 scaledAmount_) {
scaledAmount_ = (amount_ / tokenScale_) * tokenScale_;
}
/**
* @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`.
* @return scaledAmount_ Rounded value.
*/
function _roundUpToScale(
uint256 amount_,
uint256 tokenScale_
) pure returns (uint256 scaledAmount_) {
if (amount_ % tokenScale_ == 0)
scaledAmount_ = amount_;
else
scaledAmount_ = _roundToScale(amount_, tokenScale_) + tokenScale_;
}
/*********************************/
/*** Reserve Auction Utilities ***/
/*********************************/
uint256 constant MINUTE_HALF_LIFE = 0.988514020352896135_356867505 * 1e27; // 0.5^(1/60)
/**
* @notice Calculates claimable reserves within the pool.
* @dev Claimable reserve auctions and escrowed auction bonds are guaranteed by 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_,
uint256 totalBondEscrowed_,
uint256 reserveAuctionUnclaimed_,
uint256 quoteTokenBalance_
) pure returns (uint256 claimable_) {
uint256 guaranteedFunds = totalBondEscrowed_ + reserveAuctionUnclaimed_;
// calculate claimable reserves if there's quote token excess
if (quoteTokenBalance_ > guaranteedFunds) {
claimable_ = debt_ + quoteTokenBalance_;
claimable_ -= Maths.min(
claimable_,
// require 1.0 + 1e-9 deposit buffer (extra margin) for deposits
Maths.wmul(DEPOSIT_BUFFER, poolSize_) + guaranteedFunds
);
// incremental claimable reserve should not exceed excess quote in pool
claimable_ = Maths.min(
claimable_,
quoteTokenBalance_ - guaranteedFunds
);
}
}
/**
* @notice Calculates reserves auction price.
* @param reserveAuctionKicked_ Time when reserve auction was started (kicked).
* @param lastKickedReserves_ Reserves to be auctioned when started (kicked).
* @return price_ Calculated auction price.
*/
function _reserveAuctionPrice(
uint256 reserveAuctionKicked_,
uint256 lastKickedReserves_
) 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);
uint256 initialPrice = lastKickedReserves_ == 0 ? 0 : Maths.wdiv(1_000_000_000 * 1e18, lastKickedReserves_);
price_ = initialPrice * Maths.rmul(hoursComponent, minutesComponent) / 1e27;
}
}
/*************************/
/*** Auction Utilities ***/
/*************************/
/// @dev min bond factor.
uint256 constant MIN_BOND_FACTOR = 0.005 * 1e18;
/// @dev max bond factor.
uint256 constant MAX_BOND_FACTOR = 0.03 * 1e18;
/**
* @notice Calculates auction price.
* @param referencePrice_ Recorded at kick, used to calculate start price.
* @param kickTime_ Time when auction was kicked.
* @return price_ Calculated auction price.
*/
function _auctionPrice(
uint256 referencePrice_,
uint256 kickTime_
) view returns (uint256 price_) {
uint256 elapsedMinutes = Maths.wdiv((block.timestamp - kickTime_) * 1e18, 1 minutes * 1e18);
int256 timeAdjustment;
if (elapsedMinutes < 120 * 1e18) {
timeAdjustment = PRBMathSD59x18.mul(-1 * 1e18, int256(elapsedMinutes / 20));
price_ = 256 * Maths.wmul(referencePrice_, uint256(PRBMathSD59x18.exp2(timeAdjustment)));
} else if (elapsedMinutes < 840 * 1e18) {
timeAdjustment = PRBMathSD59x18.mul(-1 * 1e18, int256((elapsedMinutes - 120 * 1e18) / 120));
price_ = 4 * Maths.wmul(referencePrice_, uint256(PRBMathSD59x18.exp2(timeAdjustment)));
} else {
timeAdjustment = PRBMathSD59x18.mul(-1 * 1e18, int256((elapsedMinutes - 840 * 1e18) / 60));
price_ = Maths.wmul(referencePrice_, uint256(PRBMathSD59x18.exp2(timeAdjustment))) / 16;
}
}
/**
* @notice Calculates bond penalty factor.
* @dev Called in kick and take.
* @param debtToCollateral_ Borrower debt to collateral at time of kick.
* @param neutralPrice_ `NP` of auction.
* @param bondFactor_ Factor used to determine bondSize.
* @param auctionPrice_ Auction price at the time of call or, for bucket takes, bucket price.
* @return bpf_ Factor used in determining bond `reward` (positive) or `penalty` (negative).
*/
function _bpf(
uint256 debtToCollateral_,
uint256 neutralPrice_,
uint256 bondFactor_,
uint256 auctionPrice_
) pure returns (int256) {
int256 sign;
if (debtToCollateral_ < neutralPrice_) {
// BPF = BondFactor * min(1, max(-1, (neutralPrice - price) / (neutralPrice - debtToCollateral)))
sign = Maths.minInt(
1e18,
Maths.maxInt(
-1 * 1e18,
PRBMathSD59x18.div(
int256(neutralPrice_) - int256(auctionPrice_),
int256(neutralPrice_) - int256(debtToCollateral_)
)
)
);
} else {
int256 val = int256(neutralPrice_) - int256(auctionPrice_);
if (val < 0 ) sign = -1e18;
else if (val != 0) sign = 1e18;
}
return PRBMathSD59x18.mul(int256(bondFactor_), sign);
}
/**
* @notice Calculates bond parameters of an auction.
* @param borrowerDebt_ Borrower's debt before entering in liquidation.
* @param npTpRatio_ Borrower's Np to Tp ratio
*/
function _bondParams(
uint256 borrowerDebt_,
uint256 npTpRatio_
) pure returns (uint256 bondFactor_, uint256 bondSize_) {
// bondFactor = max(min(MAX_BOND_FACTOR, (NP/TP_ratio - 1) / 10), MIN_BOND_FACTOR)
bondFactor_ = Maths.max(
Maths.min(
MAX_BOND_FACTOR,
(npTpRatio_ - 1e18) / 10
),
MIN_BOND_FACTOR
);
bondSize_ = Maths.wmul(bondFactor_, borrowerDebt_);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == _ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*
* _Available since v4.7._
*/
function toUint248(uint256 value) internal pure returns (uint248) {
require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*
* _Available since v4.7._
*/
function toUint240(uint256 value) internal pure returns (uint240) {
require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*
* _Available since v4.7._
*/
function toUint232(uint256 value) internal pure returns (uint232) {
require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*
* _Available since v4.2._
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*
* _Available since v4.7._
*/
function toUint216(uint256 value) internal pure returns (uint216) {
require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*
* _Available since v4.7._
*/
function toUint208(uint256 value) internal pure returns (uint208) {
require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*
* _Available since v4.7._
*/
function toUint200(uint256 value) internal pure returns (uint200) {
require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*
* _Available since v4.7._
*/
function toUint192(uint256 value) internal pure returns (uint192) {
require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*
* _Available since v4.7._
*/
function toUint184(uint256 value) internal pure returns (uint184) {
require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*
* _Available since v4.7._
*/
function toUint176(uint256 value) internal pure returns (uint176) {
require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*
* _Available since v4.7._
*/
function toUint168(uint256 value) internal pure returns (uint168) {
require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*
* _Available since v4.7._
*/
function toUint160(uint256 value) internal pure returns (uint160) {
require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*
* _Available since v4.7._
*/
function toUint152(uint256 value) internal pure returns (uint152) {
require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*
* _Available since v4.7._
*/
function toUint144(uint256 value) internal pure returns (uint144) {
require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*
* _Available since v4.7._
*/
function toUint136(uint256 value) internal pure returns (uint136) {
require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v2.5._
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*
* _Available since v4.7._
*/
function toUint120(uint256 value) internal pure returns (uint120) {
require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*
* _Available since v4.7._
*/
function toUint112(uint256 value) internal pure returns (uint112) {
require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*
* _Available since v4.7._
*/
function toUint104(uint256 value) internal pure returns (uint104) {
require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*
* _Available since v4.2._
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*
* _Available since v4.7._
*/
function toUint88(uint256 value) internal pure returns (uint88) {
require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*
* _Available since v4.7._
*/
function toUint80(uint256 value) internal pure returns (uint80) {
require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*
* _Available since v4.7._
*/
function toUint72(uint256 value) internal pure returns (uint72) {
require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v2.5._
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*
* _Available since v4.7._
*/
function toUint56(uint256 value) internal pure returns (uint56) {
require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*
* _Available since v4.7._
*/
function toUint48(uint256 value) internal pure returns (uint48) {
require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*
* _Available since v4.7._
*/
function toUint40(uint256 value) internal pure returns (uint40) {
require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v2.5._
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*
* _Available since v4.7._
*/
function toUint24(uint256 value) internal pure returns (uint24) {
require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v2.5._
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*
* _Available since v2.5._
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*
* _Available since v3.0._
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*
* _Available since v4.7._
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
require(downcasted == value, "SafeCast: value doesn't fit in 248 bits");
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*
* _Available since v4.7._
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
require(downcasted == value, "SafeCast: value doesn't fit in 240 bits");
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*
* _Available since v4.7._
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
require(downcasted == value, "SafeCast: value doesn't fit in 232 bits");
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*
* _Available since v4.7._
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
require(downcasted == value, "SafeCast: value doesn't fit in 224 bits");
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*
* _Available since v4.7._
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
require(downcasted == value, "SafeCast: value doesn't fit in 216 bits");
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*
* _Available since v4.7._
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
require(downcasted == value, "SafeCast: value doesn't fit in 208 bits");
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*
* _Available since v4.7._
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
require(downcasted == value, "SafeCast: value doesn't fit in 200 bits");
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*
* _Available since v4.7._
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
require(downcasted == value, "SafeCast: value doesn't fit in 192 bits");
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*
* _Available since v4.7._
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
require(downcasted == value, "SafeCast: value doesn't fit in 184 bits");
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*
* _Available since v4.7._
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
require(downcasted == value, "SafeCast: value doesn't fit in 176 bits");
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*
* _Available since v4.7._
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
require(downcasted == value, "SafeCast: value doesn't fit in 168 bits");
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*
* _Available since v4.7._
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
require(downcasted == value, "SafeCast: value doesn't fit in 160 bits");
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*
* _Available since v4.7._
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*
* _Available since v4.7._
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
require(downcasted == value, "SafeCast: value doesn't fit in 144 bits");
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*
* _Available since v4.7._
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
require(downcasted == value, "SafeCast: value doesn't fit in 128 bits");
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*
* _Available since v4.7._
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
require(downcasted == value, "SafeCast: value doesn't fit in 120 bits");
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*
* _Available since v4.7._
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
require(downcasted == value, "SafeCast: value doesn't fit in 112 bits");
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*
* _Available since v4.7._
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
require(downcasted == value, "SafeCast: value doesn't fit in 104 bits");
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*
* _Available since v4.7._
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
require(downcasted == value, "SafeCast: value doesn't fit in 96 bits");
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*
* _Available since v4.7._
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
require(downcasted == value, "SafeCast: value doesn't fit in 88 bits");
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*
* _Available since v4.7._
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
require(downcasted == value, "SafeCast: value doesn't fit in 80 bits");
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*
* _Available since v4.7._
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
require(downcasted == value, "SafeCast: value doesn't fit in 72 bits");
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
require(downcasted == value, "SafeCast: value doesn't fit in 64 bits");
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*
* _Available since v4.7._
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
require(downcasted == value, "SafeCast: value doesn't fit in 56 bits");
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*
* _Available since v4.7._
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
require(downcasted == value, "SafeCast: value doesn't fit in 48 bits");
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*
* _Available since v4.7._
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
require(downcasted == value, "SafeCast: value doesn't fit in 40 bits");
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
require(downcasted == value, "SafeCast: value doesn't fit in 32 bits");
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*
* _Available since v4.7._
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
require(downcasted == value, "SafeCast: value doesn't fit in 24 bits");
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
require(downcasted == value, "SafeCast: value doesn't fit in 16 bits");
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
require(downcasted == value, "SafeCast: value doesn't fit in 8 bits");
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*
* _Available since v3.0._
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return
success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.18;
import {ERC20} from "@tokenized-strategy/BaseStrategy.sol";
import {BaseHealthCheck} from "@periphery/Bases/HealthCheck/BaseHealthCheck.sol";
import {Auction, AuctionSwapper} from "@periphery/swappers/AuctionSwapper.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IERC20Pool} from "@ajna-core/interfaces/pool/erc20/IERC20Pool.sol";
import {COLLATERALIZATION_FACTOR} from "@ajna-core/libraries/helpers/PoolHelper.sol";
import {Maths} from "@ajna-core/libraries/internal/Maths.sol";
import {PoolCommons} from "@ajna-core/libraries/external/PoolCommons.sol";
import {IUniswapV3Pool} from "@uniswap-v3-core/interfaces/IUniswapV3Pool.sol";
import {IUniswapV3SwapCallback} from "@uniswap-v3-core/interfaces/callback/IUniswapV3SwapCallback.sol";
import {IUniswapV3Factory} from "@uniswap-v3-core/interfaces/IUniswapV3Factory.sol";
import {IWETH} from "./interfaces/IWeth.sol";
import {IAccount} from "./interfaces/summerfi/IAccount.sol";
import {IAccountFactory} from "./interfaces/summerfi/IAccountFactory.sol";
import {AjnaProxyActions} from "./interfaces/summerfi/AjnaProxyActions.sol";
import {IAjnaRedeemer} from "./interfaces/summerfi/IAjnaRedeemer.sol";
import {IChainlinkAggregator} from "./interfaces/chainlink/IChainlinkAggregator.sol";
contract Strategy is BaseHealthCheck, IUniswapV3SwapCallback, AuctionSwapper {
using SafeERC20 for ERC20;
IAccountFactory private constant SUMMERFI_ACCOUNT_FACTORY =
IAccountFactory(0xF7B75183A2829843dB06266c114297dfbFaeE2b6);
AjnaProxyActions private constant SUMMERFI_AJNA_PROXY_ACTIONS =
AjnaProxyActions(0x3637DF43F938b05A71bb828f13D9f14498E6883c);
//PoolInfoUtils private constant POOL_INFO_UTILS =
// PoolInfoUtils(0x30c5eF2997d6a882DE52c4ec01B6D0a5e5B4fAAE);
IAjnaRedeemer private constant SUMMERFI_REWARDS =
IAjnaRedeemer(0xf309EE5603bF05E5614dB930E4EAB661662aCeE6);
IUniswapV3Factory private constant UNISWAP_FACTORY =
IUniswapV3Factory(0x1F98431c8aD98523631AE4a59f267346ea31F984);
address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address private constant AJNA_TOKEN =
0x9a96ec9B57Fb64FbC60B423d1f4da7691Bd35079;
IAccount public immutable summerfiAccount;
IERC20Pool public immutable ajnaPool;
IChainlinkAggregator public immutable chainlinkOracle;
bool public immutable oracleWrapped;
bytes4 public immutable unwrappedToWrappedSelector;
bool private immutable uniswapAsset0Weth1;
uint96 public minAjnaToAuction = 1_000e18; // 1000 ajna
IUniswapV3Pool public uniswapPool;
bool public positionOpen;
uint16 public slippageAllowedBps = 50; // 0.50%
uint64 public maxTendBasefee = 30e9; // 30 gwei
uint256 public depositLimit;
struct LTVConfig {
uint64 targetLTV;
uint64 minAdjustThreshold;
uint64 warningThreshold;
uint64 emergencyThreshold;
}
LTVConfig public ltvs;
uint256 private constant ONE_WAD = 1e18;
uint64 internal constant DEFAULT_MIN_ADJUST_THRESHOLD = 0.005e18;
uint64 internal constant DEFAULT_WARNING_THRESHOLD = 0.01e18;
uint64 internal constant DEFAULT_EMERGENCY_THRESHOLD = 0.02e18;
uint64 internal constant DUST_THRESHOLD = 100; //0.00001e18;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant UNISWAP_MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant UNISWAP_MAX_SQRT_RATIO =
1461446703485210103287273052203988822378723970342;
constructor(
address _asset,
string memory _name,
address _ajnaPool,
uint24 _uniswapFee,
bytes4 _unwrappedToWrappedSelector,
address _chainlinkOracle,
bool _oracleWrapped
) BaseHealthCheck(_asset, _name) {
require(_asset == IERC20Pool(_ajnaPool).collateralAddress(), "!collat"); // dev: asset must be collateral
require(WETH == IERC20Pool(_ajnaPool).quoteTokenAddress(), "!weth"); // dev: quoteToken must be WETH
address _summerfiAccount = SUMMERFI_ACCOUNT_FACTORY.createAccount();
ajnaPool = IERC20Pool(_ajnaPool);
summerfiAccount = IAccount(_summerfiAccount);
unwrappedToWrappedSelector = _unwrappedToWrappedSelector;
chainlinkOracle = IChainlinkAggregator(_chainlinkOracle);
oracleWrapped = _oracleWrapped;
uniswapAsset0Weth1 = address(asset) < WETH;
ERC20(_asset).safeApprove(_summerfiAccount, type(uint256).max);
LTVConfig memory _ltvs;
_ltvs.minAdjustThreshold = DEFAULT_MIN_ADJUST_THRESHOLD;
_ltvs.warningThreshold = DEFAULT_WARNING_THRESHOLD;
_ltvs.emergencyThreshold = DEFAULT_EMERGENCY_THRESHOLD;
ltvs = _ltvs;
_setUniswapFee(_uniswapFee);
}
/*******************************************
* PUBLIC VIEW FUNCTIONS *
*******************************************/
/**
* @notice Retrieves info related to our debt position
* @return _debt Current debt owed (`WAD`).
* @return _collateral Pledged collateral, including encumbered (`WAD`).
* @return _t0Np `Neutral price` (`WAD`).
* @return _thresholdPrice Borrower's `Threshold Price` (`WAD`).
*/
function positionInfo()
external
view
returns (
uint256 _debt,
uint256 _collateral,
uint256 _t0Np,
uint256 _thresholdPrice
)
{
return _positionInfo();
}
/**
* @return . The strategy's current LTV
*/
function currentLTV() external view returns (uint256) {
(uint256 _debt, uint256 _collateral, , ) = _positionInfo();
return _calculateLTV(_debt, _collateral, _getAssetPerWeth());
}
/**
* @notice A conservative estimate of assets taking into account
* the max slippage allowed
*
* @return . estimated total assets
*/
function estimatedTotalAssets() external view returns (uint256) {
(uint256 _debt, uint256 _collateral, , ) = _positionInfo();
uint256 _idle = _looseAssets();
return
_calculateNetPositionWithMaxSlippage(
_debt,
_collateral,
_getAssetPerWeth()
) + _idle;
}
/**
* @notice A liberal estimate of assets not taking into account
* the max slippage allowed
*
* @return . estimated total assets
*/
function estimatedTotalAssetsNoSlippage() external view returns (uint256) {
(uint256 _debt, uint256 _collateral, , ) = _positionInfo();
// increase debt by max slippage, since we must swap all debt to exit our position
uint256 _idle = _looseAssets();
return
_calculateNetPosition(_debt, _collateral, _getAssetPerWeth()) +
_idle;
}
/*******************************************
* MANAGEMENT FUNCTIONS *
*******************************************/
/**
* @notice Sets the ltv configuration. Can only be called by management
* @param _ltvs The LTV configuration
*/
function setLtvConfig(LTVConfig memory _ltvs) external onlyManagement {
require(_ltvs.warningThreshold < _ltvs.emergencyThreshold); // dev: warning must be less than emergency threshold
require(_ltvs.minAdjustThreshold < _ltvs.warningThreshold); // dev: minAdjust must be less than warning threshold
ltvs = _ltvs;
}
/**
* @notice Sets the uniswap fee tier. Can only be called by management
* @param _fee The uniswap fee tier to use for Asset<->Weth swaps
*/
function setUniswapFee(uint24 _fee) external onlyManagement {
_setUniswapFee(_fee);
}
/**
* @notice Sets the deposit limit. Can only be called by management
* @param _depositLimit The deposit limit
*/
function setDepositLimit(uint256 _depositLimit) external onlyManagement {
depositLimit = _depositLimit;
}
/**
* @notice Sets the slippage allowed on swaps. Can only be called by management
* @param _slippageAllowedBps The slippage allowed in basis points
*/
function setSlippageAllowedBps(uint16 _slippageAllowedBps)
external
onlyManagement
{
require(_slippageAllowedBps <= MAX_BPS); // dev: cannot be more than 100%
slippageAllowedBps = _slippageAllowedBps;
}
/**
* @notice Sets the max base fee for tends. Can only be called by management
* @param _maxTendBasefee The maximum base fee allowed in non-emergency tends
*/
function setMaxTendBasefee(uint64 _maxTendBasefee) external onlyManagement {
maxTendBasefee = _maxTendBasefee;
}
function setMinAjnaToAuction(uint96 _minAjnaToAuction)
external
onlyManagement
{
minAjnaToAuction = _minAjnaToAuction;
}
function setAuction(address _auction) external onlyEmergencyAuthorized {
if (_auction != address(0)) {
require(Auction(_auction).want() == address(asset)); // dev: wrong want
}
auction = _auction;
}
/***********************************************
* BASE STRATEGY OVERRIDE FUNCTIONS *
***********************************************/
/**
* @dev Should deploy up to '_amount' of 'asset' in the yield source.
*
* This function is called at the end of a {deposit} or {mint}
* call. Meaning that unless a whitelist is implemented it will
* be entirely permissionless and thus can be sandwiched or otherwise
* manipulated.
*
* @param _amount The amount of 'asset' that the strategy should attempt
* to deposit in the yield source.
*/
function _deployFunds(uint256 _amount) internal override {
if (!positionOpen) {
return;
}
_depositAndDraw(0, _amount, ONE_WAD, false); // deposit as collateral
}
/**
* @dev Will attempt to free the '_amount' of 'asset'.
*
* The amount of 'asset' that is already loose has already
* been accounted for.
*
* This function is called during {withdraw} and {redeem} calls.
* Meaning that unless a whitelist is implemented it will be
* entirely permissionless and thus can be sandwiched or otherwise
* manipulated.
*
* Should not rely on asset.balanceOf(address(this)) calls other than
* for diff accounting purposes.
*
* Any difference between `_amount` and what is actually freed will be
* counted as a loss and passed on to the withdrawer. This means
* care should be taken in times of illiquidity. It may be better to revert
* if withdraws are simply illiquid so not to realize incorrect losses.
*
* @param _amount, The amount of 'asset' to be freed.
*/
function _freeFunds(uint256 _amount) internal override {
(uint256 _debt, uint256 _collateral, , ) = _positionInfo();
uint256 _price = _getAssetPerWeth();
uint256 _positionValue = _calculateNetPosition(
_debt,
_collateral,
_price
) + _looseAssets();
uint256 _totalAssets = TokenizedStrategy.totalAssets();
uint256 _deployed = _deployedAssets(_totalAssets);
if (_amount != _deployed && _positionValue < _totalAssets) {
_amount = (_amount * _positionValue) / _totalAssets;
}
LTVConfig memory _ltvs = ltvs;
_leverDown(_debt, _collateral, _amount, _ltvs, _price, _deployed);
(_debt, _collateral, , ) = _positionInfo();
require(
_calculateLTV(_debt, _collateral, _price) <
_ltvs.targetLTV + _ltvs.minAdjustThreshold,
"!ltv"
); // dev: ltv in target
}
/**
* @dev Internal function to harvest all rewards, redeploy any idle
* funds and return an accurate accounting of all funds currently
* held by the Strategy.
*
* This should do any needed harvesting, rewards selling, accrual,
* redepositing etc. to get the most accurate view of current assets.
*
* NOTE: All applicable assets including loose assets should be
* accounted for in this function.
*
* Care should be taken when relying on oracles or swap values rather
* than actual amounts as all Strategy profit/loss accounting will
* be done based on this returned value.
*
* This can still be called post a shutdown, a strategist can check
* `TokenizedStrategy.isShutdown()` to decide if funds should be
* redeployed or simply realize any profits/losses.
*
* @return _totalAssets A trusted and accurate account for the total
* amount of 'asset' the strategy currently holds including idle funds.
*/
function _harvestAndReport()
internal
override
returns (uint256 _totalAssets)
{
_adjustPosition(_looseAssets());
(uint256 _debt, uint256 _collateral, , ) = _positionInfo();
_totalAssets =
_calculateNetPositionWithMaxSlippage(
_debt,
_collateral,
_getAssetPerWeth()
) +
_looseAssets();
}
/*//////////////////////////////////////////////////////////////
OPTIONAL TO OVERRIDE BY STRATEGIST
//////////////////////////////////////////////////////////////*/
/**
* @dev Optional function for strategist to override that can
* be called in between reports.
*
* If '_tend' is used tendTrigger() will also need to be overridden.
*
* This call can only be called by a permissioned role so may be
* through protected relays.
*
* This can be used to harvest and compound rewards, deposit idle funds,
* perform needed position maintenance or anything else that doesn't need
* ssda full report for.
*
* EX: A strategy that can not deposit funds without getting
* sandwiched can use the tend when a certain threshold
* of idle to totalAssets has been reached.
*
* The TokenizedStrategy contract will do all needed debt and idle updates
* after this has finished and will have no effect on PPS of the strategy
* till report() is called.
*
* @param _idle The current amount of idle funds that are available to deploy.
*
*/
function _tend(uint256 _idle) internal override {
_adjustPosition(_idle);
}
/**
* @dev Optional trigger to override if tend() will be used by the strategy.
* This must be implemented if the strategy hopes to invoke _tend().
*
* @return . Should return true if tend() should be called by keeper or false if not.
*
*/
function _tendTrigger() internal view override returns (bool) {
if (TokenizedStrategy.totalAssets() == 0 || !positionOpen) {
return false;
}
(
uint256 _debt,
uint256 _collateral,
,
uint256 _thresholdPrice
) = _positionInfo();
LTVConfig memory _ltvs = ltvs;
uint256 _assetPerWeth = _getAssetPerWeth();
uint256 _wethPerAsset = (ONE_WAD**2) / _assetPerWeth;
uint256 _currentLtv = _calculateLTV(_debt, _collateral, _assetPerWeth);
// We need to lever down if the LTV is past the emergencyThreshold
// or the price is below the threshold price
if (
_currentLtv >= _ltvs.targetLTV + _ltvs.emergencyThreshold ||
_wethPerAsset <= _thresholdPrice
) {
return true;
}
// All other checks can wait for low gas
if (block.basefee >= maxTendBasefee) {
return false;
}
// Tend if ltv is higher than the target range
if (_currentLtv >= _ltvs.targetLTV + _ltvs.warningThreshold) {
return true;
}
if (TokenizedStrategy.isShutdown()) {
return false;
}
// Tend if ltv is lower than target range
if (
_currentLtv != 0 &&
_currentLtv <= _ltvs.targetLTV - _ltvs.minAdjustThreshold &&
_availableWethBorrow() > DUST_THRESHOLD
) {
return true;
}
return false;
}
/**
* @notice Gets the max amount of `asset` that an address can deposit.
* @dev Defaults to an unlimited amount for any address. But can
* be overridden by strategists.
*
* This function will be called before any deposit or mints to enforce
* any limits desired by the strategist. This can be used for either a
* traditional deposit limit or for implementing a whitelist etc.
*
* EX:
* if(isAllowed[_owner]) return super.availableDepositLimit(_owner);
*
* This does not need to take into account any conversion rates
* from shares to assets. But should know that any non max uint256
* amounts may be converted to shares. So it is recommended to keep
* custom amounts low enough as not to cause overflow when multiplied
* by `totalSupply`.
*
* @param . The address that is depositing into the strategy.
* @return . The available amount the `_owner` can deposit in terms of `asset`
*
*/
function availableDepositLimit(
address /*_owner */
) public view override returns (uint256) {
uint256 _totalAssets = TokenizedStrategy.totalAssets();
return _totalAssets >= depositLimit ? 0 : depositLimit - _totalAssets;
}
/**
* @dev Optional function for a strategist to override that will
* allow management to manually withdraw deployed funds from the
* yield source if a strategy is shutdown.
*
* This should attempt to free `_amount`, noting that `_amount` may
* be more than is currently deployed.
*
* NOTE: This will not realize any profits or losses. A separate
* {report} will be needed in order to record any profit/loss. If
* a report may need to be called after a shutdown it is important
* to check if the strategy is shutdown during {_harvestAndReport}
* so that it does not simply re-deploy all funds that had been freed.
*
* EX:
* if(freeAsset > 0 && !TokenizedStrategy.isShutdown()) {
* depositFunds...
* }
*
* @param _amount The amount of asset to attempt to free.
*
*/
function _emergencyWithdraw(uint256 _amount) internal override {
(uint256 _debt, uint256 _collateral, , ) = _positionInfo();
uint256 _price = _getAssetPerWeth();
LTVConfig memory _ltvs = ltvs;
_leverDown(
_debt,
_collateral,
_amount,
_ltvs,
_price,
_deployedAssets()
);
(_debt, _collateral, , ) = _positionInfo();
require(
_calculateLTV(_debt, _collateral, _price) <
_ltvs.targetLTV + _ltvs.minAdjustThreshold,
"!ltv"
); // dev: ltv in target
}
function _auctionKicked(address _token)
internal
virtual
override
returns (uint256 _kicked)
{
require(_token == AJNA_TOKEN); // dev: only sell ajna
_kicked = super._auctionKicked(_token);
require(_kicked >= minAjnaToAuction); // dev: too little
}
/**************************************************
* EXTERNAL POSTION MANAGMENT FUNCTIONS *
**************************************************/
/**
* @notice Allows emergency authorized to manually lever down
*
* @param _toLoose the amount of assets to attempt to loose
* @param _targetLTV the LTV ratio to target
* @param _force Ignore safety checks
*/
function manualLeverDown(
uint256 _toLoose,
uint64 _targetLTV,
bool _force
) external onlyEmergencyAuthorized {
(uint256 _debt, uint256 _collateral, , ) = _positionInfo();
uint256 _price = _getAssetPerWeth();
LTVConfig memory _ltvs = ltvs;
require(_force || _targetLTV <= ltvs.targetLTV); // dev: _targetLTV too high
_ltvs.targetLTV = _targetLTV;
_leverDown(
_debt,
_collateral,
_toLoose,
_ltvs,
_price,
_deployedAssets()
);
(_debt, _collateral, , ) = _positionInfo();
require(
_force ||
_calculateLTV(_debt, _collateral, _price) <
_ltvs.targetLTV + _ltvs.minAdjustThreshold,
"!ltv"
); // dev: ltv in target
}
/**
* @notice Allows emergency authorized to manually repay and/or withdrwa
*
* @param _debtAmount Amount of debt to repay
* @param _collateralAmount Amount of collateral to withdraw
* @param _stamp Whether to stamp the loan or not
*/
function manualRepayWithdraw(
uint256 _debtAmount,
uint256 _collateralAmount,
bool _stamp
) external onlyEmergencyAuthorized {
_repayWithdraw(_debtAmount, _collateralAmount, _stamp);
}
/**
* @notice Allows emergency authorized to manually swap asset<->weth or vice versa
*
* @param _amountIn Amount of input token
* @param _minOut Minimum output token acceptable
* @param _assetForWeth Whether to swap asset for weth or weth for asset
*/
function manualSwap(
uint256 _amountIn,
uint64 _minOut,
bool _assetForWeth
) external onlyEmergencyAuthorized {
bool zeroForOne = uniswapAsset0Weth1 ? _assetForWeth : !_assetForWeth;
bytes memory _data = abi.encode(
LeverData(LeverAction.ManualSwap, 0, 0, 0)
);
(int256 amount0, int256 amount1) = uniswapPool.swap(
address(this),
zeroForOne,
int256(_amountIn),
(
zeroForOne
? UNISWAP_MIN_SQRT_RATIO + 1
: UNISWAP_MAX_SQRT_RATIO - 1
),
_data
);
require(uint256(zeroForOne ? amount1 : amount0) >= _minOut); // dev: !minOut
}
/**
* @notice Claims summerfi ajna rewards
*
* Unguarded because there is no risk claiming
*
* @param _weeks An array of week numbers for which to claim rewards.
* @param _amounts An array of reward amounts to claim.
* @param _proofs An array of Merkle proofs, one for each corresponding week and amount given.
*/
function redeemSummerAjnaRewards(
uint256[] calldata _weeks,
uint256[] calldata _amounts,
bytes32[][] calldata _proofs
) external {
SUMMERFI_REWARDS.claimMultiple(_weeks, _amounts, _proofs);
}
/**************************************************
* INTERNAL POSTION MANAGMENT FUNCTIONS *
**************************************************/
/**
* @notice Adjusts the leveraged position
*/
function _adjustPosition(uint256 _idle) internal {
(
uint256 _debt,
uint256 _collateral,
,
uint256 _thresholdPrice
) = _positionInfo();
LTVConfig memory _ltvs = ltvs;
uint256 _assetPerWeth = _getAssetPerWeth();
uint256 _wethPerAsset = ONE_WAD**2 / _assetPerWeth;
uint256 _currentLtv = _calculateLTV(_debt, _collateral, _assetPerWeth);
if (
positionOpen &&
(_wethPerAsset <= _thresholdPrice ||
_currentLtv >= _ltvs.targetLTV + _ltvs.minAdjustThreshold)
) {
_leverDown(
_debt,
_collateral,
0,
_ltvs,
_assetPerWeth,
_deployedAssets()
);
} else if (_currentLtv + _ltvs.minAdjustThreshold <= _ltvs.targetLTV) {
_leverUp(_debt, _collateral, _idle, _ltvs, _assetPerWeth);
} else {
return; // bail out if we are doing nothing
}
(_debt, _collateral, , _thresholdPrice) = _positionInfo();
_currentLtv = _calculateLTV(_debt, _collateral, _assetPerWeth);
require(
_currentLtv < _ltvs.targetLTV + _ltvs.minAdjustThreshold,
"!ltv"
); // dev: not safe
}
enum LeverAction {
LeverUp,
LeverDown,
ClosePosition,
ManualSwap
}
struct LeverData {
LeverAction action;
uint256 assetToFree;
uint256 assetPerWeth;
uint256 totalCollateral;
}
/**
* @notice Levers up
*/
function _leverUp(
uint256 _debt,
uint256 _collateral,
uint256 _idle,
LTVConfig memory _ltvs,
uint256 _assetPerWeth
) internal {
uint256 _supply = _calculateNetPosition(
_debt,
_collateral,
_assetPerWeth
);
uint256 _targetBorrow = _getBorrowFromSupply(
_supply + _idle,
_ltvs.targetLTV,
_assetPerWeth
);
require(_targetBorrow > _debt); // dev: something is very wrong
uint256 _toBorrow = _targetBorrow - _debt;
uint256 _availableBorrow = _availableWethBorrow();
if (_availableBorrow < _toBorrow) {
_toBorrow = _availableBorrow;
}
if (_toBorrow < DUST_THRESHOLD || _debt + _toBorrow < _minLoanSize()) {
return;
}
_swapAndLeverUp(_toBorrow, _assetPerWeth);
}
/**
* @notice Levers down
*/
function _leverDown(
uint256 _debt,
uint256 _collateral,
uint256 _assetToFree,
LTVConfig memory _ltvs,
uint256 _assetPerWeth,
uint256 _deployedAssets
) internal {
uint256 _supply = _calculateNetPosition(
_debt,
_collateral,
_assetPerWeth
);
uint256 _targetBorrow;
if (_supply > _assetToFree) {
_targetBorrow = _getBorrowFromSupply(
_supply - _assetToFree,
_ltvs.targetLTV,
_assetPerWeth
);
} else {
_assetToFree = _supply;
}
if (_debt <= _targetBorrow) {
if (_assetToFree > DUST_THRESHOLD) {
_repayWithdraw(0, _assetToFree, false);
}
return;
}
uint256 _repaymentAmount;
unchecked {
_repaymentAmount = _debt - _targetBorrow;
}
if (_targetBorrow < _minLoanSize(-int256(_repaymentAmount))) {
_targetBorrow = 0;
_repaymentAmount = _debt;
}
bool _closePosition = _repaymentAmount == _debt &&
(_assetToFree == 0 ||
_assetToFree == _supply ||
_assetToFree >= _deployedAssets);
_swapAndLeverDown(
_repaymentAmount,
_assetToFree,
_closePosition,
_assetPerWeth,
_collateral
);
}
/**************************************************
* UNISWAP FUNCTIONS *
**************************************************/
function _swapAndLeverUp(uint256 _borrowAmount, uint256 _assetPerWeth)
private
{
bool zeroForOne = !uniswapAsset0Weth1;
bytes memory _data = abi.encode(
LeverData(
LeverAction.LeverUp,
uint256(0),
_assetPerWeth,
uint256(0)
)
);
/* (int256 amount0, int256 amount1) = */
uniswapPool.swap(
address(this),
zeroForOne,
int256(_borrowAmount),
(
zeroForOne
? UNISWAP_MIN_SQRT_RATIO + 1
: UNISWAP_MAX_SQRT_RATIO - 1
),
_data
);
}
function _swapAndLeverDown(
uint256 _repaymentAmount,
uint256 _assetToLoose,
bool _close,
uint256 _assetPerWeth,
uint256 _totalCollateral
) private {
bool zeroForOne = uniswapAsset0Weth1;
bytes memory _data = abi.encode(
LeverData(
_close ? LeverAction.ClosePosition : LeverAction.LeverDown,
_assetToLoose,
_assetPerWeth,
_totalCollateral
)
);
(int256 amount0Delta, int256 amount1Delta) = uniswapPool.swap(
address(this),
zeroForOne,
-int256(_repaymentAmount),
(
zeroForOne
? UNISWAP_MIN_SQRT_RATIO + 1
: UNISWAP_MAX_SQRT_RATIO - 1
),
_data
);
uint256 _wethOut = uint256(zeroForOne ? -amount1Delta : -amount0Delta);
// it's technically possible to not receive the full output amount
// require this possibility away
require(_wethOut == _repaymentAmount); // dev: wethOut != _repaymentAmount
}
/// @inheritdoc IUniswapV3SwapCallback
function uniswapV3SwapCallback(
int256 _amount0Delta,
int256 _amount1Delta,
bytes calldata _data
) external {
require(msg.sender == address(uniswapPool)); // dev: callback only called by pool
require(_amount0Delta > 0 || _amount1Delta > 0); // dev: swaps entirely within 0-liquidity regions are not supported
(
bool _isExactInput,
uint256 _amountToPay,
uint256 _amountReceived
) = _amount0Delta > 0
? (
!uniswapAsset0Weth1,
uint256(_amount0Delta),
uint256(-_amount1Delta)
)
: (
uniswapAsset0Weth1,
uint256(_amount1Delta),
uint256(-_amount0Delta)
);
LeverData memory _leverData = abi.decode(_data, (LeverData));
if (_leverData.action == LeverAction.LeverUp) {
require(_isExactInput); // dev: WTF
uint256 _leastAssetReceived = (((_amountToPay *
(MAX_BPS - slippageAllowedBps)) / MAX_BPS) *
_leverData.assetPerWeth) / ONE_WAD;
require(_amountReceived >= _leastAssetReceived, "!slippage"); // dev: too much slippage
uint256 _collateralToAdd = _looseAssets();
if (!positionOpen) {
positionOpen = true;
_openPosition(_amountToPay, _collateralToAdd, ONE_WAD);
} else {
_depositAndDraw(_amountToPay, _collateralToAdd, ONE_WAD, false);
}
ERC20(WETH).transfer(msg.sender, _amountToPay);
} else if (
_leverData.action == LeverAction.LeverDown ||
_leverData.action == LeverAction.ClosePosition
) {
require(!_isExactInput); // dev: WTF
uint256 _expectedAssetToPay = (_amountReceived *
_leverData.assetPerWeth) / ONE_WAD;
uint256 _mostAssetToPay = (_expectedAssetToPay *
(MAX_BPS + slippageAllowedBps)) / MAX_BPS;
require(_amountToPay <= _mostAssetToPay, "!slippage"); // dev: too much slippage
if (_amountToPay > _expectedAssetToPay) {
// pass slippage onto the asset to free amount
uint256 _slippage = _amountToPay - _expectedAssetToPay;
if (_leverData.assetToFree > _slippage) {
_leverData.assetToFree -= _slippage;
} else {
_leverData.assetToFree = 0;
}
}
if (_leverData.action == LeverAction.LeverDown) {
_repayWithdraw(
_amountReceived,
Math.min(
_amountToPay + _leverData.assetToFree,
_leverData.totalCollateral
),
false
);
} else if (_leverData.action == LeverAction.ClosePosition) {
positionOpen = false;
_repayAndClose(_amountReceived);
}
asset.transfer(msg.sender, _amountToPay);
} else if (_leverData.action == LeverAction.ManualSwap) {
//require(_isExactInput, "!wtf"); // dev: WTF
if (
(_amount0Delta > 0 && uniswapAsset0Weth1) ||
(_amount1Delta > 0 && !uniswapAsset0Weth1)
) {
asset.transfer(msg.sender, _amountToPay);
} else {
ERC20(WETH).transfer(msg.sender, _amountToPay);
}
}
}
/**************************************************
* INTERNAL VIEWS *
**************************************************/
/**
* @notice Returns the strategy assets which are held as loose asset
* @return . The strategy's loose asset
*/
function _looseAssets() internal view returns (uint256) {
return asset.balanceOf(address(this));
}
/**
* @notice Returns the strategy assets which are not idle
* @return . The strategy's total debt
*/
function _deployedAssets() internal view returns (uint256) {
return _deployedAssets(TokenizedStrategy.totalAssets());
}
/**
* @notice Returns the strategy assets which are not idle
* @return . The strategy's total debt
*/
function _deployedAssets(uint256 _totalAssets)
internal
view
returns (uint256)
{
uint256 _idle = _looseAssets();
if (_idle >= _totalAssets) return 0;
return _totalAssets - _idle;
}
/**
* @notice Retrieves info related to our debt position
* @return _debt Current debt owed (`WAD`).
* @return _collateral Pledged collateral, including encumbered (`WAD`).
* @return _t0Np `Neutral price` (`WAD`).
* @return _thresholdPrice Borrower's `Threshold Price` (`WAD`).
*/
function _positionInfo()
internal
view
returns (
uint256 _debt,
uint256 _collateral,
uint256 _t0Np,
uint256 _thresholdPrice
)
{
IERC20Pool _ajnaPool = ajnaPool;
// copied from BUSL, am i going to open source jail?
(uint256 inflator, uint256 lastInflatorUpdate) = _ajnaPool
.inflatorInfo();
(uint256 interestRate, ) = _ajnaPool.interestRateInfo();
uint256 pendingInflator = PoolCommons.pendingInflator(
inflator,
lastInflatorUpdate,
interestRate
);
uint256 t0Debt;
uint256 npTpRatio;
(t0Debt, _collateral, npTpRatio) = _ajnaPool.borrowerInfo(
address(summerfiAccount)
);
_t0Np = _collateral == 0
? 0
: Math.mulDiv(
Maths.wmul(t0Debt, COLLATERALIZATION_FACTOR),
npTpRatio,
_collateral
);
_debt = Maths.ceilWmul(t0Debt, pendingInflator);
_thresholdPrice = _collateral == 0
? 0
: Maths.wmul(
Maths.wdiv(_debt, _collateral),
COLLATERALIZATION_FACTOR
);
}
/**
* @notice Returns the amount of quote token available for borrowing or removing from pool.
* @dev Calculated as the difference between pool balance and escrowed amounts locked in
* pool (auction bons + unclaimed reserves).
* @return _amount The total quote token amount available to borrow or to be removed from pool, in `WAD` units.
*/
function _availableWethBorrow() internal view returns (uint256 _amount) {
IERC20Pool _ajnaPool = ajnaPool;
// copied from BUSL, am i going to open source jail?
(uint256 bondEscrowed, uint256 unclaimedReserve, , , ) = _ajnaPool
.reservesInfo();
uint256 escrowedAmounts = bondEscrowed + unclaimedReserve;
uint256 poolBalance = ERC20(WETH).balanceOf(address(_ajnaPool)) *
_ajnaPool.quoteTokenScale();
if (poolBalance > escrowedAmounts)
_amount = poolBalance - escrowedAmounts;
}
/**
* @notice Retrieves the oracle rate asset/quoteToken
* @return Conversion rate
*/
function _getAssetPerWeth() internal view returns (uint256) {
uint256 _answer = (ONE_WAD**2) /
uint256(chainlinkOracle.latestAnswer());
if (oracleWrapped) {
return _answer;
}
return _unwrappedToWrappedAsset(_answer);
}
/**************************************************
* INTERNAL SETTERS *
**************************************************/
function _setUniswapFee(uint24 _fee) internal {
IUniswapV3Pool _uniswapPool = IUniswapV3Pool(
UNISWAP_FACTORY.getPool(address(asset), WETH, _fee)
);
require(
_uniswapPool.token0() == address(asset) ||
_uniswapPool.token1() == address(asset)
); // dev: pool must contain asset
require(
_uniswapPool.token0() == address(WETH) ||
_uniswapPool.token1() == address(WETH)
); // dev: pool must contain weth
uniswapPool = _uniswapPool;
}
/**************************************************
* POSITION HELPER FUNCTIONS *
**************************************************/
/**
* @notice Open position via account proxy
* @param _debtAmount Amount of debt to borrow
* @param _collateralAmount Amount of collateral to deposit
* @param _price Price of the bucket
*/
function _openPosition(
uint256 _debtAmount,
uint256 _collateralAmount,
uint256 _price
) internal {
summerfiAccount.execute(
address(SUMMERFI_AJNA_PROXY_ACTIONS),
abi.encodeCall(
SUMMERFI_AJNA_PROXY_ACTIONS.openPosition,
(ajnaPool, _debtAmount, _collateralAmount, _price)
)
);
IWETH(WETH).deposit{value: address(this).balance}(); // summer contracts use Ether not WETH
}
/**
* @notice Deposit collateral and draw debt via account proxy
* @param _debtAmount Amount of debt to borrow
* @param _collateralAmount Amount of collateral to deposit
* @param _price Price of the bucket
* @param _stamp Whether to stamp the loan or not
*/
function _depositAndDraw(
uint256 _debtAmount,
uint256 _collateralAmount,
uint256 _price,
bool _stamp
) internal {
summerfiAccount.execute(
address(SUMMERFI_AJNA_PROXY_ACTIONS),
abi.encodeCall(
SUMMERFI_AJNA_PROXY_ACTIONS.depositAndDraw,
(ajnaPool, _debtAmount, _collateralAmount, _price, _stamp)
)
);
IWETH(WETH).deposit{value: address(this).balance}(); // summer contracts use Ether not WETH
}
/**
* @notice Repay debt and withdraw collateral via account proxy
* @param _debtAmount Amount of debt to repay
* @param _collateralAmount Amount of collateral to withdraw
* @param _stamp Whether to stamp the loan or not
*/
function _repayWithdraw(
uint256 _debtAmount,
uint256 _collateralAmount,
bool _stamp
) internal {
if (_debtAmount != 0) {
IWETH(WETH).withdraw(_debtAmount); // summer contracts use Ether not WETH
}
summerfiAccount.execute{value: _debtAmount}(
address(SUMMERFI_AJNA_PROXY_ACTIONS),
abi.encodeCall(
SUMMERFI_AJNA_PROXY_ACTIONS.repayWithdraw,
(ajnaPool, _debtAmount, _collateralAmount, _stamp)
)
);
}
/**
* @notice Repay debt and close position via account proxy
*/
function _repayAndClose(uint256 _debtAmount) internal {
if (_debtAmount != 0) {
IWETH(WETH).withdraw(_debtAmount); // summer contracts use Ether not WETH
}
summerfiAccount.execute{value: _debtAmount}(
address(SUMMERFI_AJNA_PROXY_ACTIONS),
abi.encodeCall(
SUMMERFI_AJNA_PROXY_ACTIONS.repayAndClose,
(ajnaPool)
)
);
uint256 _balance = address(this).balance;
if (_balance != 0) {
IWETH(WETH).deposit{value: _balance}();
}
}
function _unwrappedToWrappedAsset(uint256 _amount)
internal
view
returns (uint256)
{
(bool success, bytes memory data) = address(asset).staticcall(
abi.encodeWithSelector(unwrappedToWrappedSelector, _amount)
);
require(success, "!success"); // dev: static call failed
return abi.decode(data, (uint256));
}
function _minLoanSize() internal view returns (uint256) {
return _minLoanSize(0);
}
function _minLoanSize(int256 _debtDelta)
internal
view
returns (uint256 _minDebtAmount)
{
IERC20Pool _ajnaPool = ajnaPool;
(uint256 _poolDebt, , , ) = _ajnaPool.debtInfo();
(, , uint256 _noOfLoans) = _ajnaPool.loansInfo();
if (_noOfLoans >= 10) {
// minimum debt is 10% of the average loan size
_minDebtAmount =
(uint256(int256(_poolDebt) + _debtDelta) / _noOfLoans) /
10;
}
}
/************************************************************************
* Position Math Functions *
************************************************************************/
function _getBorrowFromSupply(
uint256 _supply,
uint256 _collatRatio,
uint256 _assetPerWeth
) internal pure returns (uint256) {
if (_collatRatio == 0) {
return 0;
}
return
(((_supply * _collatRatio) / (ONE_WAD - _collatRatio)) * ONE_WAD) /
_assetPerWeth;
}
function _calculateLTV(
uint256 _debt,
uint256 _collateral,
uint256 _assetPerWeth
) internal pure returns (uint256) {
if (_debt == 0 || _collateral == 0) {
return 0;
}
return (_debt * _assetPerWeth) / _collateral;
}
function _calculateNetPositionWithMaxSlippage(
uint256 _debt,
uint256 _collateral,
uint256 _assetPerWeth
) internal view returns (uint256) {
// inflate debt by max slippage value
_debt = (_debt * (MAX_BPS + slippageAllowedBps)) / MAX_BPS;
return _calculateNetPosition(_debt, _collateral, _assetPerWeth);
}
function _calculateNetPosition(
uint256 _debt,
uint256 _collateral,
uint256 _assetPerWeth
) internal pure returns (uint256) {
_debt = (_debt * _assetPerWeth) / ONE_WAD;
if (_debt >= _collateral || _collateral == 0) {
return 0;
}
unchecked {
return _collateral - _debt;
}
}
// Needed to receive ETH
receive() external payable {}
}
{
"compilationTarget": {
"src/Strategy.sol": "Strategy"
},
"evmVersion": "paris",
"libraries": {
"lib/ajna-core/src/libraries/external/PoolCommons.sol:PoolCommons": "0xe88aaf46c9124b7b08c2dcc2505429ce72979648"
},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 2000
},
"remappings": [
":@ajna-core/=lib/ajna-core/src/",
":@base64-sol/=lib/ajna-core/lib/base64/",
":@clones/=lib/ajna-core/lib/clones-with-immutable-args/src/",
":@openzeppelin/=lib/openzeppelin-contracts/",
":@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
":@periphery/=lib/tokenized-strategy-periphery/src/",
":@prb-math/=lib/ajna-core/lib/prb-math/",
":@solmate/=lib/ajna-core/lib/solmate/src/",
":@std/=lib/ajna-core/lib/forge-std/src/",
":@tokenized-strategy/=lib/tokenized-strategy/src/",
":@uniswap-v3-core/=lib/v3-core/contracts/",
":@uniswap-v3-periphery/=lib/v3-periphery/contracts/",
":@uniswap/v3-core/=lib/v3-core/",
":@yearn-vaults/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/contracts/",
":ajna-core/=lib/ajna-core/",
":base64/=lib/ajna-core/lib/base64/",
":clones-with-immutable-args/=lib/ajna-core/lib/clones-with-immutable-args/src/",
":ds-test/=lib/tokenized-strategy-periphery/lib/forge-std/lib/ds-test/src/",
":erc4626-tests/=lib/tokenized-strategy/lib/erc4626-tests/",
":forge-std/=lib/forge-std/src/",
":openzeppelin-contracts/=lib/openzeppelin-contracts/",
":openzeppelin/=lib/openzeppelin-contracts/contracts/",
":prb-math/=lib/ajna-core/lib/prb-math/contracts/",
":src/=src/",
":tokenized-strategy-periphery/=lib/tokenized-strategy-periphery/",
":tokenized-strategy/=lib/tokenized-strategy/",
":v3-core/=lib/v3-core/contracts/",
":v3-periphery/=lib/v3-periphery/contracts/",
":yearn-vaults-v3/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/"
],
"viaIR": true
}
[{"inputs":[{"internalType":"address","name":"_asset","type":"address"},{"internalType":"string","name":"_name","type":"string"},{"internalType":"address","name":"_ajnaPool","type":"address"},{"internalType":"uint24","name":"_uniswapFee","type":"uint24"},{"internalType":"bytes4","name":"_unwrappedToWrappedSelector","type":"bytes4"},{"internalType":"address","name":"_chainlinkOracle","type":"address"},{"internalType":"bool","name":"_oracleWrapped","type":"bool"}],"stateMutability":"nonpayable","type":"constructor"},{"stateMutability":"nonpayable","type":"fallback"},{"inputs":[],"name":"ajnaPool","outputs":[{"internalType":"contract IERC20Pool","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"auction","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"auctionFactory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"auctionKicked","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"availableDepositLimit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"availableWithdrawLimit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"chainlinkOracle","outputs":[{"internalType":"contract IChainlinkAggregator","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"currentLTV","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"deployFunds","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"depositLimit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"doHealthCheck","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"estimatedTotalAssets","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"estimatedTotalAssetsNoSlippage","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"freeFunds","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"harvestAndReport","outputs":[{"internalType":"uint256","name":"_totalAssets","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"kickable","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lossLimitRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ltvs","outputs":[{"internalType":"uint64","name":"targetLTV","type":"uint64"},{"internalType":"uint64","name":"minAdjustThreshold","type":"uint64"},{"internalType":"uint64","name":"warningThreshold","type":"uint64"},{"internalType":"uint64","name":"emergencyThreshold","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_toLoose","type":"uint256"},{"internalType":"uint64","name":"_targetLTV","type":"uint64"},{"internalType":"bool","name":"_force","type":"bool"}],"name":"manualLeverDown","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_debtAmount","type":"uint256"},{"internalType":"uint256","name":"_collateralAmount","type":"uint256"},{"internalType":"bool","name":"_stamp","type":"bool"}],"name":"manualRepayWithdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_amountIn","type":"uint256"},{"internalType":"uint64","name":"_minOut","type":"uint64"},{"internalType":"bool","name":"_assetForWeth","type":"bool"}],"name":"manualSwap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"maxTendBasefee","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"minAjnaToAuction","outputs":[{"internalType":"uint96","name":"","type":"uint96"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"oracleWrapped","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"positionInfo","outputs":[{"internalType":"uint256","name":"_debt","type":"uint256"},{"internalType":"uint256","name":"_collateral","type":"uint256"},{"internalType":"uint256","name":"_t0Np","type":"uint256"},{"internalType":"uint256","name":"_thresholdPrice","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"positionOpen","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_amountTaken","type":"uint256"},{"internalType":"uint256","name":"_amountPayed","type":"uint256"}],"name":"postTake","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_amountToTake","type":"uint256"},{"internalType":"uint256","name":"_amountToPay","type":"uint256"}],"name":"preTake","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"profitLimitRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"_weeks","type":"uint256[]"},{"internalType":"uint256[]","name":"_amounts","type":"uint256[]"},{"internalType":"bytes32[][]","name":"_proofs","type":"bytes32[][]"}],"name":"redeemSummerAjnaRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_auction","type":"address"}],"name":"setAuction","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_depositLimit","type":"uint256"}],"name":"setDepositLimit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"_doHealthCheck","type":"bool"}],"name":"setDoHealthCheck","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_newLossLimitRatio","type":"uint256"}],"name":"setLossLimitRatio","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint64","name":"targetLTV","type":"uint64"},{"internalType":"uint64","name":"minAdjustThreshold","type":"uint64"},{"internalType":"uint64","name":"warningThreshold","type":"uint64"},{"internalType":"uint64","name":"emergencyThreshold","type":"uint64"}],"internalType":"struct Strategy.LTVConfig","name":"_ltvs","type":"tuple"}],"name":"setLtvConfig","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint64","name":"_maxTendBasefee","type":"uint64"}],"name":"setMaxTendBasefee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint96","name":"_minAjnaToAuction","type":"uint96"}],"name":"setMinAjnaToAuction","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_newProfitLimitRatio","type":"uint256"}],"name":"setProfitLimitRatio","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint16","name":"_slippageAllowedBps","type":"uint16"}],"name":"setSlippageAllowedBps","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint24","name":"_fee","type":"uint24"}],"name":"setUniswapFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"shutdownWithdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"slippageAllowedBps","outputs":[{"internalType":"uint16","name":"","type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"summerfiAccount","outputs":[{"internalType":"contract IAccount","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_totalIdle","type":"uint256"}],"name":"tendThis","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"tendTrigger","outputs":[{"internalType":"bool","name":"","type":"bool"},{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"tokenizedStrategyAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"uniswapPool","outputs":[{"internalType":"contract IUniswapV3Pool","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"int256","name":"_amount0Delta","type":"int256"},{"internalType":"int256","name":"_amount1Delta","type":"int256"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"uniswapV3SwapCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unwrappedToWrappedSelector","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]