Verified contractExactBUSL-1.1
LVLidoVault
Address0xbe2b67cd120f0ab47f7c6a64c21e1ec1fd5a8b6b
- Balance
0 ETH
- Transactions
2
- Compiler
solc 0.8.20
- Same code
Only this contract
Details
- Compiler
- solc 0.8.20+commit.a1b79de6
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- shanghai
- Via IR
- yes
- License
- BUSL-1.1
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 23,998,018
- Creation transaction
- 0x3c095812ca…e62a1d3014
68 files
- src/LVLidoVault.solmain60.18 KB
- lib/balancer-v2-monorepo/pkg/interfaces/contracts/solidity-utils/openzeppelin/IERC20.sol2.73 KB
- lib/openzeppelin-contracts/contracts/access/Ownable.sol3.1 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC4626.sol12.18 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol684 B
- lib/openzeppelin-contracts/contracts/utils/Context.sol963 B
- lib/prb-math/src/Common.sol25.41 KB
- lib/prb-math/src/UD60x18.sol2.15 KB
- lib/prb-math/src/sd1x18/Casting.sol2.32 KB
- lib/prb-math/src/sd1x18/Constants.sol758 B
- lib/prb-math/src/sd1x18/Errors.sol786 B
- lib/prb-math/src/sd1x18/ValueType.sol855 B
- lib/prb-math/src/sd21x18/Casting.sol2.35 KB
- lib/prb-math/src/sd21x18/Constants.sol823 B
- lib/prb-math/src/sd21x18/Errors.sol802 B
- lib/prb-math/src/sd21x18/ValueType.sol863 B
- lib/prb-math/src/sd59x18/Casting.sol4.94 KB
- lib/prb-math/src/sd59x18/Constants.sol2.78 KB
- lib/prb-math/src/sd59x18/Errors.sol4.46 KB
- lib/prb-math/src/sd59x18/Helpers.sol4.12 KB
- lib/prb-math/src/sd59x18/Math.sol27.63 KB
- lib/prb-math/src/sd59x18/ValueType.sol2.66 KB
- lib/prb-math/src/ud21x18/Casting.sol1.91 KB
- lib/prb-math/src/ud21x18/Constants.sol633 B
- lib/prb-math/src/ud21x18/Errors.sol241 B
- lib/prb-math/src/ud21x18/ValueType.sol868 B
- lib/prb-math/src/ud2x18/Casting.sol1.9 KB
- lib/prb-math/src/ud2x18/Constants.sol596 B
- lib/prb-math/src/ud2x18/Errors.sol237 B
- lib/prb-math/src/ud2x18/ValueType.sol861 B
- lib/prb-math/src/ud60x18/Casting.sol3.95 KB
- lib/prb-math/src/ud60x18/Constants.sol1.93 KB
- lib/prb-math/src/ud60x18/Conversions.sol1.02 KB
- lib/prb-math/src/ud60x18/Errors.sol2.03 KB
- lib/prb-math/src/ud60x18/Helpers.sol3.79 KB
- lib/prb-math/src/ud60x18/Math.sol22.83 KB
- lib/prb-math/src/ud60x18/ValueType.sol2.84 KB
- src/interfaces/ILVToken.sol685 B
- src/interfaces/ILiquidationProxy.sol224 B
- src/interfaces/IMorpho.sol453 B
- src/interfaces/IMorphoCallbacks.sol664 B
- src/interfaces/IPoolDataProvider.sol1.65 KB
- src/interfaces/IPoolInfoUtils.sol14.03 KB
- src/interfaces/pool/IERC3156FlashBorrower.sol728 B
- src/interfaces/pool/IERC3156FlashLender.sol1.43 KB
- src/interfaces/pool/IPool.sol1.63 KB
- src/interfaces/pool/commons/IPoolBorrowerActions.sol612 B
- src/interfaces/pool/commons/IPoolDerivedState.sol1.68 KB
- src/interfaces/pool/commons/IPoolErrors.sol5.97 KB
- src/interfaces/pool/commons/IPoolEvents.sol13.53 KB
- src/interfaces/pool/commons/IPoolImmutables.sol916 B
- src/interfaces/pool/commons/IPoolKickerActions.sol1.66 KB
- src/interfaces/pool/commons/IPoolLPActions.sol2.72 KB
- src/interfaces/pool/commons/IPoolLenderActions.sol3.7 KB
- src/interfaces/pool/commons/IPoolSettlerActions.sol823 B
- src/interfaces/pool/commons/IPoolState.sol17.21 KB
- src/interfaces/pool/commons/IPoolTakerActions.sol2.31 KB
- src/interfaces/pool/erc20/IERC20Pool.sol1.17 KB
- src/interfaces/pool/erc20/IERC20PoolBorrowerActions.sol2.23 KB
- src/interfaces/pool/erc20/IERC20PoolEvents.sol1.21 KB
- src/interfaces/pool/erc20/IERC20PoolImmutables.sol376 B
- src/interfaces/pool/erc20/IERC20PoolLenderActions.sol789 B
- src/interfaces/vault/ILidoWithdrawal.sol1.57 KB
- src/interfaces/vault/ISteth.sol607 B
- src/interfaces/vault/IWeth.sol193 B
- src/interfaces/vault/IWsteth.sol1.25 KB
- src/libraries/VaultLib.sol3.55 KB
src/LVLidoVault.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
import {IERC20} from "@balancer/solidity-utils/openzeppelin/IERC20.sol";
import {IERC20Pool} from "./interfaces/pool/erc20/IERC20Pool.sol";
import {IPoolInfoUtils} from "./interfaces/IPoolInfoUtils.sol";
import {ILVToken} from "./interfaces/ILVToken.sol";
import {ILiquidationProxy} from "./interfaces/ILiquidationProxy.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {VaultLib} from "./libraries/VaultLib.sol";
import {IWsteth} from "./interfaces/vault/IWsteth.sol";
import {IWeth} from "./interfaces/vault/IWeth.sol";
import {ISteth} from "./interfaces/vault/ISteth.sol";
import {IMorpho} from "./interfaces/IMorpho.sol";
import {IMorphoFlashLoanCallback} from "./interfaces/IMorphoCallbacks.sol";
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {UD60x18} from "@prb/math/UD60x18.sol";
import {IPoolDataProvider} from "./interfaces/IPoolDataProvider.sol";
/// @author Lendvest Labs
contract LVLidoVault is IMorphoFlashLoanCallback, Ownable {
ILVToken public testCollateralToken;
ILVToken public testQuoteToken;
IERC20Pool public pool;
ILiquidationProxy public liquidationProxy;
IMorpho public constant morpho = IMorpho(0xBBBBBbbBBb9cC5e90e3b3Af64bdAF62C37EEFFCb);
ISteth public constant steth = ISteth(VaultLib.STETH_ADDRESS);
IWsteth public constant wsteth = IWsteth(VaultLib.COLLATERAL_TOKEN);
IPoolInfoUtils public constant poolInfoUtils = IPoolInfoUtils(0x30c5eF2997d6a882DE52c4ec01B6D0a5e5B4fAAE);
IERC4626 public constant flagshipVault = IERC4626(0x38989BBA00BDF8181F4082995b3DEAe96163aC5D);
IPoolDataProvider public constant poolDataProvider = IPoolDataProvider(0x497a1994c46d4f6C864904A9f1fac6328Cb7C8a6);
// Circuit breaker for flash loan fees
uint256 public maxAcceptableFlashLoanFeeBps = 0; // 0 basis points = 0% fee (Morpho Blue standard)
uint256 public flashLoanFeeBps = 0; // 0 basis points = 0% fee (Morpho Blue standard)
address public LVLidoVaultUtil;
uint256 public totalBorrowAmount;
uint256 public totalLenderQTUnutilized;
uint256 public flagshipVaultShares;
uint256 public totalLenderQTUtilized;
uint256 public totalBorrowerCT;
uint256 public totalBorrowerCTUnutilized;
uint256 public totalCollateralLenderCT;
uint256 public totalCLDepositsUnutilized;
uint256 public totalCLDepositsUtilized;
uint256 public currentBucketIndex;
uint256 public epochStartRedemptionRate;
uint256 public currentRedemptionRate;
uint256 public collateralLenderTraunche = 0;
uint256 inverseBorrowCLAmount = 2;
uint256 public epoch = 0;
uint256 public epochStart;
uint256 public termDuration = 14 days;
uint256 public lastEpochEnd;
uint256 public constant epochCoolDownPeriod = 1 days;
uint256 public deploymentTimestamp;
uint256 public rate = 0;
int256 public constant priceDifferencethreshold = -1e16; // -1%
bool public epochStarted;
bool private _borrowInitiated;
bool public fundsQueued;
VaultLib.LenderOrder[] public lenderOrders;
VaultLib.BorrowerOrder[] public borrowerOrders;
VaultLib.CollateralLenderOrder[] public collateralLenderOrders;
mapping(uint256 => VaultLib.MatchInfo[]) public epochToMatches;
mapping(uint256 => VaultLib.CollateralLenderOrder[]) public epochToCollateralLenderOrders;
// mapping(uint256 => bytes) public epochToRatereceipt;
uint256 public requestId;
uint256 public totalManualRepay;
bool internal locked;
event RateUpdated(uint256 rate);
event FlashLoanFeeThresholdUpdated(uint256 oldThreshold, uint256 newThreshold);
event EpochMatchingSkipped(uint256 epoch, string reason);
/**
* @notice Constructor
* @param _pool The address of the Ajna Pool contract
* @param _liquidationProxy The address of the Liquidation Proxy contract
*/
constructor(address _pool, address _liquidationProxy) Ownable(msg.sender) {
pool = IERC20Pool(_pool);
liquidationProxy = ILiquidationProxy(_liquidationProxy);
testCollateralToken = ILVToken(pool.collateralAddress());
testQuoteToken = ILVToken(pool.quoteTokenAddress());
deploymentTimestamp = block.timestamp;
(,,,,, uint256 liquidityRate, uint256 variableBorrowRate,,,,,) = poolDataProvider.getReserveData(VaultLib.QUOTE_TOKEN);
rate = ((liquidityRate + variableBorrowRate) / 2);
}
receive() external payable {
if (msg.sender != address(VaultLib.LIDO_WITHDRAWAL) && msg.sender != VaultLib.QUOTE_TOKEN) {
revert VaultLib.Unauthorized();
}
emit VaultLib.FundsAdded(msg.value, address(this).balance, msg.sender);
}
fallback() external payable {
revert VaultLib.Unauthorized();
}
modifier lock() {
if (locked) revert VaultLib.ReentrantCall();
locked = true;
_;
locked = false;
}
modifier onlyProxy() {
if (msg.sender != LVLidoVaultUtil && msg.sender != address(liquidationProxy)) {
revert VaultLib.OnlyProxy();
}
_;
}
function maxFundsLimiter(uint256 quoteAmount, uint256 collateralAmount) public view returns (bool) {
uint256 wethPrice = 2430;
uint256 wstethPrice = (wethPrice * wsteth.stEthPerToken()) / 1e18;
// Fetch total existing lender amounts, also consider the value of the vault shares (in WETH)
uint256 totalQT =
quoteAmount + totalLenderQTUtilized + totalLenderQTUnutilized + flagshipVault.maxWithdraw(address(this));
// Fetch total existing borrower amounts (in WSTETH)
uint256 totalCT = collateralAmount + totalBorrowerCT + totalCLDepositsUtilized + totalCLDepositsUnutilized;
uint256 totalValue = ((totalQT * wethPrice) / 1e18) + ((totalCT * wstethPrice) / 1e18);
return totalValue <= 10000;
}
/**
* @notice Converts WETH to WSTETH through a series of token conversions
* @dev Restricted to Morpho vault and LVLidoVaultUtil contract only
* @dev Conversion flow:
* 1. WETH -> ETH (unwrap)
* 2. ETH -> stETH (stake with Lido)
* 3. stETH -> wstETH (wrap)
* @param amount Amount of WETH to convert
* @return uint256 Amount of WSTETH received after conversion
* @custom:security Only callable by authorized contracts
*/
function wethToWsteth(uint256 amount) public returns (uint256) {
// Validate caller authorization
if (msg.sender != address(morpho) && msg.sender != address(LVLidoVaultUtil)) {
revert VaultLib.Unauthorized();
}
// Step 1: Unwrap WETH to ETH
if (!IERC20(VaultLib.QUOTE_TOKEN).approve(address(VaultLib.QUOTE_TOKEN), amount)) {
revert VaultLib.TokenOperationFailed();
}
IWeth(VaultLib.QUOTE_TOKEN).withdraw(amount);
// Step 2: Stake ETH with Lido to receive stETH
uint256 shares = steth.submit{value: amount}(address(0));
uint256 stethReceived = steth.getPooledEthByShares(shares);
// Step 3: Wrap stETH to wstETH
if (!IERC20(address(steth)).approve(address(VaultLib.COLLATERAL_TOKEN), stethReceived)) {
revert VaultLib.TokenOperationFailed();
}
return wsteth.wrap(stethReceived);
}
/**
* @notice Handles the flash loan callback from Morpho Blue
* @dev This function is called by Morpho Blue after a flash loan is initiated
* @dev It performs the following steps:
* 1. Validates the caller and loan authorization
* 2. Mints collateral tokens for the pool
* 3. Draws debt from the Ajna pool
* 4. Converts borrowed WETH to wstETH to repay the flash loan
* @param assets The amount of assets received in the flash loan
* @param data Encoded data containing borrowing parameters
*/
function onMorphoFlashLoan(uint256 assets, bytes calldata data) external override {
// SECURITY: No `lock` modifier here - this callback is invoked DURING startEpoch()
// which already holds the lock. Using lock here would cause ReentrantCall error.
// Protection is provided by:
// 1. msg.sender check - only Morpho can call this
// 2. _borrowInitiated flag - only set by this contract in tryMatchOrders()
if (msg.sender != address(morpho) || !_borrowInitiated) revert VaultLib.Unauthorized();
_borrowInitiated = false;
// Decode the user data to get borrowing parameters
(uint256 baseLoanCollateral, uint256 amountToBorrow) = abi.decode(data, (uint256, uint256));
// Calculate total collateral (base + flash loan amount)
uint256 totalCollateral = baseLoanCollateral + assets;
emit VaultLib.LoanComposition(baseLoanCollateral, assets, totalCollateral, amountToBorrow);
// Mint test collateral tokens and approve them for the pool
if (
!testCollateralToken.mint(address(this), totalCollateral)
|| !testCollateralToken.approve(address(pool), totalCollateral)
) {
revert VaultLib.TokenOperationFailed();
}
// Record the borrowed amount for accounting purposes
totalBorrowAmount = amountToBorrow;
// Draw debt from the Ajna pool using the collateral
pool.drawDebt(address(this), amountToBorrow, currentBucketIndex, totalCollateral);
// Burn test quote tokens (accounting for the borrowed amount)
if (!testQuoteToken.burn(address(this), amountToBorrow)) {
revert VaultLib.TokenOperationFailed();
}
// Convert WETH to wstETH to repay the flash loan
uint256 wstethReceived = wethToWsteth(amountToBorrow);
// CRITICAL SAFETY CHECK: Verify we received enough wstETH to repay the flash loan
// If Morpho charges fees or conversion has slippage, we need to catch it here
// Note: Morpho Blue standard is 0% fees, but this protects against future changes
if (wstethReceived < assets) {
revert VaultLib.InsufficientFunds();
}
// Repay the flash loan - Morpho Blue requires approval
// Morpho will pull the tokens via transferFrom after this callback completes
IERC20 wstethToken = IERC20(VaultLib.COLLATERAL_TOKEN);
if (!wstethToken.approve(address(morpho), assets)) {
revert VaultLib.TokenOperationFailed();
}
}
/**
* @notice Matches pending lender, borrower, and collateral lender orders.
* @dev Creates loans by matching orders from the respective order books. Handles partial fulfillment by scaling
* orders. Utilizes 97.5% of lender funds for loans, reserving 2.5% for interest. Supports lender funds from
* direct deposits and flagship vault shares. Backs 50% of new debt with collateral lender deposits. Finally,
* it initiates a flash loan to provide leverage for borrowers.
*/
function tryMatchOrders() internal {
uint256 initialUtilization = 975e15; // 97.5%
uint256 originationFactor = poolInfoUtils.borrowFeeRate(address(pool));
uint256 depositFeeRate = poolInfoUtils.depositFeeRate(address(pool));
if (totalCollateralLenderCT == 0) {
revert VaultLib.InsufficientFunds();
}
uint256 totalPreFeeAmountToDeposit = 0;
uint256 borrowerCTMatched = 0;
uint256 borrowAmountMatched = 0;
uint256 totalSharesToRedeem = 0;
for ((uint256 i, uint256 j) = (0, 0); i < lenderOrders.length && j < borrowerOrders.length;) {
// Calculate borrower's debt requirements
uint256 flashLoanAmount = borrowerOrders[j].collateralAmount * (VaultLib.leverageFactor - 10);
uint256 amountToBorrow = (flashLoanAmount * epochStartRedemptionRate) / 1e19;
uint256 borrowFee = (amountToBorrow * originationFactor) / 1e18;
// Skip micro amounts from borrowers
if (borrowFee == 0) {
j++;
continue;
}
uint256 t0Debt = amountToBorrow + borrowFee;
uint256 maxLenderAmount = lenderOrders[i].quoteAmount;
// Check lenderOrder balances, using native amounts for further processing
if (lenderOrders[i].vaultShares > 0) {
maxLenderAmount = flagshipVault.previewRedeem(lenderOrders[i].vaultShares);
} else if (lenderOrders[i].quoteAmount > 0) {
maxLenderAmount = lenderOrders[i].quoteAmount;
} else {
i++;
continue;
}
// Skip micro amounts from lenders
uint256 maxLenderQuoteAmountFee = (maxLenderAmount * depositFeeRate) / 1e18;
if (maxLenderQuoteAmountFee == 0) {
i++;
continue;
}
uint256 maxT0Debt = (initialUtilization * (maxLenderAmount - maxLenderQuoteAmountFee)) / 1e18;
uint256 scaledT0Debt;
uint256 scaledAmountToBorrow;
uint256 scaledBorrowerCollateralAmount;
uint256 preFeeAmountToDeposit;
// Scale down values based on max lender deposit amount
if (t0Debt > maxT0Debt) {
// If borrower needs more than lender can provide, scale down the borrower's order
scaledT0Debt = maxT0Debt;
scaledAmountToBorrow = (scaledT0Debt * 1e18) / (1e18 + originationFactor);
uint256 scalingFactor = (scaledAmountToBorrow * 1e18) / amountToBorrow;
scaledBorrowerCollateralAmount = (borrowerOrders[j].collateralAmount * scalingFactor) / 1e18;
preFeeAmountToDeposit = maxLenderAmount;
// Skip lender if scaling causes 0 values
if (scaledBorrowerCollateralAmount == 0 || preFeeAmountToDeposit == 0) {
i++;
continue;
}
}
// Lender deposit is enough to support borrower order
else {
scaledT0Debt = t0Debt;
scaledAmountToBorrow = amountToBorrow;
scaledBorrowerCollateralAmount = borrowerOrders[j].collateralAmount;
preFeeAmountToDeposit = (scaledT0Debt * 1e36) / (initialUtilization * (1e18 - depositFeeRate));
}
// Amount set aside by lender for interest (with 97.5% initial utilization, 2.5% is set aside)
uint256 scaledReservedQuoteAmount =
((1e18 - initialUtilization) * ((scaledT0Debt * 1e18) / initialUtilization)) / 1e18;
// Create a match
epochToMatches[epoch].push(
VaultLib.MatchInfo({
lender: lenderOrders[i].lender,
borrower: borrowerOrders[j].borrower,
quoteAmount: scaledT0Debt, // 97.5% of the quote token amount
collateralAmount: scaledBorrowerCollateralAmount,
reservedQuoteAmount: scaledReservedQuoteAmount // 2.5% of the quote token amount
})
);
// Reduce available deposits for user
if (lenderOrders[i].quoteAmount == 0 && lenderOrders[i].vaultShares > 0) {
// Values were scaled down so we need to redeem less shares than available
if (maxLenderAmount > preFeeAmountToDeposit) {
// Scale down the shares to be used, preview doesn't matter here since we'll aggregate the Morpho withdrawals
uint256 scalingFactor = (preFeeAmountToDeposit * 1e18) / maxLenderAmount;
uint256 sharesToRedeem = (lenderOrders[i].vaultShares * scalingFactor) / 1e18;
totalSharesToRedeem += sharesToRedeem;
lenderOrders[i].vaultShares -= sharesToRedeem;
}
// Exact value used so we need to redeem exact shares
else {
totalSharesToRedeem += lenderOrders[i].vaultShares;
lenderOrders[i].vaultShares = 0;
}
} else {
lenderOrders[i].quoteAmount -= preFeeAmountToDeposit;
}
// Account for totals and adjust borrowerOrder
totalPreFeeAmountToDeposit += preFeeAmountToDeposit;
borrowerCTMatched += scaledBorrowerCollateralAmount;
borrowAmountMatched += scaledAmountToBorrow;
borrowerOrders[j].collateralAmount -= scaledBorrowerCollateralAmount;
// Remove used up lenderOrders
if (lenderOrders[i].quoteAmount == 0 && lenderOrders[i].vaultShares == 0) {
// Only do this when size is 2
if (lenderOrders.length > 2) {
// Move all the elements to the left
for (uint256 k = i; k < lenderOrders.length - 1; k++) {
lenderOrders[k] = lenderOrders[k + 1];
}
lenderOrders.pop();
} else if (lenderOrders.length > 0) {
lenderOrders[i] = lenderOrders[lenderOrders.length - 1];
lenderOrders.pop();
}
}
// Remove used up borrowerOrders
if (borrowerOrders[j].collateralAmount == 0) {
// Remove fully utilized borrower order
if (borrowerOrders.length > 2) {
// Move all the elements to the left
for (uint256 k = j; k < borrowerOrders.length - 1; k++) {
borrowerOrders[k] = borrowerOrders[k + 1];
}
borrowerOrders.pop();
} else if (borrowerOrders.length > 0) {
borrowerOrders[j] = borrowerOrders[borrowerOrders.length - 1];
borrowerOrders.pop();
}
}
}
// Ensure collateral lender deposits are sufficient before processing their orders
if (((borrowAmountMatched * 1e18) / epochStartRedemptionRate) / inverseBorrowCLAmount > totalCollateralLenderCT)
{
revert VaultLib.InsufficientFunds();
}
uint256 collateralLenderDepositsToMatch =
((borrowAmountMatched * 1e18) / epochStartRedemptionRate) / inverseBorrowCLAmount;
// Match collateral lender orders for the epoch
for (uint256 i = 0; i < collateralLenderOrders.length && collateralLenderDepositsToMatch > 0;) {
// Take as much as needed from each collateral lender
uint256 collateralUtilized = collateralLenderOrders[i].collateralAmount < collateralLenderDepositsToMatch
? collateralLenderOrders[i].collateralAmount
: collateralLenderDepositsToMatch;
collateralLenderDepositsToMatch -= collateralUtilized;
// Create collateralLenderOrder for the epoch
epochToCollateralLenderOrders[epoch].push(
VaultLib.CollateralLenderOrder({
collateralLender: collateralLenderOrders[i].collateralLender,
collateralAmount: collateralUtilized
})
);
// Remove or update the collateral lender order
if (collateralUtilized == collateralLenderOrders[i].collateralAmount) {
// Remove fully utilized order
for (uint256 k = i; k < collateralLenderOrders.length - 1; k++) {
collateralLenderOrders[k] = collateralLenderOrders[k + 1];
}
collateralLenderOrders.pop();
} else {
// Reduce partially utilized order
collateralLenderOrders[i].collateralAmount -= collateralUtilized;
}
}
// Adjust global collateral lender totals
// FIX: Track how much CL collateral was utilized in this epoch matching
// This amount backs 50% of the borrowed debt (inverseBorrowCLAmount = 2)
uint256 clUtilized = (((borrowAmountMatched * 1e18) / epochStartRedemptionRate) / inverseBorrowCLAmount);
totalCLDepositsUtilized += clUtilized;
// NOTE: totalCLDepositsUnutilized is managed by LVLidoVaultUtil.sol
// - It's set to 0 at epoch end (line 440 in LVLidoVaultUtil)
// - The primary source of truth is totalCollateralLenderCT (total deposits)
// - totalCLDepositsUtilized tracks per-epoch usage for accounting
// - totalCollateralLenderCT only decreases on user withdrawal, not on matching
// Withdraw Morpho shares
flagshipVaultShares -= totalSharesToRedeem;
uint256 maxAssets = flagshipVault.redeem(totalSharesToRedeem, address(this), address(this));
// Deposit lender utilized amounts
if (
!testQuoteToken.mint(address(this), totalPreFeeAmountToDeposit)
|| !IERC20(pool.quoteTokenAddress()).approve(address(pool), totalPreFeeAmountToDeposit)
) {
revert VaultLib.TokenOperationFailed();
}
(, uint256 totalPostFeeDepositAmount) =
pool.addQuoteToken(totalPreFeeAmountToDeposit, currentBucketIndex, block.timestamp + 3600);
// Note Accounting, lender fees deducted here
totalLenderQTUtilized += totalPostFeeDepositAmount;
totalLenderQTUnutilized -= totalPreFeeAmountToDeposit;
// Build params and execute flash loan
uint256 flashLoanAmount = (borrowerCTMatched * (VaultLib.leverageFactor - 10)) / 10;
// Lock flash loan
_borrowInitiated = true;
morpho.flashLoan(
VaultLib.COLLATERAL_TOKEN, // wstETH token address
flashLoanAmount, // flash loan amount
abi.encode(borrowerCTMatched, borrowAmountMatched)
);
totalBorrowerCTUnutilized -= borrowerCTMatched;
}
/**
* @notice Checks if flash loan conditions are acceptable for matching orders
* @dev Performs safety checks before committing to epoch matching
* @return bool True if safe to proceed with flash loan-based matching
*/
function isFlashLoanSafe() public view returns (bool) {
// Check 1: Max fee threshold (if Morpho adds fees, we need to know)
// Since we can't query Morpho fees directly, we rely on admin setting circuit breaker
// If maxAcceptableFlashLoanFeeBps > 0, admin has approved some fee tolerance
// If == 0 (default), we assume Morpho Blue's standard 0% fee model
// Check 2: Ensure we have borrower orders to match
if (borrowerOrders.length == 0) {
return false;
}
// Check 3: Ensure we have collateral lender deposits for backing
if (totalCollateralLenderCT == 0) {
return false;
}
// Check 4: Basic liquidity check
if (lenderOrders.length == 0) {
return false;
}
if (maxAcceptableFlashLoanFeeBps < flashLoanFeeBps){
return false;
}
return true;
}
/**
* @notice Starts a new epoch, matching orders and managing funds.
* @dev Validates epoch conditions, sets the redemption rate, and then calls `tryMatchOrders()` to match pending
* lender and borrower orders. Any remaining unutilized lender funds are deposited into the flagship vault, and
* the corresponding shares are distributed to the lenders.
* @dev SAFETY: If flash loan conditions are unsafe, epoch starts but NO MATCHING occurs (funds stay withdrawable)
*/
function startEpoch() external lock {
// Validate epoch parameters
if (
lastEpochEnd + epochCoolDownPeriod > block.timestamp || epochStarted
|| deploymentTimestamp + 2 hours > block.timestamp
) {
revert VaultLib.Unauthorized();
}
// Get current wstETH/stETH ratio and set rates
uint256 redemptionRate = wsteth.stEthPerToken();
epochStartRedemptionRate = redemptionRate;
currentRedemptionRate = redemptionRate;
currentBucketIndex = poolInfoUtils.priceToIndex(redemptionRate);
// Update the rate
(,,,,, uint256 liquidityRate, uint256 variableBorrowRate,,,,,) = poolDataProvider.getReserveData(VaultLib.QUOTE_TOKEN);
rate = ((liquidityRate + variableBorrowRate) / 2);
// Update state first
epoch++;
epochStarted = true;
collateralLenderTraunche = 0;
epochStart = block.timestamp;
// Emit events before external calls
emit VaultLib.EpochStarted(epoch, epochStart, epochStart + termDuration);
emit VaultLib.RedemptionRateUpdated(redemptionRate);
// SAFETY CHECK: Only match orders if flash loan conditions are safe
// If Morpho introduces fees or conditions are unsafe, skip matching
// This keeps all user funds in withdrawable state
if (isFlashLoanSafe()) {
// Perform external calls
tryMatchOrders();
} else {
// Emit event explaining why matching was skipped
emit EpochMatchingSkipped(epoch, "Flash loan conditions unsafe or insufficient liquidity");
// Note: Users can still withdraw their orders since no matching occurred
}
// Store amount to deposit in temporary variable
uint256 amountToDeposit = totalLenderQTUnutilized;
// Only deposit and update shares if there are unutilized funds
if (amountToDeposit > 0 && lenderOrders.length > 0) {
// Deposit remaining unutilized lender funds into flagship vault
if (!IERC20(VaultLib.QUOTE_TOKEN).approve(address(flagshipVault), amountToDeposit)) {
revert VaultLib.TokenOperationFailed();
}
uint256 depositedShares = flagshipVault.deposit(amountToDeposit, address(this));
flagshipVaultShares += depositedShares;
// Update lender shares after deposit using PRBMath
// Use depositedShares (new shares only) to ensure fair distribution and proper interest allocation
for (uint256 i = 0; i < lenderOrders.length; i++) {
UD60x18 lenderAmount = UD60x18.wrap(lenderOrders[i].quoteAmount);
UD60x18 newShares = UD60x18.wrap(depositedShares);
UD60x18 totalDeposit = UD60x18.wrap(amountToDeposit);
// Calculate shares: (lenderAmount * depositedShares) / totalDeposit
// This ensures each lender gets proportional shares from THIS deposit only
// Morpho interest accrues to the shares, benefiting only the lenders who hold them
UD60x18 shares = lenderAmount.mul(newShares).div(totalDeposit);
lenderOrders[i].vaultShares = UD60x18.unwrap(shares);
lenderOrders[i].quoteAmount = 0;
}
}
totalLenderQTUnutilized = 0;
}
// PROXY FUNCTIONS
/**
* @notice Pushes a lender order to the lenderOrders array.
* @dev Can only be called by the LVLidoVaultUtil or LiquidationProxy contract.
* @param lenderOrder The lender order to push.
*/
function lenderOrdersPush(VaultLib.LenderOrder memory lenderOrder) external onlyProxy {
lenderOrders.push(lenderOrder);
}
/**
* @notice Pushes a borrower order to the borrowerOrders array.
* @dev Can only be called by the LVLidoVaultUtil or LiquidationProxy contract.
* @param borrowerOrder The borrower order to push.
*/
function borrowerOrdersPush(VaultLib.BorrowerOrder memory borrowerOrder) external onlyProxy {
borrowerOrders.push(borrowerOrder);
}
/**
* @notice Pushes a collateral lender order to the collateralLenderOrders array.
* @dev Can only be called by the LVLidoVaultUtil or LiquidationProxy contract.
* @param collateralLenderOrder The collateral lender order to push.
*/
function collateralLenderOrdersPush(VaultLib.CollateralLenderOrder memory collateralLenderOrder)
external
onlyProxy
{
collateralLenderOrders.push(collateralLenderOrder);
}
/**
* @notice Pushes a match info to the epochToMatches mapping.
* @dev Can only be called by the LVLidoVaultUtil or LiquidationProxy contract.
* @param epoch The epoch number.
* @param matchInfo The match info to push.
*/
function epochToMatchesPush(uint256 epoch, VaultLib.MatchInfo memory matchInfo) external onlyProxy {
epochToMatches[epoch].push(matchInfo);
}
/**
* @notice Pushes a collateral lender order to the epochToCollateralLenderOrders mapping.
* @dev Can only be called by the LVLidoVaultUtil or LiquidationProxy contract.
* @param epoch The epoch number.
* @param collateralLenderOrder The collateral lender order to push.
*/
function epochToCollateralLenderOrdersPush(
uint256 epoch,
VaultLib.CollateralLenderOrder memory collateralLenderOrder
) external onlyProxy {
epochToCollateralLenderOrders[epoch].push(collateralLenderOrder);
}
/**
* @notice Deletes the matches for a given epoch.
* @dev Can only be called by the LVLidoVaultUtil or LiquidationProxy contract.
* @param epoch The epoch number.
*/
function deleteEpochMatches(uint256 epoch) external onlyProxy {
delete epochToMatches[epoch];
}
/**
* @notice Deletes the collateral lender orders for a given epoch.
* @dev Can only be called by the LVLidoVaultUtil or LiquidationProxy contract.
* @param epoch The epoch number.
*/
function deleteEpochCollateralLenderOrders(uint256 epoch) external onlyProxy {
delete epochToCollateralLenderOrders[epoch];
}
/**
* @notice Approves a token for the proxy contract.
* @dev Can only be called by the LVLidoVaultUtil or LiquidationProxy contract.
* @param token The address of the token to approve.
* @param receiver The address of the receiver.
* @param amount The amount to approve.
*/
function approveForProxy(address token, address receiver, uint256 amount) external onlyProxy returns (bool) {
return IERC20(token).approve(receiver, amount);
}
/**
* @notice Transfers a token on behalf of the proxy contract.
* @dev Can only be called by the LVLidoVaultUtil or LiquidationProxy contract.
* @param token The address of the token to transfer.
* @param recipient The address of the recipient.
* @param amount The amount to transfer.
*/
function transferForProxy(address token, address recipient, uint256 amount) external onlyProxy returns (bool) {
return IERC20(token).transfer(recipient, amount);
}
/**
* @notice Requests withdrawals for WstETH from Lido protocol
* @dev This function initiates the withdrawal process for wstETH tokens
* @dev Only callable by the proxy contract (LVLidoVaultUtil or LiquidationProxy)
* @dev Sets the global requestId to the first ID returned from the withdrawal request
* @dev Marks funds as queued in the Lido withdrawal queue
* @dev The withdrawal process in Lido is asynchronous - first request, then claim after finalization
* @param amounts Array of wstETH amounts to withdraw from Lido protocol
* @return requestId The ID of the first withdrawal request, used later for claiming
*/
function requestWithdrawalsWstETH(uint256[] memory amounts) external onlyProxy returns (uint256) {
uint256[] memory requestIds = VaultLib.LIDO_WITHDRAWAL.requestWithdrawalsWstETH(amounts, address(this));
requestId = requestIds[0];
fundsQueued = true;
return requestId;
}
/**
* @notice Claims a withdrawal from Lido protocol
* @dev Can only be called by the LVLidoVaultUtil or LiquidationProxy contract.
* @dev Uses the global requestId that was set during the requestWithdrawalsWstETH call
* @dev This function should only be called after the Lido withdrawal request has been finalized
* @dev After successful claim, the ETH will be sent to this contract's address
*/
function claimWithdrawal() external onlyProxy {
// Call Lido withdrawal contract to claim the finalized withdrawal using stored requestId
VaultLib.LIDO_WITHDRAWAL.claimWithdrawal(requestId);
// Note: After claiming, the contract will receive ETH which should be converted to WETH if needed
}
/**
* @notice Deposits ETH for WETH.
* @dev Can only be called by the LVLidoVaultUtil or LiquidationProxy contract.
* @param amount The amount of ETH to deposit.
*/
function depositEthForWeth(uint256 amount) external onlyProxy {
IWeth(VaultLib.QUOTE_TOKEN).deposit{value: amount}();
}
/**
* @notice Ends the current epoch.
* @dev Can only be called by the LVLidoVaultUtil or LiquidationProxy contract.
* @dev This function resets epoch state variables and prepares the vault for the next epoch.
*/
function end_epoch() external onlyProxy {
epochStarted = false;
fundsQueued = false; // Reset withdrawal queue status
lastEpochEnd = block.timestamp;
emit VaultLib.EndEpoch(lastEpochEnd);
}
/**
* @notice Clears Ajna deposits.
* @dev Can only be called by the LVLidoVaultUtil or LiquidationProxy contract.
* @param amount The amount of quote token to remove.
*/
function clearAjnaDeposits(uint256 amount) external onlyProxy lock {
(uint256 removedAmount_,) = pool.removeQuoteToken(amount, currentBucketIndex);
if (!testQuoteToken.burn(address(this), removedAmount_)) {
revert VaultLib.TokenOperationFailed();
}
}
/**
* @notice Sets the total manual repay amount.
* @dev Can only be called by the LVLidoVaultUtil or LiquidationProxy contract.
* @param amount The total manual repay amount.
*/
function setTotalManualRepay(uint256 amount) external onlyProxy {
totalManualRepay = amount;
}
/**
* @notice Adds collateral to avoid liquidation.
* @dev Can only be called by the LVLidoVaultUtil or LiquidationProxy contract.
* @dev Uses unutilized collateral lender deposits to increase position health.
* @param amount The amount of collateral to add.
*/
function avoidLiquidation(uint256 amount) external onlyProxy lock {
// Check if we have enough unutilized collateral from lenders
if (totalCLDepositsUnutilized < amount) revert VaultLib.InsufficientFunds();
// Update state first
totalCLDepositsUnutilized -= amount;
totalCLDepositsUtilized += amount;
// Emit event before external calls
emit VaultLib.AvoidLiquidation(amount);
// Perform external calls last
if (!testCollateralToken.mint(address(this), amount) || !testCollateralToken.approve(address(pool), amount)) {
revert VaultLib.TokenOperationFailed();
}
pool.drawDebt(address(this), 0, 7388, amount);
}
/**
* @notice Sets the LVLidoVaultUtil address.
* @dev Can only be called by the owner.
* @param _LVLidoVaultUtil The new LVLidoVaultUtil address.
*/
function setLVLidoVaultUtilAddress(address _LVLidoVaultUtil) public onlyOwner {
emit VaultLib.LVLidoVaultUtilAddressUpdated(LVLidoVaultUtil, _LVLidoVaultUtil);
LVLidoVaultUtil = _LVLidoVaultUtil;
}
/**
* @notice Sets the maximum acceptable flash loan fee threshold
* @dev CIRCUIT BREAKER: If Morpho Blue introduces flash loan fees, this protects the vault
* @dev Setting to 0 (default) means only 0% fee flash loans are acceptable (Morpho Blue standard)
* @dev If > 0, allows some fee tolerance but may make vault economics unprofitable
* @param _maxFeeBps Maximum fee in basis points (100 bps = 1%)
* @custom:security Owner should monitor Morpho fee changes and update accordingly
*/
function setMaxFlashLoanFeeThreshold(uint256 _maxFeeBps, uint256 _flashLoanFeeBps) external onlyOwner {
require(_maxFeeBps <= 1000, "Fee threshold too high"); // Max 10% as sanity check
require(_flashLoanFeeBps <= 1000, "Flash loan fee too high"); // Max 10% as sanity check
uint256 oldThreshold = maxAcceptableFlashLoanFeeBps;
maxAcceptableFlashLoanFeeBps = _maxFeeBps;
flashLoanFeeBps = _flashLoanFeeBps;
emit FlashLoanFeeThresholdUpdated(oldThreshold, _maxFeeBps);
}
// Note Anyone can call this function, ensure there are overflow protections in place.
// Define range of values that can be entered in.
/**
* @notice Repays Ajna debt.
* @param quoteTokenAmount The amount of quote token to repay.
* @dev This function allows anyone to repay debt on behalf of the vault
*/
function repayAjnaDebt(uint256 quoteTokenAmount) external lock {
// Prevent zero-value transactions to save gas
if (quoteTokenAmount == 0) {
revert VaultLib.InvalidInput();
}
// Update state first
totalManualRepay += quoteTokenAmount;
// Perform external calls last
if (
!IERC20(VaultLib.QUOTE_TOKEN).transferFrom(msg.sender, address(this), quoteTokenAmount)
|| !testQuoteToken.mint(address(this), quoteTokenAmount)
|| !IERC20(address(testQuoteToken)).approve(address(pool), quoteTokenAmount)
) {
revert VaultLib.TokenOperationFailed();
}
pool.repayDebt(address(this), quoteTokenAmount, 0, address(this), 7388);
}
/**
* @notice Gets the matches for a given epoch.
* @param _epoch The epoch number.
* @return An array of MatchInfo structs.
*/
function getEpochMatches(uint256 _epoch) external view returns (VaultLib.MatchInfo[] memory) {
return epochToMatches[_epoch];
}
/**
* @notice Gets the collateral lender orders for a given epoch.
* @param _epoch The epoch number.
* @return An array of CollateralLenderOrder structs.
*/
function getEpochCollateralLenderOrders(uint256 _epoch)
external
view
returns (VaultLib.CollateralLenderOrder[] memory)
{
return epochToCollateralLenderOrders[_epoch];
}
/**
* @notice Gets all lender orders.
* @return An array of LenderOrder structs.
*/
function getLenderOrders() external view returns (VaultLib.LenderOrder[] memory) {
return lenderOrders;
}
/**
* @notice Gets a specific lender order by index.
* @param index The index of the lender order.
* @return The LenderOrder struct at the specified index.
*/
function getLenderOrder(uint256 index) external view returns (VaultLib.LenderOrder memory) {
return lenderOrders[index];
}
/**
* @notice Gets the length of the lender orders array.
* @return The number of lender orders.
*/
function getLenderOrdersLength() external view returns (uint256) {
return lenderOrders.length;
}
/**
* @notice Gets all borrower orders.
* @return An array of BorrowerOrder structs.
*/
function getBorrowerOrders() external view returns (VaultLib.BorrowerOrder[] memory) {
return borrowerOrders;
}
/**
* @notice Gets a specific borrower order by index.
* @param index The index of the borrower order.
* @return The BorrowerOrder struct at the specified index.
*/
function getBorrowerOrder(uint256 index) external view returns (VaultLib.BorrowerOrder memory) {
return borrowerOrders[index];
}
/**
* @notice Gets the length of the borrower orders array.
* @return The number of borrower orders.
*/
function getBorrowerOrdersLength() external view returns (uint256) {
return borrowerOrders.length;
}
/**
* @notice Gets all collateral lender orders.
* @return An array of CollateralLenderOrder structs.
*/
function getCollateralLenderOrders() external view returns (VaultLib.CollateralLenderOrder[] memory) {
return collateralLenderOrders;
}
/**
* @notice Gets a specific collateral lender order by index.
* @param index The index of the collateral lender order.
* @return The CollateralLenderOrder struct at the specified index.
*/
function getCollateralLenderOrder(uint256 index) external view returns (VaultLib.CollateralLenderOrder memory) {
return collateralLenderOrders[index];
}
/**
* @notice Gets the length of the collateral lender orders array.
* @return The number of collateral lender orders.
*/
function getCollateralLenderOrdersLength() external view returns (uint256) {
return collateralLenderOrders.length;
}
/**
* @notice Gets the quote amount for a specific lender order by index.
* @param index The index of the lender order.
* @return The quote amount of the lender order.
*/
function getLenderOrderQuoteAmount(uint256 index) external view returns (uint256) {
return lenderOrders[index].quoteAmount;
}
/**
* @notice Gets all quote amounts from lender orders.
* @return An array of quote amounts.
*/
function getLenderOrderQuoteAmounts() external view returns (uint256[] memory) {
uint256[] memory amounts = new uint256[](lenderOrders.length);
for (uint256 i = 0; i < lenderOrders.length; i++) {
amounts[i] = lenderOrders[i].quoteAmount;
}
return amounts;
}
/**
* @notice Gets the vault shares for a specific lender order by index.
* @param index The index of the lender order.
* @return The vault shares of the lender order.
*/
function getLenderOrderVaultShares(uint256 index) external view returns (uint256) {
return lenderOrders[index].vaultShares;
}
/**
* @notice Gets all vault shares from lender orders.
* @return An array of vault shares.
*/
function getLenderOrderVaultSharesArray() external view returns (uint256[] memory) {
uint256[] memory shares = new uint256[](lenderOrders.length);
for (uint256 i = 0; i < lenderOrders.length; i++) {
shares[i] = lenderOrders[i].vaultShares;
}
return shares;
}
/**
* @notice Gets the collateral amount for a specific borrower order by index.
* @param index The index of the borrower order.
* @return The collateral amount of the borrower order.
*/
function getBorrowerOrderCollateralAmount(uint256 index) external view returns (uint256) {
return borrowerOrders[index].collateralAmount;
}
/**
* @notice Gets all collateral amounts from borrower orders.
* @return An array of collateral amounts.
*/
function getBorrowerOrderCollateralAmounts() external view returns (uint256[] memory) {
uint256[] memory amounts = new uint256[](borrowerOrders.length);
for (uint256 i = 0; i < borrowerOrders.length; i++) {
amounts[i] = borrowerOrders[i].collateralAmount;
}
return amounts;
}
/**
* @notice Gets the collateral amount for a specific collateral lender order by index.
* @param index The index of the collateral lender order.
* @return The collateral amount of the collateral lender order.
*/
function getCollateralLenderOrderAmount(uint256 index) external view returns (uint256) {
return collateralLenderOrders[index].collateralAmount;
}
/**
* @notice Gets all collateral amounts from collateral lender orders.
* @return An array of collateral amounts.
*/
function getCollateralLenderOrderAmounts() external view returns (uint256[] memory) {
uint256[] memory amounts = new uint256[](collateralLenderOrders.length);
for (uint256 i = 0; i < collateralLenderOrders.length; i++) {
amounts[i] = collateralLenderOrders[i].collateralAmount;
}
return amounts;
}
/**
* @notice Sets the total CL deposits unutilized.
* @dev Can only be called by the LVLidoVaultUtil or LiquidationProxy contract.
* @param _totalCLDepositsUnutilized The new total CL deposits unutilized.
*/
function setTotalCLDepositsUnutilized(uint256 _totalCLDepositsUnutilized) external onlyProxy {
totalCLDepositsUnutilized = _totalCLDepositsUnutilized;
}
/**
* @notice Sets the total CL deposits utilized.
* @dev Can only be called by the LVLidoVaultUtil or LiquidationProxy contract.
* @param _totalCLDepositsUtilized The new total CL deposits utilized.
*/
function setTotalCLDepositsUtilized(uint256 _totalCLDepositsUtilized) external onlyProxy {
totalCLDepositsUtilized = _totalCLDepositsUtilized;
}
/**
* @notice Sets the collateral lender traunche.
* @dev Can only be called by the LVLidoVaultUtil or LiquidationProxy contract.
* @param _collateralLenderTraunche The new collateral lender traunche.
*/
function setCollateralLenderTraunche(uint256 _collateralLenderTraunche) external onlyProxy {
collateralLenderTraunche = _collateralLenderTraunche;
}
/**
* @notice Sets the current redemption rate.
* @dev Can only be called by the LVLidoVaultUtil or LiquidationProxy contract.
* @param _currentRedemptionRate The new current redemption rate.
*/
function setCurrentRedemptionRate(uint256 _currentRedemptionRate) external onlyProxy {
currentRedemptionRate = _currentRedemptionRate;
}
/**
* @notice Mints tokens for the proxy contract.
* @dev Can only be called by the LVLidoVaultUtil or LiquidationProxy contract.
* @param token The address of the token to mint.
* @param receiver The address of the receiver.
* @param amount The amount to mint.
*/
function mintForProxy(address token, address receiver, uint256 amount) external onlyProxy returns (bool) {
if (token == address(testQuoteToken)) {
return testQuoteToken.mint(receiver, amount);
} else if (token == address(testCollateralToken)) {
return testCollateralToken.mint(receiver, amount);
}
}
/**
* @notice Burns tokens for the proxy contract.
* @dev Can only be called by the LVLidoVaultUtil or LiquidationProxy contract.
* @param token The address of the token to burn.
* @param receiver The address of the receiver.
* @param amount The amount to burn.
*/
function burnForProxy(address token, address receiver, uint256 amount) external onlyProxy returns (bool) {
if (token == address(testQuoteToken)) {
return testQuoteToken.burn(receiver, amount);
} else if (token == address(testCollateralToken)) {
return testCollateralToken.burn(receiver, amount);
}
}
/**
* @notice Repays debt for the proxy contract.
* @dev Can only be called by the LVLidoVaultUtil or LiquidationProxy contract.
* @param debt The amount of debt to repay.
* @param collateral The amount of collateral to repay.
*/
function repayDebtForProxy(uint256 debt, uint256 collateral) external onlyProxy {
pool.repayDebt(address(this), debt, collateral, address(this), 7388);
}
/**
* @notice Sets the total lender QT unutilized.
* @dev Can only be called by the LVLidoVaultUtil or LiquidationProxy contract.
* @param _totalLenderQTUnutilized The new total lender QT unutilized.
*/
function setTotalLenderQTUnutilized(uint256 _totalLenderQTUnutilized) external onlyProxy {
totalLenderQTUnutilized = _totalLenderQTUnutilized;
}
/**
* @notice Sets the total lender QT utilized.
* @dev Can only be called by the LVLidoVaultUtil or LiquidationProxy contract.
* @param _totalLenderQTUtilized The new total lender QT utilized.
*/
function setTotalLenderQTUtilized(uint256 _totalLenderQTUtilized) external onlyProxy {
totalLenderQTUtilized = _totalLenderQTUtilized;
}
/**
* @notice Sets the total borrower CT.
* @dev Can only be called by the LVLidoVaultUtil or LiquidationProxy contract.
* @param _totalBorrowerCT The new total borrower CT.
*/
function setTotalBorrowerCT(uint256 _totalBorrowerCT) external onlyProxy {
totalBorrowerCT = _totalBorrowerCT;
}
/**
* @notice Sets the total borrower CT unutilized.
* @dev Can only be called by the LVLidoVaultUtil or LiquidationProxy contract.
* @param _totalBorrowerCTUnutilized The new total borrower CT unutilized.
*/
function setTotalBorrowerCTUnutilized(uint256 _totalBorrowerCTUnutilized) external onlyProxy {
totalBorrowerCTUnutilized = _totalBorrowerCTUnutilized;
}
/**
* @notice Sets the total collateral lender CT.
* @dev Can only be called by the LVLidoVaultUtil or LiquidationProxy contract.
* @param _totalCollateralLenderCT The new total collateral lender CT.
*/
function setTotalCollateralLenderCT(uint256 _totalCollateralLenderCT) external onlyProxy {
totalCollateralLenderCT = _totalCollateralLenderCT;
}
// ORDER CREATION AND WITHDRAWAL FUNCTIONS
/**
* @notice Creates a lender order.
* @param amount The amount of quote token (WETH) to lend.
* @return The amount of quote token lent.
* @dev This function allows users to deposit quote tokens (WETH) into the vault
* @dev The deposited tokens are tracked as unutilized until they are matched with borrower orders
* @dev or deposited into the flagship vault during epoch start
*/
function createLenderOrder(uint256 amount) external lock returns (uint256) {
// Prevent zero-value transactions to save gas
if (amount == 0) revert VaultLib.InvalidInput();
// if (!maxFundsLimiter(amount, 0)) revert VaultLib.MaxFundsExceeded();
lenderOrders.push(VaultLib.LenderOrder({lender: msg.sender, quoteAmount: amount, vaultShares: 0}));
totalLenderQTUnutilized += amount;
emit VaultLib.LenderOrderAdded(msg.sender, amount);
if (!IERC20(VaultLib.QUOTE_TOKEN).transferFrom(address(msg.sender), address(this), amount)) {
revert VaultLib.TokenOperationFailed();
}
return amount;
}
/**
* @notice Creates a new borrower order with the specified collateral amount
* @dev Transfers collateral from the user to the vault and adds a new borrower order
* @param collateralAmount The amount of collateral to deposit for the order
* @return The amount of collateral deposited
*/
function createBorrowerOrder(uint256 collateralAmount) external lock returns (uint256) {
if (collateralAmount == 0) {
revert VaultLib.InvalidInput();
}
// if (!maxFundsLimiter(0, collateralAmount)) revert VaultLib.MaxFundsExceeded();
totalBorrowerCT += collateralAmount;
totalBorrowerCTUnutilized += collateralAmount;
borrowerOrders.push(VaultLib.BorrowerOrder({borrower: msg.sender, collateralAmount: collateralAmount}));
// Emit event before external call
emit VaultLib.BorrowerOrderAdded(msg.sender, collateralAmount);
// Perform external call last
if (!IERC20(VaultLib.COLLATERAL_TOKEN).transferFrom(msg.sender, address(this), collateralAmount)) {
revert VaultLib.TokenOperationFailed();
}
return collateralAmount;
}
/**
* @notice Lends collateral as a collateral lender.
* @param amount The amount of collateral to lend.
* @return The amount of collateral lent.
* @dev This function allows users to deposit collateral tokens (wstETH) to be used as additional
* @dev collateral for borrowers, helping to maintain healthy collateralization ratios and
* @dev potentially preventing liquidations. Collateral lenders earn fees from this service.
*/
function createCLOrder(uint256 amount) external lock returns (uint256) {
// Prevent zero-value transactions to save gas
if (amount == 0) {
revert VaultLib.InvalidInput();
}
// if (!maxFundsLimiter(0, amount)) revert VaultLib.MaxFundsExceeded();
totalCollateralLenderCT += amount;
collateralLenderOrders.push(VaultLib.CollateralLenderOrder(msg.sender, amount));
emit VaultLib.CollateralLenderDeposit(msg.sender, amount);
if (!IERC20(VaultLib.COLLATERAL_TOKEN).transferFrom(msg.sender, address(this), amount)) {
revert VaultLib.TokenOperationFailed();
}
return amount;
}
/**
* @notice Withdraws a lender order.
* @dev This function allows lenders to withdraw their unutilized funds from the vault.
* @dev Handles both direct quote token deposits and flagship vault shares.
* @dev Uses a swap-and-pop pattern to efficiently remove orders from the array.
* @return The total amount of quote tokens withdrawn.
*/
function withdrawLenderOrder() external lock returns (uint256) {
uint256 userWithdrawalAmount = 0;
uint256 userVaultShares = 0;
// Find and collect all orders from this lender
for (uint256 i = 0; i < lenderOrders.length;) {
if (lenderOrders[i].lender == msg.sender) {
// Track either vault shares or direct quote token amounts
if (lenderOrders[i].vaultShares > 0) {
userVaultShares += lenderOrders[i].vaultShares;
} else {
userWithdrawalAmount += lenderOrders[i].quoteAmount;
}
// Swap with last element and pop (more gas efficient than shifting elements)
if (i < lenderOrders.length - 1) {
lenderOrders[i] = lenderOrders[lenderOrders.length - 1];
}
lenderOrders.pop();
} else {
i++;
}
}
if (userWithdrawalAmount == 0 && userVaultShares == 0) {
revert VaultLib.NoUnfilledOrdersFound();
}
// Update all state variables first
totalLenderQTUnutilized -= userWithdrawalAmount;
// Handle flagship vault shares if present
if (userVaultShares > 0) {
flagshipVaultShares -= userVaultShares;
}
// Emit event before any external calls
emit VaultLib.WithdrawLender(msg.sender, userWithdrawalAmount);
// Perform external calls last
if (userVaultShares > 0) {
userWithdrawalAmount += flagshipVault.redeem(userVaultShares, address(this), address(this));
}
if (!IERC20(VaultLib.QUOTE_TOKEN).transfer(msg.sender, userWithdrawalAmount)) {
revert VaultLib.TokenOperationFailed();
}
return userWithdrawalAmount;
}
/**
* @notice Withdraws a borrower order.
* @dev This function allows borrowers to withdraw their unutilized collateral from pending orders
* @dev Uses a gas-efficient removal pattern (swap with last element and pop)
* @dev Updates global accounting for borrower collateral tracking
* @return The total amount of collateral tokens withdrawn.
*/
function withdrawBorrowerOrder() external lock returns (uint256) {
uint256 userWithdrawalAmount = 0;
for (uint256 i = 0; i < borrowerOrders.length;) {
if (borrowerOrders[i].borrower == msg.sender) {
userWithdrawalAmount += borrowerOrders[i].collateralAmount;
if (i < borrowerOrders.length - 1) {
borrowerOrders[i] = borrowerOrders[borrowerOrders.length - 1];
}
borrowerOrders.pop();
} else {
i++;
}
}
if (userWithdrawalAmount == 0) {
revert VaultLib.NoUnfilledOrdersFound();
}
totalBorrowerCT -= userWithdrawalAmount;
totalBorrowerCTUnutilized -= userWithdrawalAmount;
emit VaultLib.WithdrawBorrower(msg.sender, userWithdrawalAmount);
if (!IERC20(VaultLib.COLLATERAL_TOKEN).transfer(msg.sender, userWithdrawalAmount)) {
revert VaultLib.TokenOperationFailed();
}
return userWithdrawalAmount;
}
/**
* @notice Withdraws a collateral lender order.
* @dev Allows collateral lenders to withdraw their unutilized collateral tokens (wstETH)
* @dev Finds and aggregates all orders from the caller, then removes them from the array
* @dev Updates global accounting and transfers tokens back to the lender
* @dev Protected by the lock modifier to prevent reentrancy attacks
* @return The total amount of collateral withdrawn
*/
function withdrawCLOrder() external lock returns (uint256) {
uint256 userWithdrawalAmount = 0;
for (uint256 i = 0; i < collateralLenderOrders.length;) {
if (collateralLenderOrders[i].collateralLender == msg.sender) {
userWithdrawalAmount += collateralLenderOrders[i].collateralAmount;
if (i < collateralLenderOrders.length - 1) {
collateralLenderOrders[i] = collateralLenderOrders[collateralLenderOrders.length - 1];
}
collateralLenderOrders.pop();
} else {
i++;
}
}
if (userWithdrawalAmount == 0) {
revert VaultLib.NoUnfilledOrdersFound();
}
totalCollateralLenderCT -= userWithdrawalAmount;
emit VaultLib.WithdrawCollateralLender(msg.sender, userWithdrawalAmount);
if (!IERC20(VaultLib.COLLATERAL_TOKEN).transfer(msg.sender, userWithdrawalAmount)) {
revert VaultLib.TokenOperationFailed();
}
return userWithdrawalAmount;
}
// AUCTION BASED FUNCTIONS
/**
* @notice Sets whether kicking is allowed.
* @dev Can only be called by the LVLidoVaultUtil or LiquidationProxy contract.
* @param _allowKick Whether kicking is allowed.
*/
function setAllowKick(bool _allowKick) external onlyProxy {
liquidationProxy.setAllowKick(_allowKick);
}
function getAllowKick() external view returns (bool) {
return liquidationProxy.allowKick();
}
function lenderKick(uint256 bondAmount) external onlyProxy {
if (
!(
liquidationProxy.allowKick() == true && testQuoteToken.mint(address(this), bondAmount)
&& IERC20(address(testQuoteToken)).approve(address(pool), bondAmount)
)
) {
revert VaultLib.TokenOperationFailed();
}
pool.lenderKick(currentBucketIndex, 7388);
}
function withdrawBondsForProxy() external onlyProxy returns (uint256) {
(uint256 claimable, uint256 locked) = pool.kickerInfo(address(this));
if (locked != 0) {
revert VaultLib.LockedBonds();
}
return pool.withdrawBonds(address(this), claimable);
}
function updateRate(uint256 _rate) external onlyProxy {
if(_rate > 0) {
rate = _rate;
} else {
(,,,,, uint256 liquidityRate, uint256 variableBorrowRate,,,,,) = poolDataProvider.getReserveData(VaultLib.QUOTE_TOKEN);
rate = ((liquidityRate + variableBorrowRate) / 2);
}
emit RateUpdated(rate);
}
// @dev When we have proof hash of the rate, we can use this function to set the rate receipt
// function setRateReceipt(uint256 _epoch, bytes memory _rateReceipt) external {
// epochToRatereceipt[_epoch] = _rateReceipt;
// }
// function getRateReceipt(uint256 _epoch) external view returns (bytes memory) {
// return epochToRatereceipt[_epoch];
// }
}
lib/balancer-v2-monorepo/pkg/interfaces/contracts/solidity-utils/openzeppelin/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.9.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @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 `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, 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 `sender` to `recipient` 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 sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @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);
}
lib/openzeppelin-contracts/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC4626.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (interfaces/IERC4626.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";
/**
* @dev Interface of the ERC-4626 "Tokenized Vault Standard", as defined in
* https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
*/
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 redemption 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);
}
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
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 value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` 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 value) external returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
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);
}
lib/openzeppelin-contracts/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @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;
}
}
lib/prb-math/src/Common.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
// Common.sol
//
// Common mathematical functions used in both SD59x18 and UD60x18. Note that these global functions do not
// always operate with SD59x18 and UD60x18 numbers.
/*//////////////////////////////////////////////////////////////////////////
CUSTOM ERRORS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Thrown when the resultant value in {mulDiv} overflows uint256.
error PRBMath_MulDiv_Overflow(uint256 x, uint256 y, uint256 denominator);
/// @notice Thrown when the resultant value in {mulDiv18} overflows uint256.
error PRBMath_MulDiv18_Overflow(uint256 x, uint256 y);
/// @notice Thrown when one of the inputs passed to {mulDivSigned} is `type(int256).min`.
error PRBMath_MulDivSigned_InputTooSmall();
/// @notice Thrown when the resultant value in {mulDivSigned} overflows int256.
error PRBMath_MulDivSigned_Overflow(int256 x, int256 y);
/*//////////////////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////////////////*/
/// @dev The maximum value a uint128 number can have.
uint128 constant MAX_UINT128 = type(uint128).max;
/// @dev The maximum value a uint40 number can have.
uint40 constant MAX_UINT40 = type(uint40).max;
/// @dev The maximum value a uint64 number can have.
uint64 constant MAX_UINT64 = type(uint64).max;
/// @dev The unit number, which the decimal precision of the fixed-point types.
uint256 constant UNIT = 1e18;
/// @dev The unit number inverted mod 2^256.
uint256 constant UNIT_INVERSE = 78156646155174841979727994598816262306175212592076161876661_508869554232690281;
/// @dev The the largest power of two that divides the decimal value of `UNIT`. The logarithm of this value is the least significant
/// bit in the binary representation of `UNIT`.
uint256 constant UNIT_LPOTD = 262144;
/*//////////////////////////////////////////////////////////////////////////
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.
/// @custom:smtchecker abstract-function-nondet
function exp2(uint256 x) pure returns (uint256 result) {
unchecked {
// Start from 0.5 in the 192.64-bit fixed-point format.
result = 0x800000000000000000000000000000000000000000000000;
// The following logic multiplies the result by $\sqrt{2^{-i}}$ when the bit at position i is 1. Key points:
//
// 1. Intermediate results will not overflow, as the starting point is 2^191 and all magic factors are under 2^65.
// 2. The rationale for organizing the if statements into groups of 8 is gas savings. If the result of performing
// a bitwise AND operation between x and any value in the array [0x80; 0x40; 0x20; 0x10; 0x08; 0x04; 0x02; 0x01] is 1,
// we know that `x & 0xFF` is also 1.
if (x & 0xFF00000000000000 > 0) {
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 & 0xFF000000000000 > 0) {
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 & 0xFF0000000000 > 0) {
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 & 0xFF00000000 > 0) {
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 & 0xFF000000 > 0) {
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 & 0xFF0000 > 0) {
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 & 0xFF00 > 0) {
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 & 0xFF > 0) {
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;
}
}
// In the code snippet below, two operations are executed simultaneously:
//
// 1. The result is multiplied by $(2^n + 1)$, where $2^n$ represents the integer part, and the additional 1
// accounts for the initial guess of 0.5. This is achieved by subtracting from 191 instead of 192.
// 2. The result is then converted to an unsigned 60.18-decimal fixed-point format.
//
// The underlying logic is based on the relationship $2^{191-ip} = 2^{ip} / 2^{191}$, where $ip$ denotes the,
// integer part, $2^n$.
result *= UNIT;
result >>= (191 - (x >> 64));
}
}
/// @notice Finds the zero-based index of the first 1 in the binary representation of x.
///
/// @dev See the note on "msb" in this Wikipedia article: https://en.wikipedia.org/wiki/Find_first_set
///
/// Each step in this implementation is equivalent to this high-level code:
///
/// ```solidity
/// if (x >= 2 ** 128) {
/// x >>= 128;
/// result += 128;
/// }
/// ```
///
/// Where 128 is replaced with each respective power of two factor. See the full high-level implementation here:
/// https://gist.github.com/PaulRBerg/f932f8693f2733e30c4d479e8e980948
///
/// The Yul instructions used below are:
///
/// - "gt" is "greater than"
/// - "or" is the OR bitwise operator
/// - "shl" is "shift left"
/// - "shr" is "shift right"
///
/// @param x The uint256 number for which to find the index of the most significant bit.
/// @return result The index of the most significant bit as a uint256.
/// @custom:smtchecker abstract-function-nondet
function msb(uint256 x) pure returns (uint256 result) {
// 2^128
assembly ("memory-safe") {
let factor := shl(7, gt(x, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^64
assembly ("memory-safe") {
let factor := shl(6, gt(x, 0xFFFFFFFFFFFFFFFF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^32
assembly ("memory-safe") {
let factor := shl(5, gt(x, 0xFFFFFFFF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^16
assembly ("memory-safe") {
let factor := shl(4, gt(x, 0xFFFF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^8
assembly ("memory-safe") {
let factor := shl(3, gt(x, 0xFF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^4
assembly ("memory-safe") {
let factor := shl(2, gt(x, 0xF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^2
assembly ("memory-safe") {
let factor := shl(1, gt(x, 0x3))
x := shr(factor, x)
result := or(result, factor)
}
// 2^1
// No need to shift x any more.
assembly ("memory-safe") {
let factor := gt(x, 0x1)
result := or(result, factor)
}
}
/// @notice Calculates x*y÷denominator with 512-bit precision.
///
/// @dev Credits to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv.
///
/// Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - The denominator must not be zero.
/// - The result must fit in uint256.
///
/// @param x The multiplicand as a uint256.
/// @param y The multiplier as a uint256.
/// @param denominator The divisor as a uint256.
/// @return result The result as a uint256.
/// @custom:smtchecker abstract-function-nondet
function mulDiv(uint256 x, uint256 y, uint256 denominator) 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 ("memory-safe") {
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 {
return prod0 / denominator;
}
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (prod1 >= denominator) {
revert PRBMath_MulDiv_Overflow(x, y, denominator);
}
////////////////////////////////////////////////////////////////////////////
// 512 by 256 division
////////////////////////////////////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using the mulmod Yul instruction.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512-bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
unchecked {
// Calculate the largest power of two divisor of the denominator using the unary operator ~. This operation cannot overflow
// because the denominator cannot be zero at this point in the function execution. The result is always >= 1.
// For more detail, see https://cs.stackexchange.com/q/138556/92363.
uint256 lpotdod = denominator & (~denominator + 1);
uint256 flippedLpotdod;
assembly ("memory-safe") {
// Factor powers of two out of denominator.
denominator := div(denominator, lpotdod)
// Divide [prod1 prod0] by lpotdod.
prod0 := div(prod0, lpotdod)
// Get the flipped value `2^256 / lpotdod`. If the `lpotdod` is zero, the flipped value is one.
// `sub(0, lpotdod)` produces the two's complement version of `lpotdod`, which is equivalent to flipping all the bits.
// However, `div` interprets this value as an unsigned value: https://ethereum.stackexchange.com/q/147168/24693
flippedLpotdod := add(div(sub(0, lpotdod), lpotdod), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * flippedLpotdod;
// 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;
}
}
/// @notice Calculates x*y÷1e18 with 512-bit precision.
///
/// @dev A variant of {mulDiv} with constant folding, i.e. in which the denominator is hard coded to 1e18.
///
/// Notes:
/// - The body is purposely left uncommented; to understand how this works, see the documentation in {mulDiv}.
/// - The result is rounded toward zero.
/// - We take as an axiom that the result cannot be `MAX_UINT256` when x and y solve the following system of equations:
///
/// $$
/// \begin{cases}
/// x * y = MAX\_UINT256 * UNIT \\
/// (x * y) \% UNIT \geq \frac{UNIT}{2}
/// \end{cases}
/// $$
///
/// Requirements:
/// - Refer to the requirements in {mulDiv}.
/// - The result must fit in uint256.
///
/// @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.
/// @custom:smtchecker abstract-function-nondet
function mulDiv18(uint256 x, uint256 y) pure returns (uint256 result) {
uint256 prod0;
uint256 prod1;
assembly ("memory-safe") {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
if (prod1 == 0) {
unchecked {
return prod0 / UNIT;
}
}
if (prod1 >= UNIT) {
revert PRBMath_MulDiv18_Overflow(x, y);
}
uint256 remainder;
assembly ("memory-safe") {
remainder := mulmod(x, y, UNIT)
result :=
mul(
or(
div(sub(prod0, remainder), UNIT_LPOTD),
mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, UNIT_LPOTD), UNIT_LPOTD), 1))
),
UNIT_INVERSE
)
}
}
/// @notice Calculates x*y÷denominator with 512-bit precision.
///
/// @dev This is an extension of {mulDiv} for signed numbers, which works by computing the signs and the absolute values separately.
///
/// Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - Refer to the requirements in {mulDiv}.
/// - None of the inputs can be `type(int256).min`.
/// - The result must fit in 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.
/// @custom:smtchecker abstract-function-nondet
function mulDivSigned(int256 x, int256 y, int256 denominator) pure returns (int256 result) {
if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) {
revert PRBMath_MulDivSigned_InputTooSmall();
}
// Get hold of the absolute values of x, y and the denominator.
uint256 xAbs;
uint256 yAbs;
uint256 dAbs;
unchecked {
xAbs = x < 0 ? uint256(-x) : uint256(x);
yAbs = y < 0 ? uint256(-y) : uint256(y);
dAbs = denominator < 0 ? uint256(-denominator) : uint256(denominator);
}
// Compute the absolute value of x*y÷denominator. The result must fit in int256.
uint256 resultAbs = mulDiv(xAbs, yAbs, dAbs);
if (resultAbs > uint256(type(int256).max)) {
revert PRBMath_MulDivSigned_Overflow(x, y);
}
// Get the signs of x, y and the denominator.
uint256 sx;
uint256 sy;
uint256 sd;
assembly ("memory-safe") {
// "sgt" is the "signed greater than" assembly instruction and "sub(0,1)" is -1 in two's complement.
sx := sgt(x, sub(0, 1))
sy := sgt(y, sub(0, 1))
sd := sgt(denominator, sub(0, 1))
}
// XOR over sx, sy and sd. What this does is to check whether there are 1 or 3 negative signs in the inputs.
// If there are, the result should be negative. Otherwise, it should be positive.
unchecked {
result = sx ^ sy ^ sd == 0 ? -int256(resultAbs) : int256(resultAbs);
}
}
/// @notice Calculates the square root of x using the Babylonian method.
///
/// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Notes:
/// - If x is not a perfect square, the result is rounded down.
/// - Credits to OpenZeppelin for the explanations in comments below.
///
/// @param x The uint256 number for which to calculate the square root.
/// @return result The result as a uint256.
/// @custom:smtchecker abstract-function-nondet
function sqrt(uint256 x) pure returns (uint256 result) {
if (x == 0) {
return 0;
}
// For our first guess, we calculate the biggest power of 2 which is smaller than the square root of x.
//
// We know that the "msb" (most significant bit) of x is a power of 2 such that we have:
//
// $$
// msb(x) <= x <= 2*msb(x)$
// $$
//
// We write $msb(x)$ as $2^k$, and we get:
//
// $$
// k = log_2(x)
// $$
//
// Thus, we can write the initial inequality as:
//
// $$
// 2^{log_2(x)} <= x <= 2*2^{log_2(x)+1} \\
// sqrt(2^k) <= sqrt(x) < sqrt(2^{k+1}) \\
// 2^{k/2} <= sqrt(x) < 2^{(k+1)/2} <= 2^{(k/2)+1}
// $$
//
// Consequently, $2^{log_2(x) /2} is a good first approximation of sqrt(x) with at least one correct bit.
uint256 xAux = uint256(x);
result = 1;
if (xAux >= 2 ** 128) {
xAux >>= 128;
result <<= 64;
}
if (xAux >= 2 ** 64) {
xAux >>= 64;
result <<= 32;
}
if (xAux >= 2 ** 32) {
xAux >>= 32;
result <<= 16;
}
if (xAux >= 2 ** 16) {
xAux >>= 16;
result <<= 8;
}
if (xAux >= 2 ** 8) {
xAux >>= 8;
result <<= 4;
}
if (xAux >= 2 ** 4) {
xAux >>= 4;
result <<= 2;
}
if (xAux >= 2 ** 2) {
result <<= 1;
}
// At this point, `result` is an estimation with at least one bit of precision. We know the true value has at
// most 128 bits, 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 + 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;
// If x is not a perfect square, round the result toward zero.
uint256 roundedResult = x / result;
if (result >= roundedResult) {
result = roundedResult;
}
}
}
lib/prb-math/src/UD60x18.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
/*
██████╗ ██████╗ ██████╗ ███╗ ███╗ █████╗ ████████╗██╗ ██╗
██╔══██╗██╔══██╗██╔══██╗████╗ ████║██╔══██╗╚══██╔══╝██║ ██║
██████╔╝██████╔╝██████╔╝██╔████╔██║███████║ ██║ ███████║
██╔═══╝ ██╔══██╗██╔══██╗██║╚██╔╝██║██╔══██║ ██║ ██╔══██║
██║ ██║ ██║██████╔╝██║ ╚═╝ ██║██║ ██║ ██║ ██║ ██║
╚═╝ ╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝
██╗ ██╗██████╗ ██████╗ ██████╗ ██╗ ██╗ ██╗ █████╗
██║ ██║██╔══██╗██╔════╝ ██╔═████╗╚██╗██╔╝███║██╔══██╗
██║ ██║██║ ██║███████╗ ██║██╔██║ ╚███╔╝ ╚██║╚█████╔╝
██║ ██║██║ ██║██╔═══██╗████╔╝██║ ██╔██╗ ██║██╔══██╗
╚██████╔╝██████╔╝╚██████╔╝╚██████╔╝██╔╝ ██╗ ██║╚█████╔╝
╚═════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚════╝
*/
import "./ud60x18/Casting.sol";
import "./ud60x18/Constants.sol";
import "./ud60x18/Conversions.sol";
import "./ud60x18/Errors.sol";
import "./ud60x18/Helpers.sol";
import "./ud60x18/Math.sol";
import "./ud60x18/ValueType.sol";
lib/prb-math/src/sd1x18/Casting.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "../Common.sol" as Common;
import "./Errors.sol" as CastingErrors;
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { SD1x18 } from "./ValueType.sol";
/// @notice Casts an SD1x18 number into SD59x18.
/// @dev There is no overflow check because SD1x18 ⊆ SD59x18.
function intoSD59x18(SD1x18 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(int256(SD1x18.unwrap(x)));
}
/// @notice Casts an SD1x18 number into UD60x18.
/// @dev Requirements:
/// - x ≥ 0
function intoUD60x18(SD1x18 x) pure returns (UD60x18 result) {
int64 xInt = SD1x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD1x18_ToUD60x18_Underflow(x);
}
result = UD60x18.wrap(uint64(xInt));
}
/// @notice Casts an SD1x18 number into uint128.
/// @dev Requirements:
/// - x ≥ 0
function intoUint128(SD1x18 x) pure returns (uint128 result) {
int64 xInt = SD1x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD1x18_ToUint128_Underflow(x);
}
result = uint128(uint64(xInt));
}
/// @notice Casts an SD1x18 number into uint256.
/// @dev Requirements:
/// - x ≥ 0
function intoUint256(SD1x18 x) pure returns (uint256 result) {
int64 xInt = SD1x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD1x18_ToUint256_Underflow(x);
}
result = uint256(uint64(xInt));
}
/// @notice Casts an SD1x18 number into uint40.
/// @dev Requirements:
/// - x ≥ 0
/// - x ≤ MAX_UINT40
function intoUint40(SD1x18 x) pure returns (uint40 result) {
int64 xInt = SD1x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD1x18_ToUint40_Underflow(x);
}
if (xInt > int64(uint64(Common.MAX_UINT40))) {
revert CastingErrors.PRBMath_SD1x18_ToUint40_Overflow(x);
}
result = uint40(uint64(xInt));
}
/// @notice Alias for {wrap}.
function sd1x18(int64 x) pure returns (SD1x18 result) {
result = SD1x18.wrap(x);
}
/// @notice Unwraps an SD1x18 number into int64.
function unwrap(SD1x18 x) pure returns (int64 result) {
result = SD1x18.unwrap(x);
}
/// @notice Wraps an int64 number into SD1x18.
function wrap(int64 x) pure returns (SD1x18 result) {
result = SD1x18.wrap(x);
}
lib/prb-math/src/sd1x18/Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { SD1x18 } from "./ValueType.sol";
/// @dev Euler's number as an SD1x18 number.
SD1x18 constant E = SD1x18.wrap(2_718281828459045235);
/// @dev The maximum value an SD1x18 number can have.
int64 constant uMAX_SD1x18 = 9_223372036854775807;
SD1x18 constant MAX_SD1x18 = SD1x18.wrap(uMAX_SD1x18);
/// @dev The minimum value an SD1x18 number can have.
int64 constant uMIN_SD1x18 = -9_223372036854775808;
SD1x18 constant MIN_SD1x18 = SD1x18.wrap(uMIN_SD1x18);
/// @dev PI as an SD1x18 number.
SD1x18 constant PI = SD1x18.wrap(3_141592653589793238);
/// @dev The unit number, which gives the decimal precision of SD1x18.
SD1x18 constant UNIT = SD1x18.wrap(1e18);
int64 constant uUNIT = 1e18;
lib/prb-math/src/sd1x18/Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { SD1x18 } from "./ValueType.sol";
/// @notice Thrown when trying to cast an SD1x18 number that doesn't fit in UD60x18.
error PRBMath_SD1x18_ToUD60x18_Underflow(SD1x18 x);
/// @notice Thrown when trying to cast an SD1x18 number that doesn't fit in uint128.
error PRBMath_SD1x18_ToUint128_Underflow(SD1x18 x);
/// @notice Thrown when trying to cast an SD1x18 number that doesn't fit in uint256.
error PRBMath_SD1x18_ToUint256_Underflow(SD1x18 x);
/// @notice Thrown when trying to cast an SD1x18 number that doesn't fit in uint40.
error PRBMath_SD1x18_ToUint40_Overflow(SD1x18 x);
/// @notice Thrown when trying to cast an SD1x18 number that doesn't fit in uint40.
error PRBMath_SD1x18_ToUint40_Underflow(SD1x18 x);
lib/prb-math/src/sd1x18/ValueType.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Casting.sol" as Casting;
/// @notice The signed 1.18-decimal fixed-point number representation, which can have up to 1 digit and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type int64. This is useful when end users want to use int64 to save gas, e.g. with tight variable packing in contract
/// storage.
type SD1x18 is int64;
/*//////////////////////////////////////////////////////////////////////////
CASTING
//////////////////////////////////////////////////////////////////////////*/
using {
Casting.intoSD59x18,
Casting.intoUD60x18,
Casting.intoUint128,
Casting.intoUint256,
Casting.intoUint40,
Casting.unwrap
} for SD1x18 global;
lib/prb-math/src/sd21x18/Casting.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "../Common.sol" as Common;
import "./Errors.sol" as CastingErrors;
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { SD21x18 } from "./ValueType.sol";
/// @notice Casts an SD21x18 number into SD59x18.
/// @dev There is no overflow check because SD21x18 ⊆ SD59x18.
function intoSD59x18(SD21x18 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(int256(SD21x18.unwrap(x)));
}
/// @notice Casts an SD21x18 number into UD60x18.
/// @dev Requirements:
/// - x ≥ 0
function intoUD60x18(SD21x18 x) pure returns (UD60x18 result) {
int128 xInt = SD21x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD21x18_ToUD60x18_Underflow(x);
}
result = UD60x18.wrap(uint128(xInt));
}
/// @notice Casts an SD21x18 number into uint128.
/// @dev Requirements:
/// - x ≥ 0
function intoUint128(SD21x18 x) pure returns (uint128 result) {
int128 xInt = SD21x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD21x18_ToUint128_Underflow(x);
}
result = uint128(xInt);
}
/// @notice Casts an SD21x18 number into uint256.
/// @dev Requirements:
/// - x ≥ 0
function intoUint256(SD21x18 x) pure returns (uint256 result) {
int128 xInt = SD21x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD21x18_ToUint256_Underflow(x);
}
result = uint256(uint128(xInt));
}
/// @notice Casts an SD21x18 number into uint40.
/// @dev Requirements:
/// - x ≥ 0
/// - x ≤ MAX_UINT40
function intoUint40(SD21x18 x) pure returns (uint40 result) {
int128 xInt = SD21x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD21x18_ToUint40_Underflow(x);
}
if (xInt > int128(uint128(Common.MAX_UINT40))) {
revert CastingErrors.PRBMath_SD21x18_ToUint40_Overflow(x);
}
result = uint40(uint128(xInt));
}
/// @notice Alias for {wrap}.
function sd21x18(int128 x) pure returns (SD21x18 result) {
result = SD21x18.wrap(x);
}
/// @notice Unwraps an SD21x18 number into int128.
function unwrap(SD21x18 x) pure returns (int128 result) {
result = SD21x18.unwrap(x);
}
/// @notice Wraps an int128 number into SD21x18.
function wrap(int128 x) pure returns (SD21x18 result) {
result = SD21x18.wrap(x);
}
lib/prb-math/src/sd21x18/Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { SD21x18 } from "./ValueType.sol";
/// @dev Euler's number as an SD21x18 number.
SD21x18 constant E = SD21x18.wrap(2_718281828459045235);
/// @dev The maximum value an SD21x18 number can have.
int128 constant uMAX_SD21x18 = 170141183460469231731_687303715884105727;
SD21x18 constant MAX_SD21x18 = SD21x18.wrap(uMAX_SD21x18);
/// @dev The minimum value an SD21x18 number can have.
int128 constant uMIN_SD21x18 = -170141183460469231731_687303715884105728;
SD21x18 constant MIN_SD21x18 = SD21x18.wrap(uMIN_SD21x18);
/// @dev PI as an SD21x18 number.
SD21x18 constant PI = SD21x18.wrap(3_141592653589793238);
/// @dev The unit number, which gives the decimal precision of SD21x18.
SD21x18 constant UNIT = SD21x18.wrap(1e18);
int128 constant uUNIT = 1e18;
lib/prb-math/src/sd21x18/Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { SD21x18 } from "./ValueType.sol";
/// @notice Thrown when trying to cast an SD21x18 number that doesn't fit in uint128.
error PRBMath_SD21x18_ToUint128_Underflow(SD21x18 x);
/// @notice Thrown when trying to cast an SD21x18 number that doesn't fit in UD60x18.
error PRBMath_SD21x18_ToUD60x18_Underflow(SD21x18 x);
/// @notice Thrown when trying to cast an SD21x18 number that doesn't fit in uint256.
error PRBMath_SD21x18_ToUint256_Underflow(SD21x18 x);
/// @notice Thrown when trying to cast an SD21x18 number that doesn't fit in uint40.
error PRBMath_SD21x18_ToUint40_Overflow(SD21x18 x);
/// @notice Thrown when trying to cast an SD21x18 number that doesn't fit in uint40.
error PRBMath_SD21x18_ToUint40_Underflow(SD21x18 x);
lib/prb-math/src/sd21x18/ValueType.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Casting.sol" as Casting;
/// @notice The signed 21.18-decimal fixed-point number representation, which can have up to 21 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type int128. This is useful when end users want to use int128 to save gas, e.g. with tight variable packing in contract
/// storage.
type SD21x18 is int128;
/*//////////////////////////////////////////////////////////////////////////
CASTING
//////////////////////////////////////////////////////////////////////////*/
using {
Casting.intoSD59x18,
Casting.intoUD60x18,
Casting.intoUint128,
Casting.intoUint256,
Casting.intoUint40,
Casting.unwrap
} for SD21x18 global;
lib/prb-math/src/sd59x18/Casting.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Errors.sol" as CastingErrors;
import { MAX_UINT128, MAX_UINT40 } from "../Common.sol";
import { uMAX_SD1x18, uMIN_SD1x18 } from "../sd1x18/Constants.sol";
import { SD1x18 } from "../sd1x18/ValueType.sol";
import { uMAX_SD21x18, uMIN_SD21x18 } from "../sd21x18/Constants.sol";
import { SD21x18 } from "../sd21x18/ValueType.sol";
import { uMAX_UD2x18 } from "../ud2x18/Constants.sol";
import { UD2x18 } from "../ud2x18/ValueType.sol";
import { uMAX_UD21x18 } from "../ud21x18/Constants.sol";
import { UD21x18 } from "../ud21x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { SD59x18 } from "./ValueType.sol";
/// @notice Casts an SD59x18 number into int256.
/// @dev This is basically a functional alias for {unwrap}.
function intoInt256(SD59x18 x) pure returns (int256 result) {
result = SD59x18.unwrap(x);
}
/// @notice Casts an SD59x18 number into SD1x18.
/// @dev Requirements:
/// - x ≥ uMIN_SD1x18
/// - x ≤ uMAX_SD1x18
function intoSD1x18(SD59x18 x) pure returns (SD1x18 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < uMIN_SD1x18) {
revert CastingErrors.PRBMath_SD59x18_IntoSD1x18_Underflow(x);
}
if (xInt > uMAX_SD1x18) {
revert CastingErrors.PRBMath_SD59x18_IntoSD1x18_Overflow(x);
}
result = SD1x18.wrap(int64(xInt));
}
/// @notice Casts an SD59x18 number into SD21x18.
/// @dev Requirements:
/// - x ≥ uMIN_SD21x18
/// - x ≤ uMAX_SD21x18
function intoSD21x18(SD59x18 x) pure returns (SD21x18 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < uMIN_SD21x18) {
revert CastingErrors.PRBMath_SD59x18_IntoSD21x18_Underflow(x);
}
if (xInt > uMAX_SD21x18) {
revert CastingErrors.PRBMath_SD59x18_IntoSD21x18_Overflow(x);
}
result = SD21x18.wrap(int128(xInt));
}
/// @notice Casts an SD59x18 number into UD2x18.
/// @dev Requirements:
/// - x ≥ 0
/// - x ≤ uMAX_UD2x18
function intoUD2x18(SD59x18 x) pure returns (UD2x18 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD59x18_IntoUD2x18_Underflow(x);
}
if (xInt > int256(uint256(uMAX_UD2x18))) {
revert CastingErrors.PRBMath_SD59x18_IntoUD2x18_Overflow(x);
}
result = UD2x18.wrap(uint64(uint256(xInt)));
}
/// @notice Casts an SD59x18 number into UD21x18.
/// @dev Requirements:
/// - x ≥ 0
/// - x ≤ uMAX_UD21x18
function intoUD21x18(SD59x18 x) pure returns (UD21x18 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD59x18_IntoUD21x18_Underflow(x);
}
if (xInt > int256(uint256(uMAX_UD21x18))) {
revert CastingErrors.PRBMath_SD59x18_IntoUD21x18_Overflow(x);
}
result = UD21x18.wrap(uint128(uint256(xInt)));
}
/// @notice Casts an SD59x18 number into UD60x18.
/// @dev Requirements:
/// - x ≥ 0
function intoUD60x18(SD59x18 x) pure returns (UD60x18 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD59x18_IntoUD60x18_Underflow(x);
}
result = UD60x18.wrap(uint256(xInt));
}
/// @notice Casts an SD59x18 number into uint256.
/// @dev Requirements:
/// - x ≥ 0
function intoUint256(SD59x18 x) pure returns (uint256 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD59x18_IntoUint256_Underflow(x);
}
result = uint256(xInt);
}
/// @notice Casts an SD59x18 number into uint128.
/// @dev Requirements:
/// - x ≥ 0
/// - x ≤ uMAX_UINT128
function intoUint128(SD59x18 x) pure returns (uint128 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD59x18_IntoUint128_Underflow(x);
}
if (xInt > int256(uint256(MAX_UINT128))) {
revert CastingErrors.PRBMath_SD59x18_IntoUint128_Overflow(x);
}
result = uint128(uint256(xInt));
}
/// @notice Casts an SD59x18 number into uint40.
/// @dev Requirements:
/// - x ≥ 0
/// - x ≤ MAX_UINT40
function intoUint40(SD59x18 x) pure returns (uint40 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD59x18_IntoUint40_Underflow(x);
}
if (xInt > int256(uint256(MAX_UINT40))) {
revert CastingErrors.PRBMath_SD59x18_IntoUint40_Overflow(x);
}
result = uint40(uint256(xInt));
}
/// @notice Alias for {wrap}.
function sd(int256 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(x);
}
/// @notice Alias for {wrap}.
function sd59x18(int256 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(x);
}
/// @notice Unwraps an SD59x18 number into int256.
function unwrap(SD59x18 x) pure returns (int256 result) {
result = SD59x18.unwrap(x);
}
/// @notice Wraps an int256 number into SD59x18.
function wrap(int256 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(x);
}
lib/prb-math/src/sd59x18/Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { SD59x18 } from "./ValueType.sol";
// NOTICE: the "u" prefix stands for "unwrapped".
/// @dev Euler's number as an SD59x18 number.
SD59x18 constant E = SD59x18.wrap(2_718281828459045235);
/// @dev The maximum input permitted in {exp}.
int256 constant uEXP_MAX_INPUT = 133_084258667509499440;
SD59x18 constant EXP_MAX_INPUT = SD59x18.wrap(uEXP_MAX_INPUT);
/// @dev Any value less than this returns 0 in {exp}.
int256 constant uEXP_MIN_THRESHOLD = -41_446531673892822322;
SD59x18 constant EXP_MIN_THRESHOLD = SD59x18.wrap(uEXP_MIN_THRESHOLD);
/// @dev The maximum input permitted in {exp2}.
int256 constant uEXP2_MAX_INPUT = 192e18 - 1;
SD59x18 constant EXP2_MAX_INPUT = SD59x18.wrap(uEXP2_MAX_INPUT);
/// @dev Any value less than this returns 0 in {exp2}.
int256 constant uEXP2_MIN_THRESHOLD = -59_794705707972522261;
SD59x18 constant EXP2_MIN_THRESHOLD = SD59x18.wrap(uEXP2_MIN_THRESHOLD);
/// @dev Half the UNIT number.
int256 constant uHALF_UNIT = 0.5e18;
SD59x18 constant HALF_UNIT = SD59x18.wrap(uHALF_UNIT);
/// @dev $log_2(10)$ as an SD59x18 number.
int256 constant uLOG2_10 = 3_321928094887362347;
SD59x18 constant LOG2_10 = SD59x18.wrap(uLOG2_10);
/// @dev $log_2(e)$ as an SD59x18 number.
int256 constant uLOG2_E = 1_442695040888963407;
SD59x18 constant LOG2_E = SD59x18.wrap(uLOG2_E);
/// @dev The maximum value an SD59x18 number can have.
int256 constant uMAX_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_792003956564819967;
SD59x18 constant MAX_SD59x18 = SD59x18.wrap(uMAX_SD59x18);
/// @dev The maximum whole value an SD59x18 number can have.
int256 constant uMAX_WHOLE_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_000000000000000000;
SD59x18 constant MAX_WHOLE_SD59x18 = SD59x18.wrap(uMAX_WHOLE_SD59x18);
/// @dev The minimum value an SD59x18 number can have.
int256 constant uMIN_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_792003956564819968;
SD59x18 constant MIN_SD59x18 = SD59x18.wrap(uMIN_SD59x18);
/// @dev The minimum whole value an SD59x18 number can have.
int256 constant uMIN_WHOLE_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_000000000000000000;
SD59x18 constant MIN_WHOLE_SD59x18 = SD59x18.wrap(uMIN_WHOLE_SD59x18);
/// @dev PI as an SD59x18 number.
SD59x18 constant PI = SD59x18.wrap(3_141592653589793238);
/// @dev The unit number, which gives the decimal precision of SD59x18.
int256 constant uUNIT = 1e18;
SD59x18 constant UNIT = SD59x18.wrap(1e18);
/// @dev The unit number squared.
int256 constant uUNIT_SQUARED = 1e36;
SD59x18 constant UNIT_SQUARED = SD59x18.wrap(uUNIT_SQUARED);
/// @dev Zero as an SD59x18 number.
SD59x18 constant ZERO = SD59x18.wrap(0);
lib/prb-math/src/sd59x18/Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { SD59x18 } from "./ValueType.sol";
/// @notice Thrown when taking the absolute value of `MIN_SD59x18`.
error PRBMath_SD59x18_Abs_MinSD59x18();
/// @notice Thrown when ceiling a number overflows SD59x18.
error PRBMath_SD59x18_Ceil_Overflow(SD59x18 x);
/// @notice Thrown when converting a basic integer to the fixed-point format overflows SD59x18.
error PRBMath_SD59x18_Convert_Overflow(int256 x);
/// @notice Thrown when converting a basic integer to the fixed-point format underflows SD59x18.
error PRBMath_SD59x18_Convert_Underflow(int256 x);
/// @notice Thrown when dividing two numbers and one of them is `MIN_SD59x18`.
error PRBMath_SD59x18_Div_InputTooSmall();
/// @notice Thrown when dividing two numbers and one of the intermediary unsigned results overflows SD59x18.
error PRBMath_SD59x18_Div_Overflow(SD59x18 x, SD59x18 y);
/// @notice Thrown when taking the natural exponent of a base greater than 133_084258667509499441.
error PRBMath_SD59x18_Exp_InputTooBig(SD59x18 x);
/// @notice Thrown when taking the binary exponent of a base greater than 192e18.
error PRBMath_SD59x18_Exp2_InputTooBig(SD59x18 x);
/// @notice Thrown when flooring a number underflows SD59x18.
error PRBMath_SD59x18_Floor_Underflow(SD59x18 x);
/// @notice Thrown when taking the geometric mean of two numbers and their product is negative.
error PRBMath_SD59x18_Gm_NegativeProduct(SD59x18 x, SD59x18 y);
/// @notice Thrown when taking the geometric mean of two numbers and multiplying them overflows SD59x18.
error PRBMath_SD59x18_Gm_Overflow(SD59x18 x, SD59x18 y);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in SD1x18.
error PRBMath_SD59x18_IntoSD1x18_Overflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in SD1x18.
error PRBMath_SD59x18_IntoSD1x18_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in SD21x18.
error PRBMath_SD59x18_IntoSD21x18_Overflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in SD21x18.
error PRBMath_SD59x18_IntoSD21x18_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in UD2x18.
error PRBMath_SD59x18_IntoUD2x18_Overflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in UD2x18.
error PRBMath_SD59x18_IntoUD2x18_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in UD21x18.
error PRBMath_SD59x18_IntoUD21x18_Overflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in UD21x18.
error PRBMath_SD59x18_IntoUD21x18_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in UD60x18.
error PRBMath_SD59x18_IntoUD60x18_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in uint128.
error PRBMath_SD59x18_IntoUint128_Overflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in uint128.
error PRBMath_SD59x18_IntoUint128_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in uint256.
error PRBMath_SD59x18_IntoUint256_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in uint40.
error PRBMath_SD59x18_IntoUint40_Overflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in uint40.
error PRBMath_SD59x18_IntoUint40_Underflow(SD59x18 x);
/// @notice Thrown when taking the logarithm of a number less than or equal to zero.
error PRBMath_SD59x18_Log_InputTooSmall(SD59x18 x);
/// @notice Thrown when multiplying two numbers and one of the inputs is `MIN_SD59x18`.
error PRBMath_SD59x18_Mul_InputTooSmall();
/// @notice Thrown when multiplying two numbers and the intermediary absolute result overflows SD59x18.
error PRBMath_SD59x18_Mul_Overflow(SD59x18 x, SD59x18 y);
/// @notice Thrown when raising a number to a power and the intermediary absolute result overflows SD59x18.
error PRBMath_SD59x18_Powu_Overflow(SD59x18 x, uint256 y);
/// @notice Thrown when taking the square root of a negative number.
error PRBMath_SD59x18_Sqrt_NegativeInput(SD59x18 x);
/// @notice Thrown when the calculating the square root overflows SD59x18.
error PRBMath_SD59x18_Sqrt_Overflow(SD59x18 x);
lib/prb-math/src/sd59x18/Helpers.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { wrap } from "./Casting.sol";
import { SD59x18 } from "./ValueType.sol";
/// @notice Implements the checked addition operation (+) in the SD59x18 type.
function add(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
return wrap(x.unwrap() + y.unwrap());
}
/// @notice Implements the AND (&) bitwise operation in the SD59x18 type.
function and(SD59x18 x, int256 bits) pure returns (SD59x18 result) {
return wrap(x.unwrap() & bits);
}
/// @notice Implements the AND (&) bitwise operation in the SD59x18 type.
function and2(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
return wrap(x.unwrap() & y.unwrap());
}
/// @notice Implements the equal (=) operation in the SD59x18 type.
function eq(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = x.unwrap() == y.unwrap();
}
/// @notice Implements the greater than operation (>) in the SD59x18 type.
function gt(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = x.unwrap() > y.unwrap();
}
/// @notice Implements the greater than or equal to operation (>=) in the SD59x18 type.
function gte(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = x.unwrap() >= y.unwrap();
}
/// @notice Implements a zero comparison check function in the SD59x18 type.
function isZero(SD59x18 x) pure returns (bool result) {
result = x.unwrap() == 0;
}
/// @notice Implements the left shift operation (<<) in the SD59x18 type.
function lshift(SD59x18 x, uint256 bits) pure returns (SD59x18 result) {
result = wrap(x.unwrap() << bits);
}
/// @notice Implements the lower than operation (<) in the SD59x18 type.
function lt(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = x.unwrap() < y.unwrap();
}
/// @notice Implements the lower than or equal to operation (<=) in the SD59x18 type.
function lte(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = x.unwrap() <= y.unwrap();
}
/// @notice Implements the unchecked modulo operation (%) in the SD59x18 type.
function mod(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
result = wrap(x.unwrap() % y.unwrap());
}
/// @notice Implements the not equal operation (!=) in the SD59x18 type.
function neq(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = x.unwrap() != y.unwrap();
}
/// @notice Implements the NOT (~) bitwise operation in the SD59x18 type.
function not(SD59x18 x) pure returns (SD59x18 result) {
result = wrap(~x.unwrap());
}
/// @notice Implements the OR (|) bitwise operation in the SD59x18 type.
function or(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
result = wrap(x.unwrap() | y.unwrap());
}
/// @notice Implements the right shift operation (>>) in the SD59x18 type.
function rshift(SD59x18 x, uint256 bits) pure returns (SD59x18 result) {
result = wrap(x.unwrap() >> bits);
}
/// @notice Implements the checked subtraction operation (-) in the SD59x18 type.
function sub(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
result = wrap(x.unwrap() - y.unwrap());
}
/// @notice Implements the checked unary minus operation (-) in the SD59x18 type.
function unary(SD59x18 x) pure returns (SD59x18 result) {
result = wrap(-x.unwrap());
}
/// @notice Implements the unchecked addition operation (+) in the SD59x18 type.
function uncheckedAdd(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
unchecked {
result = wrap(x.unwrap() + y.unwrap());
}
}
/// @notice Implements the unchecked subtraction operation (-) in the SD59x18 type.
function uncheckedSub(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
unchecked {
result = wrap(x.unwrap() - y.unwrap());
}
}
/// @notice Implements the unchecked unary minus operation (-) in the SD59x18 type.
function uncheckedUnary(SD59x18 x) pure returns (SD59x18 result) {
unchecked {
result = wrap(-x.unwrap());
}
}
/// @notice Implements the XOR (^) bitwise operation in the SD59x18 type.
function xor(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
result = wrap(x.unwrap() ^ y.unwrap());
}
lib/prb-math/src/sd59x18/Math.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "../Common.sol" as Common;
import "./Errors.sol" as Errors;
import {
uEXP_MAX_INPUT,
uEXP2_MAX_INPUT,
uEXP_MIN_THRESHOLD,
uEXP2_MIN_THRESHOLD,
uHALF_UNIT,
uLOG2_10,
uLOG2_E,
uMAX_SD59x18,
uMAX_WHOLE_SD59x18,
uMIN_SD59x18,
uMIN_WHOLE_SD59x18,
UNIT,
uUNIT,
uUNIT_SQUARED,
ZERO
} from "./Constants.sol";
import { wrap } from "./Helpers.sol";
import { SD59x18 } from "./ValueType.sol";
/// @notice Calculates the absolute value of x.
///
/// @dev Requirements:
/// - x > MIN_SD59x18.
///
/// @param x The SD59x18 number for which to calculate the absolute value.
/// @return result The absolute value of x as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function abs(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt == uMIN_SD59x18) {
revert Errors.PRBMath_SD59x18_Abs_MinSD59x18();
}
result = xInt < 0 ? wrap(-xInt) : x;
}
/// @notice Calculates the arithmetic average of x and y.
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// @param x The first operand as an SD59x18 number.
/// @param y The second operand as an SD59x18 number.
/// @return result The arithmetic average as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function avg(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
int256 yInt = y.unwrap();
unchecked {
// This operation is equivalent to `x / 2 + y / 2`, and it can never overflow.
int256 sum = (xInt >> 1) + (yInt >> 1);
if (sum < 0) {
// If at least one of x and y is odd, add 1 to the result, because shifting negative numbers to the right
// rounds toward negative infinity. The right part is equivalent to `sum + (x % 2 == 1 || y % 2 == 1)`.
assembly ("memory-safe") {
result := add(sum, and(or(xInt, yInt), 1))
}
} else {
// Add 1 if both x and y are odd to account for the double 0.5 remainder truncated after shifting.
result = wrap(sum + (xInt & yInt & 1));
}
}
}
/// @notice Yields the smallest whole number greater than or equal to x.
///
/// @dev Optimized for fractional value inputs, because every whole value has (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x ≤ MAX_WHOLE_SD59x18
///
/// @param x The SD59x18 number to ceil.
/// @return result The smallest whole number greater than or equal to x, as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function ceil(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt > uMAX_WHOLE_SD59x18) {
revert Errors.PRBMath_SD59x18_Ceil_Overflow(x);
}
int256 remainder = xInt % uUNIT;
if (remainder == 0) {
result = x;
} else {
unchecked {
// Solidity uses C fmod style, which returns a modulus with the same sign as x.
int256 resultInt = xInt - remainder;
if (xInt > 0) {
resultInt += uUNIT;
}
result = wrap(resultInt);
}
}
}
/// @notice Divides two SD59x18 numbers, returning a new SD59x18 number.
///
/// @dev This is an extension of {Common.mulDiv} for signed numbers, which works by computing the signs and the absolute
/// values separately.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv}.
/// - The result is rounded toward zero.
///
/// Requirements:
/// - Refer to the requirements in {Common.mulDiv}.
/// - None of the inputs can be `MIN_SD59x18`.
/// - The denominator must not be zero.
/// - The result must fit in SD59x18.
///
/// @param x The numerator as an SD59x18 number.
/// @param y The denominator as an SD59x18 number.
/// @return result The quotient as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function div(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
int256 yInt = y.unwrap();
if (xInt == uMIN_SD59x18 || yInt == uMIN_SD59x18) {
revert Errors.PRBMath_SD59x18_Div_InputTooSmall();
}
// Get hold of the absolute values of x and y.
uint256 xAbs;
uint256 yAbs;
unchecked {
xAbs = xInt < 0 ? uint256(-xInt) : uint256(xInt);
yAbs = yInt < 0 ? uint256(-yInt) : uint256(yInt);
}
// Compute the absolute value (x*UNIT÷y). The resulting value must fit in SD59x18.
uint256 resultAbs = Common.mulDiv(xAbs, uint256(uUNIT), yAbs);
if (resultAbs > uint256(uMAX_SD59x18)) {
revert Errors.PRBMath_SD59x18_Div_Overflow(x, y);
}
// Check if x and y have the same sign using two's complement representation. The left-most bit represents the sign (1 for
// negative, 0 for positive or zero).
bool sameSign = (xInt ^ yInt) > -1;
// If the inputs have the same sign, the result should be positive. Otherwise, it should be negative.
unchecked {
result = wrap(sameSign ? int256(resultAbs) : -int256(resultAbs));
}
}
/// @notice Calculates the natural exponent of x using the following formula:
///
/// $$
/// e^x = 2^{x * log_2{e}}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {exp2}.
///
/// Requirements:
/// - Refer to the requirements in {exp2}.
/// - x < 133_084258667509499441.
///
/// @param x The exponent as an SD59x18 number.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function exp(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
// Any input less than the threshold returns zero.
// This check also prevents an overflow for very small numbers.
if (xInt < uEXP_MIN_THRESHOLD) {
return ZERO;
}
// This check prevents values greater than 192e18 from being passed to {exp2}.
if (xInt > uEXP_MAX_INPUT) {
revert Errors.PRBMath_SD59x18_Exp_InputTooBig(x);
}
unchecked {
// Inline the fixed-point multiplication to save gas.
int256 doubleUnitProduct = xInt * uLOG2_E;
result = exp2(wrap(doubleUnitProduct / uUNIT));
}
}
/// @notice Calculates the binary exponent of x using the binary fraction method using the following formula:
///
/// $$
/// 2^{-x} = \frac{1}{2^x}
/// $$
///
/// @dev See https://ethereum.stackexchange.com/q/79903/24693.
///
/// Notes:
/// - If x < -59_794705707972522261, the result is zero.
///
/// Requirements:
/// - x < 192e18.
/// - The result must fit in SD59x18.
///
/// @param x The exponent as an SD59x18 number.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function exp2(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt < 0) {
// The inverse of any number less than the threshold is truncated to zero.
if (xInt < uEXP2_MIN_THRESHOLD) {
return ZERO;
}
unchecked {
// Inline the fixed-point inversion to save gas.
result = wrap(uUNIT_SQUARED / exp2(wrap(-xInt)).unwrap());
}
} else {
// Numbers greater than or equal to 192e18 don't fit in the 192.64-bit format.
if (xInt > uEXP2_MAX_INPUT) {
revert Errors.PRBMath_SD59x18_Exp2_InputTooBig(x);
}
unchecked {
// Convert x to the 192.64-bit fixed-point format.
uint256 x_192x64 = uint256((xInt << 64) / uUNIT);
// It is safe to cast the result to int256 due to the checks above.
result = wrap(int256(Common.exp2(x_192x64)));
}
}
}
/// @notice Yields the greatest whole 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 ≥ MIN_WHOLE_SD59x18
///
/// @param x The SD59x18 number to floor.
/// @return result The greatest whole number less than or equal to x, as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function floor(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt < uMIN_WHOLE_SD59x18) {
revert Errors.PRBMath_SD59x18_Floor_Underflow(x);
}
int256 remainder = xInt % uUNIT;
if (remainder == 0) {
result = x;
} else {
unchecked {
// Solidity uses C fmod style, which returns a modulus with the same sign as x.
int256 resultInt = xInt - remainder;
if (xInt < 0) {
resultInt -= uUNIT;
}
result = wrap(resultInt);
}
}
}
/// @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 SD59x18 number to get the fractional part of.
/// @return result The fractional part of x as an SD59x18 number.
function frac(SD59x18 x) pure returns (SD59x18 result) {
result = wrap(x.unwrap() % uUNIT);
}
/// @notice Calculates the geometric mean of x and y, i.e. $\sqrt{x * y}$.
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x * y must fit in SD59x18.
/// - x * y must not be negative, since complex numbers are not supported.
///
/// @param x The first operand as an SD59x18 number.
/// @param y The second operand as an SD59x18 number.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function gm(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
int256 yInt = y.unwrap();
if (xInt == 0 || yInt == 0) {
return ZERO;
}
unchecked {
// Equivalent to `xy / x != y`. Checking for overflow this way is faster than letting Solidity do it.
int256 xyInt = xInt * yInt;
if (xyInt / xInt != yInt) {
revert Errors.PRBMath_SD59x18_Gm_Overflow(x, y);
}
// The product must not be negative, since complex numbers are not supported.
if (xyInt < 0) {
revert Errors.PRBMath_SD59x18_Gm_NegativeProduct(x, y);
}
// We don't need to multiply the result by `UNIT` here because the x*y product picked up a factor of `UNIT`
// during multiplication. See the comments in {Common.sqrt}.
uint256 resultUint = Common.sqrt(uint256(xyInt));
result = wrap(int256(resultUint));
}
}
/// @notice Calculates the inverse of x.
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x must not be zero.
///
/// @param x The SD59x18 number for which to calculate the inverse.
/// @return result The inverse as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function inv(SD59x18 x) pure returns (SD59x18 result) {
result = wrap(uUNIT_SQUARED / x.unwrap());
}
/// @notice Calculates the natural logarithm of x using the following formula:
///
/// $$
/// ln{x} = log_2{x} / log_2{e}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {log2}.
/// - The precision isn't sufficiently fine-grained to return exactly `UNIT` when the input is `E`.
///
/// Requirements:
/// - Refer to the requirements in {log2}.
///
/// @param x The SD59x18 number for which to calculate the natural logarithm.
/// @return result The natural logarithm as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function ln(SD59x18 x) pure returns (SD59x18 result) {
// Inline the fixed-point multiplication to save gas. This is overflow-safe because the maximum value that
// {log2} can return is ~195_205294292027477728.
result = wrap(log2(x).unwrap() * uUNIT / uLOG2_E);
}
/// @notice Calculates the common logarithm of x using the following formula:
///
/// $$
/// log_{10}{x} = log_2{x} / log_2{10}
/// $$
///
/// However, if x is an exact power of ten, a hard coded value is returned.
///
/// @dev Notes:
/// - Refer to the notes in {log2}.
///
/// Requirements:
/// - Refer to the requirements in {log2}.
///
/// @param x The SD59x18 number for which to calculate the common logarithm.
/// @return result The common logarithm as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function log10(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt < 0) {
revert Errors.PRBMath_SD59x18_Log_InputTooSmall(x);
}
// Note that the `mul` in this block is the standard multiplication operation, not {SD59x18.mul}.
// prettier-ignore
assembly ("memory-safe") {
switch x
case 1 { result := mul(uUNIT, sub(0, 18)) }
case 10 { result := mul(uUNIT, sub(1, 18)) }
case 100 { result := mul(uUNIT, sub(2, 18)) }
case 1000 { result := mul(uUNIT, sub(3, 18)) }
case 10000 { result := mul(uUNIT, sub(4, 18)) }
case 100000 { result := mul(uUNIT, sub(5, 18)) }
case 1000000 { result := mul(uUNIT, sub(6, 18)) }
case 10000000 { result := mul(uUNIT, sub(7, 18)) }
case 100000000 { result := mul(uUNIT, sub(8, 18)) }
case 1000000000 { result := mul(uUNIT, sub(9, 18)) }
case 10000000000 { result := mul(uUNIT, sub(10, 18)) }
case 100000000000 { result := mul(uUNIT, sub(11, 18)) }
case 1000000000000 { result := mul(uUNIT, sub(12, 18)) }
case 10000000000000 { result := mul(uUNIT, sub(13, 18)) }
case 100000000000000 { result := mul(uUNIT, sub(14, 18)) }
case 1000000000000000 { result := mul(uUNIT, sub(15, 18)) }
case 10000000000000000 { result := mul(uUNIT, sub(16, 18)) }
case 100000000000000000 { result := mul(uUNIT, sub(17, 18)) }
case 1000000000000000000 { result := 0 }
case 10000000000000000000 { result := uUNIT }
case 100000000000000000000 { result := mul(uUNIT, 2) }
case 1000000000000000000000 { result := mul(uUNIT, 3) }
case 10000000000000000000000 { result := mul(uUNIT, 4) }
case 100000000000000000000000 { result := mul(uUNIT, 5) }
case 1000000000000000000000000 { result := mul(uUNIT, 6) }
case 10000000000000000000000000 { result := mul(uUNIT, 7) }
case 100000000000000000000000000 { result := mul(uUNIT, 8) }
case 1000000000000000000000000000 { result := mul(uUNIT, 9) }
case 10000000000000000000000000000 { result := mul(uUNIT, 10) }
case 100000000000000000000000000000 { result := mul(uUNIT, 11) }
case 1000000000000000000000000000000 { result := mul(uUNIT, 12) }
case 10000000000000000000000000000000 { result := mul(uUNIT, 13) }
case 100000000000000000000000000000000 { result := mul(uUNIT, 14) }
case 1000000000000000000000000000000000 { result := mul(uUNIT, 15) }
case 10000000000000000000000000000000000 { result := mul(uUNIT, 16) }
case 100000000000000000000000000000000000 { result := mul(uUNIT, 17) }
case 1000000000000000000000000000000000000 { result := mul(uUNIT, 18) }
case 10000000000000000000000000000000000000 { result := mul(uUNIT, 19) }
case 100000000000000000000000000000000000000 { result := mul(uUNIT, 20) }
case 1000000000000000000000000000000000000000 { result := mul(uUNIT, 21) }
case 10000000000000000000000000000000000000000 { result := mul(uUNIT, 22) }
case 100000000000000000000000000000000000000000 { result := mul(uUNIT, 23) }
case 1000000000000000000000000000000000000000000 { result := mul(uUNIT, 24) }
case 10000000000000000000000000000000000000000000 { result := mul(uUNIT, 25) }
case 100000000000000000000000000000000000000000000 { result := mul(uUNIT, 26) }
case 1000000000000000000000000000000000000000000000 { result := mul(uUNIT, 27) }
case 10000000000000000000000000000000000000000000000 { result := mul(uUNIT, 28) }
case 100000000000000000000000000000000000000000000000 { result := mul(uUNIT, 29) }
case 1000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 30) }
case 10000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 31) }
case 100000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 32) }
case 1000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 33) }
case 10000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 34) }
case 100000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 35) }
case 1000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 36) }
case 10000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 37) }
case 100000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 38) }
case 1000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 39) }
case 10000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 40) }
case 100000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 41) }
case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 42) }
case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 43) }
case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 44) }
case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 45) }
case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 46) }
case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 47) }
case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 48) }
case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 49) }
case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 50) }
case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 51) }
case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 52) }
case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 53) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 54) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 55) }
case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 56) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 57) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 58) }
default { result := uMAX_SD59x18 }
}
if (result.unwrap() == uMAX_SD59x18) {
unchecked {
// Inline the fixed-point division to save gas.
result = wrap(log2(x).unwrap() * uUNIT / uLOG2_10);
}
}
}
/// @notice Calculates the binary logarithm of x using the iterative approximation algorithm:
///
/// $$
/// log_2{x} = n + log_2{y}, \text{ where } y = x*2^{-n}, \ y \in [1, 2)
/// $$
///
/// For $0 \leq x \lt 1$, the input is inverted:
///
/// $$
/// log_2{x} = -log_2{\frac{1}{x}}
/// $$
///
/// @dev See https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation.
///
/// Notes:
/// - Due to the lossy precision of the iterative approximation, the results are not perfectly accurate to the last decimal.
///
/// Requirements:
/// - x > 0
///
/// @param x The SD59x18 number for which to calculate the binary logarithm.
/// @return result The binary logarithm as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function log2(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt <= 0) {
revert Errors.PRBMath_SD59x18_Log_InputTooSmall(x);
}
unchecked {
int256 sign;
if (xInt >= uUNIT) {
sign = 1;
} else {
sign = -1;
// Inline the fixed-point inversion to save gas.
xInt = uUNIT_SQUARED / xInt;
}
// Calculate the integer part of the logarithm.
uint256 n = Common.msb(uint256(xInt / uUNIT));
// This is the integer part of the logarithm as an SD59x18 number. The operation can't overflow
// because n is at most 255, `UNIT` is 1e18, and the sign is either 1 or -1.
int256 resultInt = int256(n) * uUNIT;
// Calculate $y = x * 2^{-n}$.
int256 y = xInt >> n;
// If y is the unit number, the fractional part is zero.
if (y == uUNIT) {
return wrap(resultInt * sign);
}
// Calculate the fractional part via the iterative approximation.
// The `delta >>= 1` part is equivalent to `delta /= 2`, but shifting bits is more gas efficient.
int256 DOUBLE_UNIT = 2e18;
for (int256 delta = uHALF_UNIT; delta > 0; delta >>= 1) {
y = (y * y) / uUNIT;
// Is y^2 >= 2e18 and so in the range [2e18, 4e18)?
if (y >= DOUBLE_UNIT) {
// Add the 2^{-m} factor to the logarithm.
resultInt = resultInt + delta;
// Halve y, which corresponds to z/2 in the Wikipedia article.
y >>= 1;
}
}
resultInt *= sign;
result = wrap(resultInt);
}
}
/// @notice Multiplies two SD59x18 numbers together, returning a new SD59x18 number.
///
/// @dev Notes:
/// - Refer to the notes in {Common.mulDiv18}.
///
/// Requirements:
/// - Refer to the requirements in {Common.mulDiv18}.
/// - None of the inputs can be `MIN_SD59x18`.
/// - The result must fit in SD59x18.
///
/// @param x The multiplicand as an SD59x18 number.
/// @param y The multiplier as an SD59x18 number.
/// @return result The product as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function mul(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
int256 yInt = y.unwrap();
if (xInt == uMIN_SD59x18 || yInt == uMIN_SD59x18) {
revert Errors.PRBMath_SD59x18_Mul_InputTooSmall();
}
// Get hold of the absolute values of x and y.
uint256 xAbs;
uint256 yAbs;
unchecked {
xAbs = xInt < 0 ? uint256(-xInt) : uint256(xInt);
yAbs = yInt < 0 ? uint256(-yInt) : uint256(yInt);
}
// Compute the absolute value (x*y÷UNIT). The resulting value must fit in SD59x18.
uint256 resultAbs = Common.mulDiv18(xAbs, yAbs);
if (resultAbs > uint256(uMAX_SD59x18)) {
revert Errors.PRBMath_SD59x18_Mul_Overflow(x, y);
}
// Check if x and y have the same sign using two's complement representation. The left-most bit represents the sign (1 for
// negative, 0 for positive or zero).
bool sameSign = (xInt ^ yInt) > -1;
// If the inputs have the same sign, the result should be positive. Otherwise, it should be negative.
unchecked {
result = wrap(sameSign ? int256(resultAbs) : -int256(resultAbs));
}
}
/// @notice Raises x to the power of y using the following formula:
///
/// $$
/// x^y = 2^{log_2{x} * y}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {exp2}, {log2}, and {mul}.
/// - Returns `UNIT` for 0^0.
///
/// Requirements:
/// - Refer to the requirements in {exp2}, {log2}, and {mul}.
///
/// @param x The base as an SD59x18 number.
/// @param y Exponent to raise x to, as an SD59x18 number
/// @return result x raised to power y, as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function pow(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
int256 yInt = y.unwrap();
// If both x and y are zero, the result is `UNIT`. If just x is zero, the result is always zero.
if (xInt == 0) {
return yInt == 0 ? UNIT : ZERO;
}
// If x is `UNIT`, the result is always `UNIT`.
else if (xInt == uUNIT) {
return UNIT;
}
// If y is zero, the result is always `UNIT`.
if (yInt == 0) {
return UNIT;
}
// If y is `UNIT`, the result is always x.
else if (yInt == uUNIT) {
return x;
}
// Calculate the result using the formula.
result = exp2(mul(log2(x), y));
}
/// @notice Raises x (an SD59x18 number) to the power y (an unsigned basic integer) using the well-known
/// algorithm "exponentiation by squaring".
///
/// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv18}.
/// - Returns `UNIT` for 0^0.
///
/// Requirements:
/// - Refer to the requirements in {abs} and {Common.mulDiv18}.
/// - The result must fit in SD59x18.
///
/// @param x The base as an SD59x18 number.
/// @param y The exponent as a uint256.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function powu(SD59x18 x, uint256 y) pure returns (SD59x18 result) {
uint256 xAbs = uint256(abs(x).unwrap());
// Calculate the first iteration of the loop in advance.
uint256 resultAbs = y & 1 > 0 ? xAbs : uint256(uUNIT);
// Equivalent to `for(y /= 2; y > 0; y /= 2)`.
uint256 yAux = y;
for (yAux >>= 1; yAux > 0; yAux >>= 1) {
xAbs = Common.mulDiv18(xAbs, xAbs);
// Equivalent to `y % 2 == 1`.
if (yAux & 1 > 0) {
resultAbs = Common.mulDiv18(resultAbs, xAbs);
}
}
// The result must fit in SD59x18.
if (resultAbs > uint256(uMAX_SD59x18)) {
revert Errors.PRBMath_SD59x18_Powu_Overflow(x, y);
}
unchecked {
// Is the base negative and the exponent odd? If yes, the result should be negative.
int256 resultInt = int256(resultAbs);
bool isNegative = x.unwrap() < 0 && y & 1 == 1;
if (isNegative) {
resultInt = -resultInt;
}
result = wrap(resultInt);
}
}
/// @notice Calculates the square root of x using the Babylonian method.
///
/// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Notes:
/// - Only the positive root is returned.
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x ≥ 0, since complex numbers are not supported.
/// - x ≤ MAX_SD59x18 / UNIT
///
/// @param x The SD59x18 number for which to calculate the square root.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function sqrt(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt < 0) {
revert Errors.PRBMath_SD59x18_Sqrt_NegativeInput(x);
}
if (xInt > uMAX_SD59x18 / uUNIT) {
revert Errors.PRBMath_SD59x18_Sqrt_Overflow(x);
}
unchecked {
// Multiply x by `UNIT` to account for the factor of `UNIT` picked up when multiplying two SD59x18 numbers.
// In this case, the two numbers are both the square root.
uint256 resultUint = Common.sqrt(uint256(xInt * uUNIT));
result = wrap(int256(resultUint));
}
}
lib/prb-math/src/sd59x18/ValueType.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Casting.sol" as Casting;
import "./Helpers.sol" as Helpers;
import "./Math.sol" as Math;
/// @notice The signed 59.18-decimal fixed-point number representation, which can have up to 59 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type int256.
type SD59x18 is int256;
/*//////////////////////////////////////////////////////////////////////////
CASTING
//////////////////////////////////////////////////////////////////////////*/
using {
Casting.intoInt256,
Casting.intoSD1x18,
Casting.intoSD21x18,
Casting.intoUD2x18,
Casting.intoUD21x18,
Casting.intoUD60x18,
Casting.intoUint256,
Casting.intoUint128,
Casting.intoUint40,
Casting.unwrap
} for SD59x18 global;
/*//////////////////////////////////////////////////////////////////////////
MATHEMATICAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
using {
Math.abs,
Math.avg,
Math.ceil,
Math.div,
Math.exp,
Math.exp2,
Math.floor,
Math.frac,
Math.gm,
Math.inv,
Math.log10,
Math.log2,
Math.ln,
Math.mul,
Math.pow,
Math.powu,
Math.sqrt
} for SD59x18 global;
/*//////////////////////////////////////////////////////////////////////////
HELPER FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
using {
Helpers.add,
Helpers.and,
Helpers.eq,
Helpers.gt,
Helpers.gte,
Helpers.isZero,
Helpers.lshift,
Helpers.lt,
Helpers.lte,
Helpers.mod,
Helpers.neq,
Helpers.not,
Helpers.or,
Helpers.rshift,
Helpers.sub,
Helpers.uncheckedAdd,
Helpers.uncheckedSub,
Helpers.uncheckedUnary,
Helpers.xor
} for SD59x18 global;
/*//////////////////////////////////////////////////////////////////////////
OPERATORS
//////////////////////////////////////////////////////////////////////////*/
// The global "using for" directive makes it possible to use these operators on the SD59x18 type.
using {
Helpers.add as +,
Helpers.and2 as &,
Math.div as /,
Helpers.eq as ==,
Helpers.gt as >,
Helpers.gte as >=,
Helpers.lt as <,
Helpers.lte as <=,
Helpers.mod as %,
Math.mul as *,
Helpers.neq as !=,
Helpers.not as ~,
Helpers.or as |,
Helpers.sub as -,
Helpers.unary as -,
Helpers.xor as ^
} for SD59x18 global;
lib/prb-math/src/ud21x18/Casting.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "../Common.sol" as Common;
import "./Errors.sol" as Errors;
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { UD21x18 } from "./ValueType.sol";
/// @notice Casts a UD21x18 number into SD59x18.
/// @dev There is no overflow check because UD21x18 ⊆ SD59x18.
function intoSD59x18(UD21x18 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(int256(uint256(UD21x18.unwrap(x))));
}
/// @notice Casts a UD21x18 number into UD60x18.
/// @dev There is no overflow check because UD21x18 ⊆ UD60x18.
function intoUD60x18(UD21x18 x) pure returns (UD60x18 result) {
result = UD60x18.wrap(UD21x18.unwrap(x));
}
/// @notice Casts a UD21x18 number into uint128.
/// @dev This is basically an alias for {unwrap}.
function intoUint128(UD21x18 x) pure returns (uint128 result) {
result = UD21x18.unwrap(x);
}
/// @notice Casts a UD21x18 number into uint256.
/// @dev There is no overflow check because UD21x18 ⊆ uint256.
function intoUint256(UD21x18 x) pure returns (uint256 result) {
result = uint256(UD21x18.unwrap(x));
}
/// @notice Casts a UD21x18 number into uint40.
/// @dev Requirements:
/// - x ≤ MAX_UINT40
function intoUint40(UD21x18 x) pure returns (uint40 result) {
uint128 xUint = UD21x18.unwrap(x);
if (xUint > uint128(Common.MAX_UINT40)) {
revert Errors.PRBMath_UD21x18_IntoUint40_Overflow(x);
}
result = uint40(xUint);
}
/// @notice Alias for {wrap}.
function ud21x18(uint128 x) pure returns (UD21x18 result) {
result = UD21x18.wrap(x);
}
/// @notice Unwrap a UD21x18 number into uint128.
function unwrap(UD21x18 x) pure returns (uint128 result) {
result = UD21x18.unwrap(x);
}
/// @notice Wraps a uint128 number into UD21x18.
function wrap(uint128 x) pure returns (UD21x18 result) {
result = UD21x18.wrap(x);
}
lib/prb-math/src/ud21x18/Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { UD21x18 } from "./ValueType.sol";
/// @dev Euler's number as a UD21x18 number.
UD21x18 constant E = UD21x18.wrap(2_718281828459045235);
/// @dev The maximum value a UD21x18 number can have.
uint128 constant uMAX_UD21x18 = 340282366920938463463_374607431768211455;
UD21x18 constant MAX_UD21x18 = UD21x18.wrap(uMAX_UD21x18);
/// @dev PI as a UD21x18 number.
UD21x18 constant PI = UD21x18.wrap(3_141592653589793238);
/// @dev The unit number, which gives the decimal precision of UD21x18.
uint256 constant uUNIT = 1e18;
UD21x18 constant UNIT = UD21x18.wrap(1e18);
lib/prb-math/src/ud21x18/Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { UD21x18 } from "./ValueType.sol";
/// @notice Thrown when trying to cast a UD21x18 number that doesn't fit in uint40.
error PRBMath_UD21x18_IntoUint40_Overflow(UD21x18 x);
lib/prb-math/src/ud21x18/ValueType.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Casting.sol" as Casting;
/// @notice The unsigned 21.18-decimal fixed-point number representation, which can have up to 21 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type uint128. This is useful when end users want to use uint128 to save gas, e.g. with tight variable packing in contract
/// storage.
type UD21x18 is uint128;
/*//////////////////////////////////////////////////////////////////////////
CASTING
//////////////////////////////////////////////////////////////////////////*/
using {
Casting.intoSD59x18,
Casting.intoUD60x18,
Casting.intoUint128,
Casting.intoUint256,
Casting.intoUint40,
Casting.unwrap
} for UD21x18 global;
lib/prb-math/src/ud2x18/Casting.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "../Common.sol" as Common;
import "./Errors.sol" as Errors;
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { UD2x18 } from "./ValueType.sol";
/// @notice Casts a UD2x18 number into SD59x18.
/// @dev There is no overflow check because UD2x18 ⊆ SD59x18.
function intoSD59x18(UD2x18 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(int256(uint256(UD2x18.unwrap(x))));
}
/// @notice Casts a UD2x18 number into UD60x18.
/// @dev There is no overflow check because UD2x18 ⊆ UD60x18.
function intoUD60x18(UD2x18 x) pure returns (UD60x18 result) {
result = UD60x18.wrap(UD2x18.unwrap(x));
}
/// @notice Casts a UD2x18 number into uint128.
/// @dev There is no overflow check because UD2x18 ⊆ uint128.
function intoUint128(UD2x18 x) pure returns (uint128 result) {
result = uint128(UD2x18.unwrap(x));
}
/// @notice Casts a UD2x18 number into uint256.
/// @dev There is no overflow check because UD2x18 ⊆ uint256.
function intoUint256(UD2x18 x) pure returns (uint256 result) {
result = uint256(UD2x18.unwrap(x));
}
/// @notice Casts a UD2x18 number into uint40.
/// @dev Requirements:
/// - x ≤ MAX_UINT40
function intoUint40(UD2x18 x) pure returns (uint40 result) {
uint64 xUint = UD2x18.unwrap(x);
if (xUint > uint64(Common.MAX_UINT40)) {
revert Errors.PRBMath_UD2x18_IntoUint40_Overflow(x);
}
result = uint40(xUint);
}
/// @notice Alias for {wrap}.
function ud2x18(uint64 x) pure returns (UD2x18 result) {
result = UD2x18.wrap(x);
}
/// @notice Unwrap a UD2x18 number into uint64.
function unwrap(UD2x18 x) pure returns (uint64 result) {
result = UD2x18.unwrap(x);
}
/// @notice Wraps a uint64 number into UD2x18.
function wrap(uint64 x) pure returns (UD2x18 result) {
result = UD2x18.wrap(x);
}
lib/prb-math/src/ud2x18/Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { UD2x18 } from "./ValueType.sol";
/// @dev Euler's number as a UD2x18 number.
UD2x18 constant E = UD2x18.wrap(2_718281828459045235);
/// @dev The maximum value a UD2x18 number can have.
uint64 constant uMAX_UD2x18 = 18_446744073709551615;
UD2x18 constant MAX_UD2x18 = UD2x18.wrap(uMAX_UD2x18);
/// @dev PI as a UD2x18 number.
UD2x18 constant PI = UD2x18.wrap(3_141592653589793238);
/// @dev The unit number, which gives the decimal precision of UD2x18.
UD2x18 constant UNIT = UD2x18.wrap(1e18);
uint64 constant uUNIT = 1e18;
lib/prb-math/src/ud2x18/Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { UD2x18 } from "./ValueType.sol";
/// @notice Thrown when trying to cast a UD2x18 number that doesn't fit in uint40.
error PRBMath_UD2x18_IntoUint40_Overflow(UD2x18 x);
lib/prb-math/src/ud2x18/ValueType.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Casting.sol" as Casting;
/// @notice The unsigned 2.18-decimal fixed-point number representation, which can have up to 2 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type uint64. This is useful when end users want to use uint64 to save gas, e.g. with tight variable packing in contract
/// storage.
type UD2x18 is uint64;
/*//////////////////////////////////////////////////////////////////////////
CASTING
//////////////////////////////////////////////////////////////////////////*/
using {
Casting.intoSD59x18,
Casting.intoUD60x18,
Casting.intoUint128,
Casting.intoUint256,
Casting.intoUint40,
Casting.unwrap
} for UD2x18 global;
lib/prb-math/src/ud60x18/Casting.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Errors.sol" as CastingErrors;
import { MAX_UINT128, MAX_UINT40 } from "../Common.sol";
import { uMAX_SD1x18 } from "../sd1x18/Constants.sol";
import { SD1x18 } from "../sd1x18/ValueType.sol";
import { uMAX_SD21x18 } from "../sd21x18/Constants.sol";
import { SD21x18 } from "../sd21x18/ValueType.sol";
import { uMAX_SD59x18 } from "../sd59x18/Constants.sol";
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { uMAX_UD2x18 } from "../ud2x18/Constants.sol";
import { uMAX_UD21x18 } from "../ud21x18/Constants.sol";
import { UD2x18 } from "../ud2x18/ValueType.sol";
import { UD21x18 } from "../ud21x18/ValueType.sol";
import { UD60x18 } from "./ValueType.sol";
/// @notice Casts a UD60x18 number into SD1x18.
/// @dev Requirements:
/// - x ≤ uMAX_SD1x18
function intoSD1x18(UD60x18 x) pure returns (SD1x18 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > uint256(int256(uMAX_SD1x18))) {
revert CastingErrors.PRBMath_UD60x18_IntoSD1x18_Overflow(x);
}
result = SD1x18.wrap(int64(uint64(xUint)));
}
/// @notice Casts a UD60x18 number into SD21x18.
/// @dev Requirements:
/// - x ≤ uMAX_SD21x18
function intoSD21x18(UD60x18 x) pure returns (SD21x18 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > uint256(int256(uMAX_SD21x18))) {
revert CastingErrors.PRBMath_UD60x18_IntoSD21x18_Overflow(x);
}
result = SD21x18.wrap(int128(uint128(xUint)));
}
/// @notice Casts a UD60x18 number into UD2x18.
/// @dev Requirements:
/// - x ≤ uMAX_UD2x18
function intoUD2x18(UD60x18 x) pure returns (UD2x18 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > uMAX_UD2x18) {
revert CastingErrors.PRBMath_UD60x18_IntoUD2x18_Overflow(x);
}
result = UD2x18.wrap(uint64(xUint));
}
/// @notice Casts a UD60x18 number into UD21x18.
/// @dev Requirements:
/// - x ≤ uMAX_UD21x18
function intoUD21x18(UD60x18 x) pure returns (UD21x18 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > uMAX_UD21x18) {
revert CastingErrors.PRBMath_UD60x18_IntoUD21x18_Overflow(x);
}
result = UD21x18.wrap(uint128(xUint));
}
/// @notice Casts a UD60x18 number into SD59x18.
/// @dev Requirements:
/// - x ≤ uMAX_SD59x18
function intoSD59x18(UD60x18 x) pure returns (SD59x18 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > uint256(uMAX_SD59x18)) {
revert CastingErrors.PRBMath_UD60x18_IntoSD59x18_Overflow(x);
}
result = SD59x18.wrap(int256(xUint));
}
/// @notice Casts a UD60x18 number into uint128.
/// @dev This is basically an alias for {unwrap}.
function intoUint256(UD60x18 x) pure returns (uint256 result) {
result = UD60x18.unwrap(x);
}
/// @notice Casts a UD60x18 number into uint128.
/// @dev Requirements:
/// - x ≤ MAX_UINT128
function intoUint128(UD60x18 x) pure returns (uint128 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > MAX_UINT128) {
revert CastingErrors.PRBMath_UD60x18_IntoUint128_Overflow(x);
}
result = uint128(xUint);
}
/// @notice Casts a UD60x18 number into uint40.
/// @dev Requirements:
/// - x ≤ MAX_UINT40
function intoUint40(UD60x18 x) pure returns (uint40 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > MAX_UINT40) {
revert CastingErrors.PRBMath_UD60x18_IntoUint40_Overflow(x);
}
result = uint40(xUint);
}
/// @notice Alias for {wrap}.
function ud(uint256 x) pure returns (UD60x18 result) {
result = UD60x18.wrap(x);
}
/// @notice Alias for {wrap}.
function ud60x18(uint256 x) pure returns (UD60x18 result) {
result = UD60x18.wrap(x);
}
/// @notice Unwraps a UD60x18 number into uint256.
function unwrap(UD60x18 x) pure returns (uint256 result) {
result = UD60x18.unwrap(x);
}
/// @notice Wraps a uint256 number into the UD60x18 value type.
function wrap(uint256 x) pure returns (UD60x18 result) {
result = UD60x18.wrap(x);
}
lib/prb-math/src/ud60x18/Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { UD60x18 } from "./ValueType.sol";
// NOTICE: the "u" prefix stands for "unwrapped".
/// @dev Euler's number as a UD60x18 number.
UD60x18 constant E = UD60x18.wrap(2_718281828459045235);
/// @dev The maximum input permitted in {exp}.
uint256 constant uEXP_MAX_INPUT = 133_084258667509499440;
UD60x18 constant EXP_MAX_INPUT = UD60x18.wrap(uEXP_MAX_INPUT);
/// @dev The maximum input permitted in {exp2}.
uint256 constant uEXP2_MAX_INPUT = 192e18 - 1;
UD60x18 constant EXP2_MAX_INPUT = UD60x18.wrap(uEXP2_MAX_INPUT);
/// @dev Half the UNIT number.
uint256 constant uHALF_UNIT = 0.5e18;
UD60x18 constant HALF_UNIT = UD60x18.wrap(uHALF_UNIT);
/// @dev $log_2(10)$ as a UD60x18 number.
uint256 constant uLOG2_10 = 3_321928094887362347;
UD60x18 constant LOG2_10 = UD60x18.wrap(uLOG2_10);
/// @dev $log_2(e)$ as a UD60x18 number.
uint256 constant uLOG2_E = 1_442695040888963407;
UD60x18 constant LOG2_E = UD60x18.wrap(uLOG2_E);
/// @dev The maximum value a UD60x18 number can have.
uint256 constant uMAX_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_584007913129639935;
UD60x18 constant MAX_UD60x18 = UD60x18.wrap(uMAX_UD60x18);
/// @dev The maximum whole value a UD60x18 number can have.
uint256 constant uMAX_WHOLE_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_000000000000000000;
UD60x18 constant MAX_WHOLE_UD60x18 = UD60x18.wrap(uMAX_WHOLE_UD60x18);
/// @dev PI as a UD60x18 number.
UD60x18 constant PI = UD60x18.wrap(3_141592653589793238);
/// @dev The unit number, which gives the decimal precision of UD60x18.
uint256 constant uUNIT = 1e18;
UD60x18 constant UNIT = UD60x18.wrap(uUNIT);
/// @dev The unit number squared.
uint256 constant uUNIT_SQUARED = 1e36;
UD60x18 constant UNIT_SQUARED = UD60x18.wrap(uUNIT_SQUARED);
/// @dev Zero as a UD60x18 number.
UD60x18 constant ZERO = UD60x18.wrap(0);
lib/prb-math/src/ud60x18/Conversions.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { uMAX_UD60x18, uUNIT } from "./Constants.sol";
import { PRBMath_UD60x18_Convert_Overflow } from "./Errors.sol";
import { UD60x18 } from "./ValueType.sol";
/// @notice Converts a UD60x18 number to a simple integer by dividing it by `UNIT`.
/// @dev The result is rounded toward zero.
/// @param x The UD60x18 number to convert.
/// @return result The same number in basic integer form.
function convert(UD60x18 x) pure returns (uint256 result) {
result = UD60x18.unwrap(x) / uUNIT;
}
/// @notice Converts a simple integer to UD60x18 by multiplying it by `UNIT`.
///
/// @dev Requirements:
/// - x ≤ MAX_UD60x18 / UNIT
///
/// @param x The basic integer to convert.
/// @return result The same number converted to UD60x18.
function convert(uint256 x) pure returns (UD60x18 result) {
if (x > uMAX_UD60x18 / uUNIT) {
revert PRBMath_UD60x18_Convert_Overflow(x);
}
unchecked {
result = UD60x18.wrap(x * uUNIT);
}
}
lib/prb-math/src/ud60x18/Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { UD60x18 } from "./ValueType.sol";
/// @notice Thrown when ceiling a number overflows UD60x18.
error PRBMath_UD60x18_Ceil_Overflow(UD60x18 x);
/// @notice Thrown when converting a basic integer to the fixed-point format overflows UD60x18.
error PRBMath_UD60x18_Convert_Overflow(uint256 x);
/// @notice Thrown when taking the natural exponent of a base greater than 133_084258667509499441.
error PRBMath_UD60x18_Exp_InputTooBig(UD60x18 x);
/// @notice Thrown when taking the binary exponent of a base greater than 192e18.
error PRBMath_UD60x18_Exp2_InputTooBig(UD60x18 x);
/// @notice Thrown when taking the geometric mean of two numbers and multiplying them overflows UD60x18.
error PRBMath_UD60x18_Gm_Overflow(UD60x18 x, UD60x18 y);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD1x18.
error PRBMath_UD60x18_IntoSD1x18_Overflow(UD60x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD21x18.
error PRBMath_UD60x18_IntoSD21x18_Overflow(UD60x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD59x18.
error PRBMath_UD60x18_IntoSD59x18_Overflow(UD60x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in UD2x18.
error PRBMath_UD60x18_IntoUD2x18_Overflow(UD60x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in UD21x18.
error PRBMath_UD60x18_IntoUD21x18_Overflow(UD60x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint128.
error PRBMath_UD60x18_IntoUint128_Overflow(UD60x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint40.
error PRBMath_UD60x18_IntoUint40_Overflow(UD60x18 x);
/// @notice Thrown when taking the logarithm of a number less than UNIT.
error PRBMath_UD60x18_Log_InputTooSmall(UD60x18 x);
/// @notice Thrown when calculating the square root overflows UD60x18.
error PRBMath_UD60x18_Sqrt_Overflow(UD60x18 x);
lib/prb-math/src/ud60x18/Helpers.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { wrap } from "./Casting.sol";
import { UD60x18 } from "./ValueType.sol";
/// @notice Implements the checked addition operation (+) in the UD60x18 type.
function add(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(x.unwrap() + y.unwrap());
}
/// @notice Implements the AND (&) bitwise operation in the UD60x18 type.
function and(UD60x18 x, uint256 bits) pure returns (UD60x18 result) {
result = wrap(x.unwrap() & bits);
}
/// @notice Implements the AND (&) bitwise operation in the UD60x18 type.
function and2(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(x.unwrap() & y.unwrap());
}
/// @notice Implements the equal operation (==) in the UD60x18 type.
function eq(UD60x18 x, UD60x18 y) pure returns (bool result) {
result = x.unwrap() == y.unwrap();
}
/// @notice Implements the greater than operation (>) in the UD60x18 type.
function gt(UD60x18 x, UD60x18 y) pure returns (bool result) {
result = x.unwrap() > y.unwrap();
}
/// @notice Implements the greater than or equal to operation (>=) in the UD60x18 type.
function gte(UD60x18 x, UD60x18 y) pure returns (bool result) {
result = x.unwrap() >= y.unwrap();
}
/// @notice Implements a zero comparison check function in the UD60x18 type.
function isZero(UD60x18 x) pure returns (bool result) {
// This wouldn't work if x could be negative.
result = x.unwrap() == 0;
}
/// @notice Implements the left shift operation (<<) in the UD60x18 type.
function lshift(UD60x18 x, uint256 bits) pure returns (UD60x18 result) {
result = wrap(x.unwrap() << bits);
}
/// @notice Implements the lower than operation (<) in the UD60x18 type.
function lt(UD60x18 x, UD60x18 y) pure returns (bool result) {
result = x.unwrap() < y.unwrap();
}
/// @notice Implements the lower than or equal to operation (<=) in the UD60x18 type.
function lte(UD60x18 x, UD60x18 y) pure returns (bool result) {
result = x.unwrap() <= y.unwrap();
}
/// @notice Implements the checked modulo operation (%) in the UD60x18 type.
function mod(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(x.unwrap() % y.unwrap());
}
/// @notice Implements the not equal operation (!=) in the UD60x18 type.
function neq(UD60x18 x, UD60x18 y) pure returns (bool result) {
result = x.unwrap() != y.unwrap();
}
/// @notice Implements the NOT (~) bitwise operation in the UD60x18 type.
function not(UD60x18 x) pure returns (UD60x18 result) {
result = wrap(~x.unwrap());
}
/// @notice Implements the OR (|) bitwise operation in the UD60x18 type.
function or(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(x.unwrap() | y.unwrap());
}
/// @notice Implements the right shift operation (>>) in the UD60x18 type.
function rshift(UD60x18 x, uint256 bits) pure returns (UD60x18 result) {
result = wrap(x.unwrap() >> bits);
}
/// @notice Implements the checked subtraction operation (-) in the UD60x18 type.
function sub(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(x.unwrap() - y.unwrap());
}
/// @notice Implements the unchecked addition operation (+) in the UD60x18 type.
function uncheckedAdd(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
unchecked {
result = wrap(x.unwrap() + y.unwrap());
}
}
/// @notice Implements the unchecked subtraction operation (-) in the UD60x18 type.
function uncheckedSub(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
unchecked {
result = wrap(x.unwrap() - y.unwrap());
}
}
/// @notice Implements the XOR (^) bitwise operation in the UD60x18 type.
function xor(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(x.unwrap() ^ y.unwrap());
}
lib/prb-math/src/ud60x18/Math.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "../Common.sol" as Common;
import "./Errors.sol" as Errors;
import { wrap } from "./Casting.sol";
import {
uEXP_MAX_INPUT,
uEXP2_MAX_INPUT,
uHALF_UNIT,
uLOG2_10,
uLOG2_E,
uMAX_UD60x18,
uMAX_WHOLE_UD60x18,
UNIT,
uUNIT,
uUNIT_SQUARED,
ZERO
} from "./Constants.sol";
import { UD60x18 } from "./ValueType.sol";
/*//////////////////////////////////////////////////////////////////////////
MATHEMATICAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Calculates the arithmetic average of x and y using the following formula:
///
/// $$
/// avg(x, y) = (x & y) + ((xUint ^ yUint) / 2)
/// $$
///
/// In English, this is what this formula does:
///
/// 1. AND x and y.
/// 2. Calculate half of XOR x and y.
/// 3. Add the two results together.
///
/// This technique is known as SWAR, which stands for "SIMD within a register". You can read more about it here:
/// https://devblogs.microsoft.com/oldnewthing/20220207-00/?p=106223
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// @param x The first operand as a UD60x18 number.
/// @param y The second operand as a UD60x18 number.
/// @return result The arithmetic average as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function avg(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
uint256 yUint = y.unwrap();
unchecked {
result = wrap((xUint & yUint) + ((xUint ^ yUint) >> 1));
}
}
/// @notice Yields the smallest whole number greater than or equal to x.
///
/// @dev This is 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 ≤ MAX_WHOLE_UD60x18
///
/// @param x The UD60x18 number to ceil.
/// @return result The smallest whole number greater than or equal to x, as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function ceil(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
if (xUint > uMAX_WHOLE_UD60x18) {
revert Errors.PRBMath_UD60x18_Ceil_Overflow(x);
}
assembly ("memory-safe") {
// Equivalent to `x % UNIT`.
let remainder := mod(x, uUNIT)
// Equivalent to `UNIT - remainder`.
let delta := sub(uUNIT, remainder)
// Equivalent to `x + remainder > 0 ? delta : 0`.
result := add(x, mul(delta, gt(remainder, 0)))
}
}
/// @notice Divides two UD60x18 numbers, returning a new UD60x18 number.
///
/// @dev Uses {Common.mulDiv} to enable overflow-safe multiplication and division.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv}.
///
/// Requirements:
/// - Refer to the requirements in {Common.mulDiv}.
///
/// @param x The numerator as a UD60x18 number.
/// @param y The denominator as a UD60x18 number.
/// @return result The quotient as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function div(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(Common.mulDiv(x.unwrap(), uUNIT, y.unwrap()));
}
/// @notice Calculates the natural exponent of x using the following formula:
///
/// $$
/// e^x = 2^{x * log_2{e}}
/// $$
///
/// @dev Requirements:
/// - x ≤ 133_084258667509499440
///
/// @param x The exponent as a UD60x18 number.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function exp(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
// This check prevents values greater than 192e18 from being passed to {exp2}.
if (xUint > uEXP_MAX_INPUT) {
revert Errors.PRBMath_UD60x18_Exp_InputTooBig(x);
}
unchecked {
// Inline the fixed-point multiplication to save gas.
uint256 doubleUnitProduct = xUint * uLOG2_E;
result = exp2(wrap(doubleUnitProduct / uUNIT));
}
}
/// @notice Calculates the binary exponent of x using the binary fraction method.
///
/// @dev See https://ethereum.stackexchange.com/q/79903/24693
///
/// Requirements:
/// - x < 192e18
/// - The result must fit in UD60x18.
///
/// @param x The exponent as a UD60x18 number.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function exp2(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
// Numbers greater than or equal to 192e18 don't fit in the 192.64-bit format.
if (xUint > uEXP2_MAX_INPUT) {
revert Errors.PRBMath_UD60x18_Exp2_InputTooBig(x);
}
// Convert x to the 192.64-bit fixed-point format.
uint256 x_192x64 = (xUint << 64) / uUNIT;
// Pass x to the {Common.exp2} function, which uses the 192.64-bit fixed-point number representation.
result = wrap(Common.exp2(x_192x64));
}
/// @notice Yields the greatest whole number less than or equal to x.
/// @dev Optimized for fractional value inputs, because every whole value has (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
/// @param x The UD60x18 number to floor.
/// @return result The greatest whole number less than or equal to x, as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function floor(UD60x18 x) pure returns (UD60x18 result) {
assembly ("memory-safe") {
// Equivalent to `x % UNIT`.
let remainder := mod(x, uUNIT)
// Equivalent to `x - remainder > 0 ? remainder : 0)`.
result := sub(x, mul(remainder, gt(remainder, 0)))
}
}
/// @notice Yields the excess beyond the floor of x using the odd function definition.
/// @dev See https://en.wikipedia.org/wiki/Fractional_part.
/// @param x The UD60x18 number to get the fractional part of.
/// @return result The fractional part of x as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function frac(UD60x18 x) pure returns (UD60x18 result) {
assembly ("memory-safe") {
result := mod(x, uUNIT)
}
}
/// @notice Calculates the geometric mean of x and y, i.e. $\sqrt{x * y}$, rounding down.
///
/// @dev Requirements:
/// - x * y must fit in UD60x18.
///
/// @param x The first operand as a UD60x18 number.
/// @param y The second operand as a UD60x18 number.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function gm(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
uint256 yUint = y.unwrap();
if (xUint == 0 || yUint == 0) {
return ZERO;
}
unchecked {
// Checking for overflow this way is faster than letting Solidity do it.
uint256 xyUint = xUint * yUint;
if (xyUint / xUint != yUint) {
revert Errors.PRBMath_UD60x18_Gm_Overflow(x, y);
}
// We don't need to multiply the result by `UNIT` here because the x*y product picked up a factor of `UNIT`
// during multiplication. See the comments in {Common.sqrt}.
result = wrap(Common.sqrt(xyUint));
}
}
/// @notice Calculates the inverse of x.
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x must not be zero.
///
/// @param x The UD60x18 number for which to calculate the inverse.
/// @return result The inverse as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function inv(UD60x18 x) pure returns (UD60x18 result) {
unchecked {
result = wrap(uUNIT_SQUARED / x.unwrap());
}
}
/// @notice Calculates the natural logarithm of x using the following formula:
///
/// $$
/// ln{x} = log_2{x} / log_2{e}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {log2}.
/// - The precision isn't sufficiently fine-grained to return exactly `UNIT` when the input is `E`.
///
/// Requirements:
/// - Refer to the requirements in {log2}.
///
/// @param x The UD60x18 number for which to calculate the natural logarithm.
/// @return result The natural logarithm as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function ln(UD60x18 x) pure returns (UD60x18 result) {
unchecked {
// Inline the fixed-point multiplication to save gas. This is overflow-safe because the maximum value that
// {log2} can return is ~196_205294292027477728.
result = wrap(log2(x).unwrap() * uUNIT / uLOG2_E);
}
}
/// @notice Calculates the common logarithm of x using the following formula:
///
/// $$
/// log_{10}{x} = log_2{x} / log_2{10}
/// $$
///
/// However, if x is an exact power of ten, a hard coded value is returned.
///
/// @dev Notes:
/// - Refer to the notes in {log2}.
///
/// Requirements:
/// - Refer to the requirements in {log2}.
///
/// @param x The UD60x18 number for which to calculate the common logarithm.
/// @return result The common logarithm as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function log10(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
if (xUint < uUNIT) {
revert Errors.PRBMath_UD60x18_Log_InputTooSmall(x);
}
// Note that the `mul` in this assembly block is the standard multiplication operation, not {UD60x18.mul}.
// prettier-ignore
assembly ("memory-safe") {
switch x
case 1 { result := mul(uUNIT, sub(0, 18)) }
case 10 { result := mul(uUNIT, sub(1, 18)) }
case 100 { result := mul(uUNIT, sub(2, 18)) }
case 1000 { result := mul(uUNIT, sub(3, 18)) }
case 10000 { result := mul(uUNIT, sub(4, 18)) }
case 100000 { result := mul(uUNIT, sub(5, 18)) }
case 1000000 { result := mul(uUNIT, sub(6, 18)) }
case 10000000 { result := mul(uUNIT, sub(7, 18)) }
case 100000000 { result := mul(uUNIT, sub(8, 18)) }
case 1000000000 { result := mul(uUNIT, sub(9, 18)) }
case 10000000000 { result := mul(uUNIT, sub(10, 18)) }
case 100000000000 { result := mul(uUNIT, sub(11, 18)) }
case 1000000000000 { result := mul(uUNIT, sub(12, 18)) }
case 10000000000000 { result := mul(uUNIT, sub(13, 18)) }
case 100000000000000 { result := mul(uUNIT, sub(14, 18)) }
case 1000000000000000 { result := mul(uUNIT, sub(15, 18)) }
case 10000000000000000 { result := mul(uUNIT, sub(16, 18)) }
case 100000000000000000 { result := mul(uUNIT, sub(17, 18)) }
case 1000000000000000000 { result := 0 }
case 10000000000000000000 { result := uUNIT }
case 100000000000000000000 { result := mul(uUNIT, 2) }
case 1000000000000000000000 { result := mul(uUNIT, 3) }
case 10000000000000000000000 { result := mul(uUNIT, 4) }
case 100000000000000000000000 { result := mul(uUNIT, 5) }
case 1000000000000000000000000 { result := mul(uUNIT, 6) }
case 10000000000000000000000000 { result := mul(uUNIT, 7) }
case 100000000000000000000000000 { result := mul(uUNIT, 8) }
case 1000000000000000000000000000 { result := mul(uUNIT, 9) }
case 10000000000000000000000000000 { result := mul(uUNIT, 10) }
case 100000000000000000000000000000 { result := mul(uUNIT, 11) }
case 1000000000000000000000000000000 { result := mul(uUNIT, 12) }
case 10000000000000000000000000000000 { result := mul(uUNIT, 13) }
case 100000000000000000000000000000000 { result := mul(uUNIT, 14) }
case 1000000000000000000000000000000000 { result := mul(uUNIT, 15) }
case 10000000000000000000000000000000000 { result := mul(uUNIT, 16) }
case 100000000000000000000000000000000000 { result := mul(uUNIT, 17) }
case 1000000000000000000000000000000000000 { result := mul(uUNIT, 18) }
case 10000000000000000000000000000000000000 { result := mul(uUNIT, 19) }
case 100000000000000000000000000000000000000 { result := mul(uUNIT, 20) }
case 1000000000000000000000000000000000000000 { result := mul(uUNIT, 21) }
case 10000000000000000000000000000000000000000 { result := mul(uUNIT, 22) }
case 100000000000000000000000000000000000000000 { result := mul(uUNIT, 23) }
case 1000000000000000000000000000000000000000000 { result := mul(uUNIT, 24) }
case 10000000000000000000000000000000000000000000 { result := mul(uUNIT, 25) }
case 100000000000000000000000000000000000000000000 { result := mul(uUNIT, 26) }
case 1000000000000000000000000000000000000000000000 { result := mul(uUNIT, 27) }
case 10000000000000000000000000000000000000000000000 { result := mul(uUNIT, 28) }
case 100000000000000000000000000000000000000000000000 { result := mul(uUNIT, 29) }
case 1000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 30) }
case 10000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 31) }
case 100000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 32) }
case 1000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 33) }
case 10000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 34) }
case 100000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 35) }
case 1000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 36) }
case 10000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 37) }
case 100000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 38) }
case 1000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 39) }
case 10000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 40) }
case 100000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 41) }
case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 42) }
case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 43) }
case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 44) }
case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 45) }
case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 46) }
case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 47) }
case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 48) }
case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 49) }
case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 50) }
case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 51) }
case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 52) }
case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 53) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 54) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 55) }
case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 56) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 57) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 58) }
case 100000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 59) }
default { result := uMAX_UD60x18 }
}
if (result.unwrap() == uMAX_UD60x18) {
unchecked {
// Inline the fixed-point division to save gas.
result = wrap(log2(x).unwrap() * uUNIT / uLOG2_10);
}
}
}
/// @notice Calculates the binary logarithm of x using the iterative approximation algorithm:
///
/// $$
/// log_2{x} = n + log_2{y}, \text{ where } y = x*2^{-n}, \ y \in [1, 2)
/// $$
///
/// For $0 \leq x \lt 1$, the input is inverted:
///
/// $$
/// log_2{x} = -log_2{\frac{1}{x}}
/// $$
///
/// @dev See https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation
///
/// Notes:
/// - Due to the lossy precision of the iterative approximation, the results are not perfectly accurate to the last decimal.
///
/// Requirements:
/// - x ≥ UNIT
///
/// @param x The UD60x18 number for which to calculate the binary logarithm.
/// @return result The binary logarithm as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function log2(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
if (xUint < uUNIT) {
revert Errors.PRBMath_UD60x18_Log_InputTooSmall(x);
}
unchecked {
// Calculate the integer part of the logarithm.
uint256 n = Common.msb(xUint / uUNIT);
// This is the integer part of the logarithm as a UD60x18 number. The operation can't overflow because n
// n is at most 255 and UNIT is 1e18.
uint256 resultUint = n * uUNIT;
// Calculate $y = x * 2^{-n}$.
uint256 y = xUint >> n;
// If y is the unit number, the fractional part is zero.
if (y == uUNIT) {
return wrap(resultUint);
}
// Calculate the fractional part via the iterative approximation.
// The `delta >>= 1` part is equivalent to `delta /= 2`, but shifting bits is more gas efficient.
uint256 DOUBLE_UNIT = 2e18;
for (uint256 delta = uHALF_UNIT; delta > 0; delta >>= 1) {
y = (y * y) / uUNIT;
// Is y^2 >= 2e18 and so in the range [2e18, 4e18)?
if (y >= DOUBLE_UNIT) {
// Add the 2^{-m} factor to the logarithm.
resultUint += delta;
// Halve y, which corresponds to z/2 in the Wikipedia article.
y >>= 1;
}
}
result = wrap(resultUint);
}
}
/// @notice Multiplies two UD60x18 numbers together, returning a new UD60x18 number.
///
/// @dev Uses {Common.mulDiv} to enable overflow-safe multiplication and division.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv}.
///
/// Requirements:
/// - Refer to the requirements in {Common.mulDiv}.
///
/// @dev See the documentation in {Common.mulDiv18}.
/// @param x The multiplicand as a UD60x18 number.
/// @param y The multiplier as a UD60x18 number.
/// @return result The product as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function mul(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(Common.mulDiv18(x.unwrap(), y.unwrap()));
}
/// @notice Raises x to the power of y.
///
/// For $1 \leq x \leq \infty$, the following standard formula is used:
///
/// $$
/// x^y = 2^{log_2{x} * y}
/// $$
///
/// For $0 \leq x \lt 1$, since the unsigned {log2} is undefined, an equivalent formula is used:
///
/// $$
/// i = \frac{1}{x}
/// w = 2^{log_2{i} * y}
/// x^y = \frac{1}{w}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {log2} and {mul}.
/// - Returns `UNIT` for 0^0.
/// - It may not perform well with very small values of x. Consider using SD59x18 as an alternative.
///
/// Requirements:
/// - Refer to the requirements in {exp2}, {log2}, and {mul}.
///
/// @param x The base as a UD60x18 number.
/// @param y The exponent as a UD60x18 number.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function pow(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
uint256 yUint = y.unwrap();
// If both x and y are zero, the result is `UNIT`. If just x is zero, the result is always zero.
if (xUint == 0) {
return yUint == 0 ? UNIT : ZERO;
}
// If x is `UNIT`, the result is always `UNIT`.
else if (xUint == uUNIT) {
return UNIT;
}
// If y is zero, the result is always `UNIT`.
if (yUint == 0) {
return UNIT;
}
// If y is `UNIT`, the result is always x.
else if (yUint == uUNIT) {
return x;
}
// If x is > UNIT, use the standard formula.
if (xUint > uUNIT) {
result = exp2(mul(log2(x), y));
}
// Conversely, if x < UNIT, use the equivalent formula.
else {
UD60x18 i = wrap(uUNIT_SQUARED / xUint);
UD60x18 w = exp2(mul(log2(i), y));
result = wrap(uUNIT_SQUARED / w.unwrap());
}
}
/// @notice Raises x (a UD60x18 number) to the power y (an unsigned basic integer) using the well-known
/// algorithm "exponentiation by squaring".
///
/// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv18}.
/// - Returns `UNIT` for 0^0.
///
/// Requirements:
/// - The result must fit in UD60x18.
///
/// @param x The base as a UD60x18 number.
/// @param y The exponent as a uint256.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function powu(UD60x18 x, uint256 y) pure returns (UD60x18 result) {
// Calculate the first iteration of the loop in advance.
uint256 xUint = x.unwrap();
uint256 resultUint = y & 1 > 0 ? xUint : uUNIT;
// Equivalent to `for(y /= 2; y > 0; y /= 2)`.
for (y >>= 1; y > 0; y >>= 1) {
xUint = Common.mulDiv18(xUint, xUint);
// Equivalent to `y % 2 == 1`.
if (y & 1 > 0) {
resultUint = Common.mulDiv18(resultUint, xUint);
}
}
result = wrap(resultUint);
}
/// @notice Calculates the square root of x using the Babylonian method.
///
/// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x ≤ MAX_UD60x18 / UNIT
///
/// @param x The UD60x18 number for which to calculate the square root.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function sqrt(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
unchecked {
if (xUint > uMAX_UD60x18 / uUNIT) {
revert Errors.PRBMath_UD60x18_Sqrt_Overflow(x);
}
// Multiply x by `UNIT` to account for the factor of `UNIT` picked up when multiplying two UD60x18 numbers.
// In this case, the two numbers are both the square root.
result = wrap(Common.sqrt(xUint * uUNIT));
}
}
lib/prb-math/src/ud60x18/ValueType.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Casting.sol" as Casting;
import "./Helpers.sol" as Helpers;
import "./Math.sol" as Math;
/// @notice The unsigned 60.18-decimal fixed-point number representation, which can have up to 60 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the Solidity type uint256.
/// @dev The value type is defined here so it can be imported in all other files.
type UD60x18 is uint256;
/*//////////////////////////////////////////////////////////////////////////
CASTING
//////////////////////////////////////////////////////////////////////////*/
using {
Casting.intoSD1x18,
Casting.intoSD21x18,
Casting.intoSD59x18,
Casting.intoUD2x18,
Casting.intoUD21x18,
Casting.intoUint128,
Casting.intoUint256,
Casting.intoUint40,
Casting.unwrap
} for UD60x18 global;
/*//////////////////////////////////////////////////////////////////////////
MATHEMATICAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
// The global "using for" directive makes the functions in this library callable on the UD60x18 type.
using {
Math.avg,
Math.ceil,
Math.div,
Math.exp,
Math.exp2,
Math.floor,
Math.frac,
Math.gm,
Math.inv,
Math.ln,
Math.log10,
Math.log2,
Math.mul,
Math.pow,
Math.powu,
Math.sqrt
} for UD60x18 global;
/*//////////////////////////////////////////////////////////////////////////
HELPER FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
// The global "using for" directive makes the functions in this library callable on the UD60x18 type.
using {
Helpers.add,
Helpers.and,
Helpers.eq,
Helpers.gt,
Helpers.gte,
Helpers.isZero,
Helpers.lshift,
Helpers.lt,
Helpers.lte,
Helpers.mod,
Helpers.neq,
Helpers.not,
Helpers.or,
Helpers.rshift,
Helpers.sub,
Helpers.uncheckedAdd,
Helpers.uncheckedSub,
Helpers.xor
} for UD60x18 global;
/*//////////////////////////////////////////////////////////////////////////
OPERATORS
//////////////////////////////////////////////////////////////////////////*/
// The global "using for" directive makes it possible to use these operators on the UD60x18 type.
using {
Helpers.add as +,
Helpers.and2 as &,
Math.div as /,
Helpers.eq as ==,
Helpers.gt as >,
Helpers.gte as >=,
Helpers.lt as <,
Helpers.lte as <=,
Helpers.or as |,
Helpers.mod as %,
Math.mul as *,
Helpers.neq as !=,
Helpers.not as ~,
Helpers.sub as -,
Helpers.xor as ^
} for UD60x18 global;
src/interfaces/ILVToken.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
interface ILVToken {
// Standard ERC20 functions
function transfer(address recipient, uint256 amount) external returns (bool);
function balanceOf(address account) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
// Additional functions for collateral token management
function mint(address account, uint256 amount) external returns (bool);
function burn(address from, uint256 amount) external returns (bool);
}
src/interfaces/ILiquidationProxy.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
interface ILiquidationProxy {
function setAllowKick(bool _allowKick) external;
function allowKick() external view returns (bool);
}
src/interfaces/IMorpho.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IMorpho
/// @notice Interface for Morpho Blue flash loan functionality
interface IMorpho {
/// @notice Executes a flash loan
/// @param token The address of the token to borrow
/// @param assets The amount of assets to borrow
/// @param data Arbitrary data to pass to the callback
function flashLoan(address token, uint256 assets, bytes calldata data) external;
}
src/interfaces/IMorphoCallbacks.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IMorphoFlashLoanCallback
/// @notice Interface for contracts that want to receive Morpho Blue flash loans
interface IMorphoFlashLoanCallback {
/// @notice Callback function called by Morpho during a flash loan
/// @param assets The amount of assets that were flash loaned
/// @param data Arbitrary data passed from the flash loan initiator
/// @dev The contract must approve Morpho to spend `assets` amount of the borrowed token
/// @dev Morpho will pull the funds after this callback completes
function onMorphoFlashLoan(uint256 assets, bytes calldata data) external;
}
src/interfaces/IPoolDataProvider.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title IPoolDataProvider
* @author Aave
* @notice Defines the basic interface of a PoolDataProvider
*/
interface IPoolDataProvider {
/**
* @notice Returns the reserve data
* @param asset The address of the underlying asset of the reserve
* @return unbacked The amount of unbacked tokens
* @return accruedToTreasuryScaled The scaled amount of tokens accrued to treasury that is to be minted
* @return totalAToken The total supply of the aToken
* @return totalStableDebt The total stable debt of the reserve
* @return totalVariableDebt The total variable debt of the reserve
* @return liquidityRate The liquidity rate of the reserve
* @return variableBorrowRate The variable borrow rate of the reserve
* @return stableBorrowRate The stable borrow rate of the reserve
* @return averageStableBorrowRate The average stable borrow rate of the reserve
* @return liquidityIndex The liquidity index of the reserve
* @return variableBorrowIndex The variable borrow index of the reserve
* @return lastUpdateTimestamp The timestamp of the last update of the reserve
*/
function getReserveData(
address asset
)
external
view
returns (
uint256 unbacked,
uint256 accruedToTreasuryScaled,
uint256 totalAToken,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 stableBorrowRate,
uint256 averageStableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
uint40 lastUpdateTimestamp
);
}src/interfaces/IPoolInfoUtils.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
/**
* @title Pool Info Utils contract
* @notice Contract for providing information for any deployed pool.
* @dev Pool info is calculated using same helper functions / logic as in `Pool` contracts.
*/
interface IPoolInfoUtils {
/**
* @notice Exposes status of a liquidation auction.
* @param ajnaPool_ Address of `Ajna` pool.
* @param borrower_ Identifies the loan being liquidated.
* @return kickTime_ Time auction was kicked, implying end time.
* @return collateral_ Remaining collateral available to be purchased. (`WAD`)
* @return debtToCover_ Borrower debt to be covered. (`WAD`)
* @return isCollateralized_ `True` if loan is collateralized.
* @return price_ Current price of the auction. (`WAD`)
* @return neutralPrice_ Price at which bond holder is neither rewarded nor penalized. (`WAD`)
* @return referencePrice_ Price used to determine auction start price. (`WAD`)
* @return debtToCollateral_ Borrower debt to collateral at time of kick. (`WAD`)
* @return bondFactor_ The factor used for calculating bond size. (`WAD`)
*/
function auctionStatus(address ajnaPool_, address borrower_)
external
view
returns (
uint256 kickTime_,
uint256 collateral_,
uint256 debtToCover_,
bool isCollateralized_,
uint256 price_,
uint256 neutralPrice_,
uint256 referencePrice_,
uint256 debtToCollateral_,
uint256 bondFactor_
);
/**
* @notice Returns details of an auction for a given borrower address.
* @dev Calls and returns all values from pool.auctionInfo().
* @param ajnaPool_ Address of `Ajna` pool.
* @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 at time of kick, 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 ajnaPool_, 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 Retrieves info of a given borrower in a given `Ajna` pool.
* @param ajnaPool_ Address of `Ajna` pool.
* @param borrower_ Borrower's address.
* @return debt_ Current debt owed by borrower (`WAD`).
* @return collateral_ Pledged collateral, including encumbered (`WAD`).
* @return t0Np_ `Neutral price` (`WAD`).
* @return thresholdPrice_ Borrower's `Threshold Price` (`WAD`).
*/
function borrowerInfo(address ajnaPool_, address borrower_)
external
view
returns (uint256 debt_, uint256 collateral_, uint256 t0Np_, uint256 thresholdPrice_);
/**
* @notice Get a bucket struct for a given index.
* @param ajnaPool_ Address of `Ajna` pool.
* @param index_ The index of the bucket to retrieve.
* @return price_ Bucket's price (`WAD`).
* @return quoteTokens_ Amount of quote token in bucket, `deposit + interest` (`WAD`).
* @return collateral_ Unencumbered collateral in bucket (`WAD`).
* @return bucketLP_ Outstanding `LP` balance in bucket (`WAD`).
* @return scale_ Lender interest multiplier (`WAD`).
* @return exchangeRate_ The exchange rate of the bucket, in `WAD` units.
*/
function bucketInfo(address ajnaPool_, uint256 index_)
external
view
returns (
uint256 price_,
uint256 quoteTokens_,
uint256 collateral_,
uint256 bucketLP_,
uint256 scale_,
uint256 exchangeRate_
);
/**
* @notice Returns info related to pool loans.
* @param ajnaPool_ Address of `Ajna` pool.
* @return poolSize_ The total amount of quote tokens in pool (`WAD`).
* @return loansCount_ The number of loans in pool.
* @return maxBorrower_ The address with the highest `TP` in pool.
* @return pendingInflator_ Pending inflator in pool.
* @return pendingInterestFactor_ Factor used to scale the inflator.
*/
function poolLoansInfo(address ajnaPool_)
external
view
returns (
uint256 poolSize_,
uint256 loansCount_,
address maxBorrower_,
uint256 pendingInflator_,
uint256 pendingInterestFactor_
);
/**
* @notice Returns info related to pool prices.
* @param ajnaPool_ Address of `Ajna` pool.
* @return hpb_ The price value of the current `Highest Price Bucket` (`HPB`), in `WAD` units.
* @return hpbIndex_ The index of the current `Highest Price Bucket` (`HPB`), in `WAD` units.
* @return htp_ The price value of the current `Highest Threshold Price` (`HTP`) bucket, in `WAD` units.
* @return htpIndex_ The index of the current `Highest Threshold Price` (`HTP`) bucket, in `WAD` units.
* @return lup_ The price value of the current `Lowest Utilized Price` (LUP) bucket, in `WAD` units.
* @return lupIndex_ The index of the current `Lowest Utilized Price` (`LUP`) bucket, in `WAD` units.
*/
function poolPricesInfo(address ajnaPool_)
external
view
returns (uint256 hpb_, uint256 hpbIndex_, uint256 htp_, uint256 htpIndex_, uint256 lup_, uint256 lupIndex_);
/**
* @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).
* @param ajnaPool_ Address of `Ajna` pool.
* @return amount_ The total quote token amount available to borrow or to be removed from pool, in `WAD` units.
*/
function availableQuoteTokenAmount(address ajnaPool_) external view returns (uint256 amount_);
/**
* @notice Returns info related to `Claimaible Reserve Auction`.
* @param ajnaPool_ Address of `Ajna` pool.
* @return reserves_ The amount of excess quote tokens.
* @return claimableReserves_ Denominated in quote token, or `0` if no reserves can be auctioned.
* @return claimableReservesRemaining_ Amount of claimable reserves which has not yet been taken.
* @return auctionPrice_ Current price at which `1` quote token may be purchased, denominated in `Ajna`.
* @return timeRemaining_ Seconds remaining before takes are no longer allowed.
*/
function poolReservesInfo(address ajnaPool_)
external
view
returns (
uint256 reserves_,
uint256 claimableReserves_,
uint256 claimableReservesRemaining_,
uint256 auctionPrice_,
uint256 timeRemaining_
);
/**
* @notice Returns info related to pool utilization.
* @param ajnaPool_ Address of `Ajna` pool.
* @return poolMinDebtAmount_ Minimum debt amount.
* @return poolCollateralization_ Current pool collateralization ratio.
* @return poolActualUtilization_ The current pool actual utilization, in `WAD` units.
* @return poolTargetUtilization_ The current pool Target utilization, in `WAD` units.
*/
function poolUtilizationInfo(address ajnaPool_)
external
view
returns (
uint256 poolMinDebtAmount_,
uint256 poolCollateralization_,
uint256 poolActualUtilization_,
uint256 poolTargetUtilization_
);
/**
* @notice Returns the proportion of interest rate which is awarded to lenders;
* the remainder accumulates in reserves.
* @param ajnaPool_ Address of `Ajna` pool.
* @return lenderInterestMargin_ Lender interest margin in pool.
*/
function lenderInterestMargin(address ajnaPool_) external view returns (uint256 lenderInterestMargin_);
/**
* @notice Returns bucket price for a given bucket index.
*/
function indexToPrice(uint256 index_) external pure returns (uint256);
/**
* @notice Returns bucket index for a given bucket price.
*/
function priceToIndex(uint256 price_) external pure returns (uint256);
/**
* @notice Returns current `LUP` for a given pool.
*/
function lup(address ajnaPool_) external view returns (uint256);
/**
* @notice Returns current `LUP` index for a given pool.
*/
function lupIndex(address ajnaPool_) external view returns (uint256);
/**
* @notice Returns current `HPB` for a given pool.
*/
function hpb(address ajnaPool_) external view returns (uint256);
/**
* @notice Returns current `HPB` index for a given pool.
*/
function hpbIndex(address ajnaPool_) external view returns (uint256);
/**
* @notice Returns current `HTP` for a given pool.
*/
function htp(address ajnaPool_) external view returns (uint256 htp_);
/**
* @notice Calculates origination fee rate for a pool.
* @notice Calculated as greater of the current annualized interest rate divided by `52` (one week of interest) or `5` bps.
* @return Fee rate calculated from the pool interest rate.
*/
function borrowFeeRate(address ajnaPool_) external view returns (uint256);
/**
* @notice Calculates deposit fee rate for a pool.
* @notice Calculated as current annualized rate divided by 365 * 3 (8 hours of interest)
* @return Fee rate calculated from the pool interest rate.
*/
function depositFeeRate(address ajnaPool_) external view returns (uint256);
/**
* @notice Calculate the amount of quote tokens in bucket for a given amount of `LP`.
* @param lp_ The number of `LP` to calculate amounts for.
* @param index_ The price bucket index for which the value should be calculated.
* @return quoteAmount_ The exact amount of quote tokens that can be exchanged for the given `LP`, `WAD` units.
*/
function lpToQuoteTokens(address ajnaPool_, uint256 lp_, uint256 index_)
external
view
returns (uint256 quoteAmount_);
/**
* @notice Calculate the amount of collateral tokens in bucket for a given amount of `LP`.
* @param lp_ The number of `LP` to calculate amounts for.
* @param index_ The price bucket index for which the value should be calculated.
* @return collateralAmount_ The exact amount of collateral tokens that can be exchanged for the given `LP`, `WAD` units.
*/
function lpToCollateral(address ajnaPool_, uint256 lp_, uint256 index_)
external
view
returns (uint256 collateralAmount_);
}
// /**********************/
// /*** Pool Utilities ***/
// /**********************/
// /**
// * @notice Calculates encumberance for a debt amount at a given price.
// * @param debt_ The debt amount to calculate encumberance for.
// * @param price_ The price to calculate encumberance at.
// * @return encumberance_ Encumberance value.
// */
// function _encumberance(
// uint256 debt_,
// uint256 price_
// ) pure returns (uint256 encumberance_) {
// return price_ != 0 ? Maths.wdiv(Maths.wmul(COLLATERALIZATION_FACTOR , debt_), price_) : 0;
// }
// /**
// * @notice Calculates collateralization for a given debt and collateral amounts, at a given price.
// * @param debt_ The debt amount.
// * @param collateral_ The collateral amount.
// * @param price_ The price to calculate collateralization at.
// * @return Collateralization value. `1 WAD` if debt amount is `0`.
// */
// function _collateralization(
// uint256 debt_,
// uint256 collateral_,
// uint256 price_
// ) pure returns (uint256) {
// // cannot be undercollateralized if there is no debt
// if (debt_ == 0) return 1e18;
// // borrower is undercollateralized when lup at MIN_PRICE
// if (price_ == MIN_PRICE) return 0;
// return Maths.wdiv(Maths.wmul(collateral_, price_), Maths.wmul(COLLATERALIZATION_FACTOR, debt_));
// }
// /**
// * @notice Calculates target utilization for given `EMA` values.
// * @param debtColEma_ The `EMA` of debt squared to collateral.
// * @param lupt0DebtEma_ The `EMA` of `LUP * t0 debt`.
// * @return Target utilization of the pool.
// */
// function _targetUtilization(
// uint256 debtColEma_,
// uint256 lupt0DebtEma_
// ) pure returns (uint256) {
// return (lupt0DebtEma_ != 0) ? Maths.wdiv(debtColEma_, lupt0DebtEma_) : Maths.WAD;
// }
src/interfaces/pool/IERC3156FlashBorrower.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity 0.8.20;
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);
}
src/interfaces/pool/IERC3156FlashLender.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity 0.8.20;
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);
}
src/interfaces/pool/IPool.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity 0.8.20;
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;
}
src/interfaces/pool/commons/IPoolBorrowerActions.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity 0.8.20;
/**
* @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;
}
src/interfaces/pool/commons/IPoolDerivedState.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity 0.8.20;
/**
* @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);
}
src/interfaces/pool/commons/IPoolErrors.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity 0.8.20;
/**
* @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();
}
src/interfaces/pool/commons/IPoolEvents.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity 0.8.20;
/**
* @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();
}
src/interfaces/pool/commons/IPoolImmutables.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity 0.8.20;
/**
* @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);
}
src/interfaces/pool/commons/IPoolKickerActions.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity 0.8.20;
/**
* @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;
}
src/interfaces/pool/commons/IPoolLPActions.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity 0.8.20;
/**
* @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;
}
src/interfaces/pool/commons/IPoolLenderActions.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity 0.8.20;
/**
* @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;
}
src/interfaces/pool/commons/IPoolSettlerActions.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity 0.8.20;
/**
* @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_);
}
src/interfaces/pool/commons/IPoolState.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity 0.8.20;
/**
* @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 => uint256) 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
}
src/interfaces/pool/commons/IPoolTakerActions.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity 0.8.20;
/**
* @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_);
}
src/interfaces/pool/erc20/IERC20Pool.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity 0.8.20;
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);
}
src/interfaces/pool/erc20/IERC20PoolBorrowerActions.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity 0.8.20;
/**
* @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_);
}
src/interfaces/pool/erc20/IERC20PoolEvents.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity 0.8.20;
/**
* @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);
}
src/interfaces/pool/erc20/IERC20PoolImmutables.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity 0.8.20;
/**
* @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);
}
src/interfaces/pool/erc20/IERC20PoolLenderActions.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity 0.8.20;
/**
* @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_);
}
src/interfaces/vault/ILidoWithdrawal.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
interface ILidoWithdrawal {
// @notice Handles withdrawal request finalization and ETH locking. Requests can be nominal (1:1) or discounted based on share rate.
struct BatchesCalculationState {
uint256 remainingEthBudget;
bool finished;
uint256[36] batches;
uint256 batchesLength;
}
function requestWithdrawalsWstETH(uint256[] calldata _amounts, address _owner)
external
returns (uint256[] memory requestIds);
function claimWithdrawal(uint256 _requestId) external;
function getClaimableEther(uint256[] calldata _requestIds, uint256[] calldata _hints)
external
view
returns (uint256[] memory claimableEthValues);
function getLastCheckpointIndex() external view returns (uint256);
function findCheckpointHints(uint256[] calldata _requestIds, uint256 _firstIndex, uint256 _lastIndex)
external
view
returns (uint256[] memory hintIds);
function finalize(uint256 _lastRequestIdToBeFinalized, uint256 _maxShareRate) external payable;
function prefinalize(uint256[] calldata _batches, uint256 _maxShareRate)
external
view
returns (uint256 ethToLock, uint256 sharesToBurn);
function calculateFinalizationBatches(
uint256 _maxShareRate,
uint256 _maxTimestamp,
uint256 _maxRequestsPerCall,
BatchesCalculationState memory _state
) external view returns (BatchesCalculationState memory);
}
src/interfaces/vault/ISteth.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity 0.8.20;
interface ISteth {
/**
* @notice Allows a user to deposit Ether and receive stETH in return.
* @param _referral The address of the referral (if any) for the deposit.
* @return The amount of stETH minted for the deposited Ether.
*/
function submit(address _referral) external payable returns (uint256);
/**
* @return the amount of Ether that corresponds to `_sharesAmount` token shares.
*/
function getPooledEthByShares(uint256 _sharesAmount) external view returns (uint256);
}
src/interfaces/vault/IWeth.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
interface IWeth {
function withdraw(uint256 amount) external;
function deposit() external payable;
}
src/interfaces/vault/IWsteth.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
interface IWsteth {
/**
* @notice Returns the amount of stETH that corresponds to one wstETH.
* @dev The value increases over time as staking rewards accumulate.
* @return The amount of stETH per one wstETH, scaled to 18 decimals.
*/
function stEthPerToken() external view returns (uint256);
/**
* @notice Returns the amount of wstETH that corresponds to one stETH.
* @dev This value decreases over time as staking rewards accumulate.
* @return The amount of wstETH per one stETH, scaled to 18 decimals.
*/
function tokensPerStEth() external view returns (uint256);
/**
* @notice Wraps stETH into wstETH.
* @dev Transfers `stETH` from the caller and mints `wstETH` to the caller.
* @param _stETHAmount The amount of stETH to wrap.
* @return The amount of wstETH minted.
*/
function wrap(uint256 _stETHAmount) external returns (uint256);
/**
* @notice Returns the balance of the account.
* @param account The address of the account.
* @return The balance of the account.
*/
function balanceOf(address account) external view returns (uint256);
}
src/libraries/VaultLib.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
import {ILidoWithdrawal} from "../interfaces/vault/ILidoWithdrawal.sol";
/**
* @title VaultLib
*/
library VaultLib {
struct LenderOrder {
address lender;
uint256 quoteAmount;
uint256 vaultShares;
}
struct BorrowerOrder {
address borrower;
uint256 collateralAmount;
}
struct CollateralLenderOrder {
address collateralLender;
uint256 collateralAmount;
}
struct MatchInfo {
address lender;
address borrower;
uint256 quoteAmount; // 97%
uint256 collateralAmount;
uint256 reservedQuoteAmount; // 3%
}
address public constant QUOTE_TOKEN = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant COLLATERAL_TOKEN = 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0;
address public constant STETH_ADDRESS = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84;
ILidoWithdrawal public constant LIDO_WITHDRAWAL = ILidoWithdrawal(0x889edC2eDab5f40e902b864aD4d7AdE8E412F9B1);
address public constant router = 0x65Dcc24F8ff9e51F10DCc7Ed1e4e2A61e6E14bd6;
bytes32 public constant donId = 0x66756e2d657468657265756d2d6d61696e6e65742d3100000000000000000000;
uint256 public constant leverageFactor = 10;
/* EVENTS */
event EndEpoch(uint256 time);
event TermEnded(uint256 time);
event FundsQueued(uint256 requestId, uint256 collateralAmount);
event FundsClaimed(uint256 requestId, uint256 amount);
event FundsAdded(uint256 ethAmount, uint256 contractBalance, address sender);
event ForwarderAddressUpdated(address oldAddress, address newAddress);
event AvoidLiquidation(uint256 collateralAmount);
event EpochStarted(uint256 epoch, uint256 epochStart, uint256 termEnd);
event RedemptionRateUpdated(uint256 redemptionRate);
event OCRResponse(bytes32 indexed requestId, bytes response, uint256 rate, bytes err);
event RequestRevertedWithErrorMsg(string reason);
event RequestRevertedWithoutErrorMsg(bytes data);
event LVLidoVaultUtilAddressUpdated(address oldAddress, address newAddress);
event LoanComposition(
uint256 baseCollateral, uint256 leveragedCollateral, uint256 totalCollateral, uint256 quoteToBorrow
);
event AmountsOwed(uint256 lendersOwed, uint256 borrowersOwed, uint256 collateralLendersOwed);
// ------------------------------------------------------------
// Confirmed to be used
event LenderOrderAdded(address lender, uint256 quoteAmount);
event BorrowerOrderAdded(address borrower, uint256 collateralAmount);
event CollateralLenderDeposit(address collateralLender, uint256 collateralAmount);
event WithdrawLender(address lender, uint256 quoteAmount);
event WithdrawBorrower(address borrower, uint256 collateralAmount);
event WithdrawCollateralLender(address collateralLender, uint256 collateralAmount);
event EpochInterestEarned(
uint256 epochNumber,
uint256 lendersInterestAccrued,
uint256 borrowersInterestAccrued,
uint256 collateralLendersInterestAccrued
);
/* Errors */
error InsufficientFunds();
error Unauthorized();
error OnlyForwarder();
error OnlyProxy();
error ReentrantCall();
error InvalidInput();
error NoETHToClaim();
error NoUnfilledOrdersFound();
error MaxFundsExceeded();
error TokenOperationFailed();
error LockedBonds();
// ------------------------------------------------------------
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "shanghai",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"@chainlink/contracts/=lib/chainlink/contracts/",
"forge-std/=lib/forge-std/src/",
"@balancer/=lib/balancer-v2-monorepo/pkg/interfaces/contracts/",
"@prb/math/=lib/prb-math/src/",
"@balancer-labs/=lib/balancer-v2-monorepo/../../node_modules/@balancer-labs/",
"balancer-v2-monorepo/=lib/balancer-v2-monorepo/",
"chainlink/=lib/chainlink/",
"ds-test/=lib/balancer-v2-monorepo/../../pvt/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"prb-math/=lib/prb-math/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.