Verified contractExactGPL-2.0-or-later
Lotus
Address0x214fb708c3fd648720ba2e82dbdc6a21beb28a0a
- Balance
0 ETH
- Transactions
12
- Compiler
solc 0.8.28
- Same code
2 more contracts
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- GPL-2.0-or-later
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,429,729
- Creation transaction
- 0x64702af063…ba255e1dfa
21 files
- src/Lotus.solmain62.94 KB
- lib/solady/src/utils/FixedPointMathLib.sol55.69 KB
- lib/solady/src/utils/ReentrancyGuardTransient.sol4.8 KB
- lib/solady/src/utils/SafeCastLib.sol23.8 KB
- lib/solady/src/utils/SafeTransferLib.sol32.86 KB
- src/access/TwoStepOwnable.sol3.72 KB
- src/hooks/interfaces/ILotusHooks.sol5.49 KB
- src/hooks/libraries/Hooks.sol5.95 KB
- src/interfaces/ILiquidationModule.sol2.89 KB
- src/interfaces/ILotus.sol32.2 KB
- src/interfaces/ILotusCallbacks.sol3.35 KB
- src/interfaces/IOracle.sol861 B
- src/interfaces/IRiskEngine.sol4.36 KB
- src/libraries/ConstantsLib.sol3.02 KB
- src/libraries/InterestMathLib.sol1.34 KB
- src/libraries/LotusErrorsLib.sol9.01 KB
- src/libraries/LotusEventsLib.sol9.1 KB
- src/libraries/LotusExternalLib.sol13.89 KB
- src/libraries/MarketParamsLib.sol1.06 KB
- src/libraries/SharesMathLib.sol2.42 KB
- src/libraries/UtilsLib.sol576 B
src/Lotus.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Adapted in part from Morpho Blue. Modified by Lotus DeFi Labs, Inc. through November 2026.
pragma solidity ^0.8.28;
import {FixedPointMathLib} from "solady/src/utils/FixedPointMathLib.sol";
import {SafeTransferLib} from "solady/src/utils/SafeTransferLib.sol";
import {SafeCastLib} from "solady/src/utils/SafeCastLib.sol";
import {ReentrancyGuardTransient} from "solady/src/utils/ReentrancyGuardTransient.sol";
import {AccrualDelta, BadDebtDeltas, IRiskEngine} from "./interfaces/IRiskEngine.sol";
import {
Id,
ILotus,
MarketParams,
TrancheConfig,
Position,
Tranche,
Authorization,
Signature
} from "./interfaces/ILotus.sol";
import {
ILotusSupplyCallback,
ILotusFlashLoanCallback,
ILotusSupplyCollateralCallback,
ILotusRepayCallback
} from "./interfaces/ILotusCallbacks.sol";
import {ILiquidationModule, LiquidationQuoteContext} from "./interfaces/ILiquidationModule.sol";
import {IOracle} from "./interfaces/IOracle.sol";
import {ILotusHooks} from "./hooks/interfaces/ILotusHooks.sol";
import {Hooks} from "./hooks/libraries/Hooks.sol";
import {
WAD,
ORACLE_PRICE_SCALE,
MAX_FEE,
MAX_BORROW_RATE_PER_SECOND,
MIN_PARTIAL_REPAY_ASSETS,
MIN_COOLDOWN_DURATION,
MAX_COOLDOWN_DURATION,
MIN_BORROW_LTV_BUFFER,
MAX_BORROW_LTV_BUFFER,
DOMAIN_TYPEHASH
} from "./libraries/ConstantsLib.sol";
import {InterestMathLib} from "./libraries/InterestMathLib.sol";
import {LotusErrorsLib} from "./libraries/LotusErrorsLib.sol";
import {LotusEventsLib} from "./libraries/LotusEventsLib.sol";
import {LotusExternalLib} from "./libraries/LotusExternalLib.sol";
import {MarketParamsLib} from "./libraries/MarketParamsLib.sol";
import {SharesMathLib} from "./libraries/SharesMathLib.sol";
import {UtilsLib} from "./libraries/UtilsLib.sol";
import {TwoStepOwnable} from "./access/TwoStepOwnable.sol";
/// @title Lotus
/// @notice Core Lotus lending protocol implementation.
contract Lotus is TwoStepOwnable, ILotus, ReentrancyGuardTransient {
using SharesMathLib for uint256;
using SafeCastLib for uint256;
using FixedPointMathLib for uint256;
using MarketParamsLib for MarketParams;
/// @dev Derived from: `uint32(bytes4(keccak256("RiskEngineCallReentrancy()"))) | 1 << 71`.
/// @dev 9 bytes is large enough to avoid collisions in practice without excessive bytecode bloat.
uint256 private constant _RISK_ENGINE_CALL_GUARD_SLOT = 0x8000000000c608db4f;
/* IMMUTABLES */
/// @inheritdoc ILotus
bytes32 public immutable DOMAIN_SEPARATOR;
/// @inheritdoc ILotus
uint256 public immutable MIN_BORROW_DURATION;
/// @inheritdoc ILotus
uint256 public immutable FULL_COOLDOWN_BAD_DEBT_RATIO;
/* STORAGE */
/// @inheritdoc ILotus
address public feeRecipient;
/// @inheritdoc ILotus
/// @dev Packed into the `feeRecipient` slot.
uint64 public borrowLtvBuffer;
/// @inheritdoc ILotus
mapping(address token => uint64) public flashLoanFee;
/// @inheritdoc ILotus
mapping(address riskEngine => bool) public isRiskEngineEnabled;
/// @inheritdoc ILotus
mapping(uint256 lltv => bool) public isLltvEnabled;
/// @inheritdoc ILotus
mapping(address liquidationModule => bool) public isLiquidationModuleEnabled;
/// @inheritdoc ILotus
mapping(address manager => bool) public isModuleManager;
/// @inheritdoc ILotus
mapping(address authorizer => mapping(address authorized => bool)) public isAuthorized;
/// @inheritdoc ILotus
mapping(address authorizer => uint256) public nonce;
/// @inheritdoc ILotus
mapping(address account => bool) public isBorrowCooldownExempt;
/// @dev Backing storage for ILotus market parameters.
mapping(Id id => MarketParams) internal idToMarketParams;
/// @dev Tranche configuration arrays indexed by their configuration hash.
mapping(bytes32 trancheConfigsHash => TrancheConfig[]) internal _trancheConfigs;
/// @dev Backing storage for tranche state by market id.
/// @dev Tranche seniority: index 0 = most senior, higher indices = more junior.
/// @dev Bad debt may be allocated only to its origin tranche or higher-index, more-junior tranches.
/// The configured risk engine determines allocation within that eligible suffix; Lotus does not enforce a strict
/// junior-first waterfall.
mapping(Id id => Tranche[]) internal marketTranches;
/// @dev Position state indexed by market id, user, and tranche index.
mapping(Id id => mapping(address user => mapping(uint256 trancheIndex => Position))) internal _positions;
/// @dev Per-tranche repay cooldown expiry, armed by bad debt.
mapping(Id id => mapping(uint256 trancheIndex => uint64)) internal _borrowCooldownUntil;
/// @dev Backing storage for per-market hook configuration.
mapping(Id id => Hooks.HookConfig) internal marketHookConfig;
/// @dev Pause state. Storage is internal; wrapped in a struct so pause logic can DELEGATECALL
/// into `LotusExternalLib`, keeping the bulk of pause administration out of Lotus's runtime
/// bytecode.
LotusExternalLib.State internal _pause;
/* CONSTRUCTOR */
/// @param initialOwner The initial Lotus admin.
/// @param initialFeeRecipient The initial Lotus fee recipient.
/// @param minBorrowDuration Borrow-cooldown minimum position age, in [`MIN_COOLDOWN_DURATION`,
/// `MAX_COOLDOWN_DURATION`].
/// @param fullCooldownBadDebtRatio Bad-debt ratio (WAD) arming the full cooldown, in (0, `WAD`].
/// @param initialBorrowLtvBuffer Initial relative borrow buffer below each LLTV (WAD), in
/// [`MIN_BORROW_LTV_BUFFER`, `MAX_BORROW_LTV_BUFFER`].
constructor(
address initialOwner,
address initialFeeRecipient,
uint256 minBorrowDuration,
uint256 fullCooldownBadDebtRatio,
uint64 initialBorrowLtvBuffer
) {
if (initialOwner == address(0)) revert LotusErrorsLib.ZeroAddress();
if (minBorrowDuration < MIN_COOLDOWN_DURATION || minBorrowDuration > MAX_COOLDOWN_DURATION) {
revert LotusErrorsLib.InvalidBorrowCooldownConfig();
}
if (fullCooldownBadDebtRatio == 0 || fullCooldownBadDebtRatio > WAD) {
revert LotusErrorsLib.InvalidBorrowCooldownConfig();
}
DOMAIN_SEPARATOR = keccak256(abi.encode(DOMAIN_TYPEHASH, block.chainid, address(this)));
MIN_BORROW_DURATION = minBorrowDuration;
FULL_COOLDOWN_BAD_DEBT_RATIO = fullCooldownBadDebtRatio;
_initializeOwner(initialOwner);
_setFeeRecipient(initialFeeRecipient);
_setBorrowLtvBuffer(initialBorrowLtvBuffer);
}
/* MODIFIERS */
modifier onlyOwnerOrModuleManager() {
_onlyOwnerOrModuleManager();
_;
}
modifier notInRiskEngineCallWindow() {
_revertIfInRiskEngineCallWindow();
_;
}
/* OWNER FUNCTIONS */
/// @inheritdoc ILotus
function setFee(
MarketParams memory marketParams,
uint256 trancheIndex,
uint64 newFee,
bytes calldata riskEngineData
) external onlyOwner notInRiskEngineCallWindow nonReentrant {
Id id = marketParams.id();
uint256 numTranches = _validateMarket(id);
_validateTrancheIndex(trancheIndex, numTranches);
_enforceNotPaused(id);
Tranche storage tranche = marketTranches[id][trancheIndex];
if (newFee == tranche.fee) {
revert LotusErrorsLib.FeeAlreadySet(id, trancheIndex, newFee);
}
if (newFee > MAX_FEE) revert LotusErrorsLib.InvalidFee(newFee);
_accrueInterest(marketParams, id, riskEngineData);
tranche.fee = newFee;
emit LotusEventsLib.FeeUpdated(id, trancheIndex, newFee);
}
/// @inheritdoc ILotus
function setFeeRecipient(address newFeeRecipient) external onlyOwner {
if (newFeeRecipient == feeRecipient) revert LotusErrorsLib.FeeRecipientAlreadySet(newFeeRecipient);
_setFeeRecipient(newFeeRecipient);
}
/// @inheritdoc ILotus
function setBorrowLtvBuffer(uint64 newBuffer) external onlyOwner {
if (newBuffer == borrowLtvBuffer) revert LotusErrorsLib.BorrowLtvBufferAlreadySet(newBuffer);
_setBorrowLtvBuffer(newBuffer);
}
/// @inheritdoc ILotus
function setFlashLoanFee(address token, uint64 newFee) external onlyOwner {
LotusExternalLib.setFlashLoanFee(flashLoanFee, token, newFee);
}
/// @inheritdoc ILotus
function enableLltv(uint128 lltv) external onlyOwner {
LotusExternalLib.enableLltv(isLltvEnabled, lltv);
}
/// @inheritdoc ILotus
function enableModuleManager(address manager) external onlyOwner {
if (manager == address(0)) revert LotusErrorsLib.ZeroAddress();
if (isModuleManager[manager]) revert LotusErrorsLib.ModuleManagerAlreadyEnabled(manager);
isModuleManager[manager] = true;
emit LotusEventsLib.ModuleManagerEnabled(manager);
}
/// @inheritdoc ILotus
function disableModuleManager(address manager) external onlyOwner {
if (!isModuleManager[manager]) revert LotusErrorsLib.ModuleManagerNotEnabled(manager);
isModuleManager[manager] = false;
emit LotusEventsLib.ModuleManagerDisabled(manager);
}
/// @inheritdoc ILotus
function setMarketHook(MarketParams memory marketParams, address hook, uint256 permissions) external onlyOwner {
Id id = marketParams.id();
_validateMarket(id);
marketHookConfig[id] = Hooks.validateHookConfig(hook, permissions);
emit LotusEventsLib.MarketHookUpdated(id, hook, permissions);
}
/// @inheritdoc ILotus
function enableLiquidationModule(address liquidationModule) external onlyOwnerOrModuleManager {
if (liquidationModule == address(0)) revert LotusErrorsLib.ZeroAddress();
if (isLiquidationModuleEnabled[liquidationModule]) {
revert LotusErrorsLib.LiquidationModuleAlreadyEnabled(liquidationModule);
}
isLiquidationModuleEnabled[liquidationModule] = true;
emit LotusEventsLib.LiquidationModuleEnabled(liquidationModule);
}
/// @inheritdoc ILotus
function enableRiskEngine(address riskEngine) external onlyOwnerOrModuleManager {
if (riskEngine == address(0)) revert LotusErrorsLib.ZeroAddress();
if (isRiskEngineEnabled[riskEngine]) revert LotusErrorsLib.RiskEngineAlreadyEnabled(riskEngine);
isRiskEngineEnabled[riskEngine] = true;
emit LotusEventsLib.RiskEngineEnabled(riskEngine);
}
/* PAUSE FUNCTIONS */
/// @inheritdoc ILotus
/// @dev When `global` is true, halts every state-changing operation across the protocol; while
/// globally paused no per-market pause/unpause is allowed. When `global` is false, halts every
/// state-changing operation on `marketParams`'s market only. Unpausing (in either scope)
/// records the moment so the lazy per-market sync skips interest accrual over the pause window
/// (see `_enforceNotPaused`). Interest from the last pre-pause interaction up to the pause is
/// not captured by the lazy sync. Operators who need that interest realized must call
/// `accrueInterest` before pausing; it cannot be recovered during a pause, because accrual
/// reverts while paused, or after unpause, because the sync skips directly to the unpause
/// timestamp. This preserves emergency-pause availability when accrual itself depends on a
/// broken oracle or risk engine and could revert.
function setPaused(MarketParams memory marketParams, bool global, bool paused) external onlyOwner {
LotusExternalLib.setPaused(_pause, marketTranches, marketParams, global, paused);
}
/// @inheritdoc ILotus
function clearBorrowCooldown(Id id, uint256 trancheIndex) external onlyOwner {
_validateTrancheIndex(trancheIndex, marketTranches[id].length);
delete _borrowCooldownUntil[id][trancheIndex];
emit BorrowCooldownCleared(id, trancheIndex);
}
/// @inheritdoc ILotus
function setBorrowCooldownExempt(address account, bool exempt) external onlyOwner {
isBorrowCooldownExempt[account] = exempt;
emit BorrowCooldownExemptSet(account, exempt);
}
/* MARKET CREATION */
/// @inheritdoc ILotus
function createMarket(
MarketParams memory marketParams,
TrancheConfig[] memory tranches,
bytes calldata riskEngineParams,
bytes calldata liquidationParams
) external notInRiskEngineCallWindow returns (Id id, bytes32 trancheConfigsHash) {
_checkNotGlobalPaused();
if (marketParams.loanToken == address(0)) {
revert LotusErrorsLib.ZeroAddress();
}
if (!isRiskEngineEnabled[marketParams.riskEngine]) {
revert LotusErrorsLib.RiskEngineNotEnabled(marketParams.riskEngine);
}
if (marketParams.liquidationModule == address(0)) {
revert LotusErrorsLib.ZeroAddress();
}
if (!isLiquidationModuleEnabled[marketParams.liquidationModule]) {
revert LotusErrorsLib.LiquidationModuleNotEnabled(marketParams.liquidationModule);
}
if (tranches.length == 0) {
revert LotusErrorsLib.InconsistentInput();
}
// Recompute the hash from the tranches and overwrite whatever the caller supplied: id derivation, storage
// indexing and downstream lookups all key off this field, so it must always reflect `tranches`.
trancheConfigsHash = MarketParamsLib.computeTrancheConfigsHash(tranches);
marketParams.trancheConfigsHash = trancheConfigsHash;
id = marketParams.id();
if (marketTranches[id].length != 0) revert LotusErrorsLib.MarketAlreadyExists(id);
bool shouldStoreTrancheConfigs = _trancheConfigs[trancheConfigsHash].length == 0;
for (uint256 i = 0; i < tranches.length;) {
TrancheConfig memory cfg = tranches[i];
if (cfg.collateralToken == address(0)) revert LotusErrorsLib.ZeroAddress();
if (cfg.oracle == address(0)) revert LotusErrorsLib.ZeroAddress();
if (!isLltvEnabled[cfg.lltv]) {
revert LotusErrorsLib.LltvNotEnabled(cfg.lltv);
}
Tranche memory t;
t.lastUpdate = uint64(block.timestamp);
marketTranches[id].push(t);
if (shouldStoreTrancheConfigs) {
_trancheConfigs[trancheConfigsHash].push(cfg);
}
emit LotusEventsLib.MarketTrancheConfigured(id, i, cfg.collateralToken, cfg.oracle, cfg.lltv);
unchecked {
++i;
}
}
idToMarketParams[id] = marketParams;
_enterRiskEngineCallWindow();
IRiskEngine(marketParams.riskEngine).initialize(id, riskEngineParams);
_exitRiskEngineCallWindow();
ILiquidationModule(marketParams.liquidationModule).initializeMarket(id, liquidationParams);
emit LotusEventsLib.MarketCreated(id, marketParams);
}
/* LENDER FUNCTIONS */
/// @inheritdoc ILotus
function supply(
MarketParams memory marketParams,
uint256 trancheIndex,
uint256 assets,
uint256 shares,
address onBehalf,
bytes calldata data,
bytes calldata riskEngineData
) external notInRiskEngineCallWindow returns (uint256 suppliedAssets, uint256 suppliedShares) {
Id id = marketParams.id();
uint256 numTranches = _validateMarket(id);
_validateInputs(assets, shares, address(0), onBehalf, trancheIndex, numTranches, false, false);
_enforceNotPaused(id);
_accrueInterest(marketParams, id, riskEngineData);
Tranche storage tranche = marketTranches[id][trancheIndex];
(assets, shares) =
_convertAssetsAndSharesProtocolFavorable(assets, shares, tranche.supplyAssets, tranche.supplyShares);
if (shares == 0) revert LotusErrorsLib.InvalidZeroShareSupply();
_updateSupplyPosition(id, onBehalf, tranche, trancheIndex, shares, assets, true);
Hooks.afterSupply(
marketHookConfig[id],
ILotusHooks.SupplyParams({
id: id,
trancheIndex: trancheIndex,
sender: msg.sender,
onBehalf: onBehalf,
assets: assets,
shares: shares
})
);
emit LotusEventsLib.Supplied(id, msg.sender, onBehalf, trancheIndex, assets, shares);
LotusExternalLib.emitTrancheState(id, trancheIndex, tranche);
if (data.length > 0) ILotusSupplyCallback(msg.sender).onLotusSupply(assets, data);
SafeTransferLib.safeTransferFrom(marketParams.loanToken, msg.sender, address(this), assets);
return (assets, shares);
}
/// @inheritdoc ILotus
function withdraw(
MarketParams memory marketParams,
uint256 trancheIndex,
uint256 assets,
uint256 shares,
address onBehalf,
address receiver,
bytes calldata riskEngineData
) external notInRiskEngineCallWindow returns (uint256 withdrawnAssets, uint256 withdrawnShares) {
Id id = marketParams.id();
uint256 numTranches = _validateMarket(id);
_validateInputs(assets, shares, receiver, onBehalf, trancheIndex, numTranches, true, true);
_enforceNotPaused(id);
_accrueInterest(marketParams, id, riskEngineData);
uint256 trancheFreeSupply = _getValidatedFreeSupply(marketParams, id, trancheIndex, numTranches, riskEngineData);
Tranche storage tranche = marketTranches[id][trancheIndex];
(assets, shares) = _convertSupplyUserFavorable(assets, shares, tranche);
if (assets == 0) revert LotusErrorsLib.InvalidZeroAssetWithdrawal();
if (assets > trancheFreeSupply) revert LotusErrorsLib.InsufficientLiquidity(assets);
_updateSupplyPosition(id, onBehalf, tranche, trancheIndex, shares, assets, false);
Hooks.afterWithdraw(
marketHookConfig[id],
ILotusHooks.WithdrawParams({
id: id,
trancheIndex: trancheIndex,
sender: msg.sender,
onBehalf: onBehalf,
receiver: receiver,
assets: assets,
shares: shares
})
);
emit LotusEventsLib.Withdrawn(id, msg.sender, onBehalf, receiver, trancheIndex, assets, shares);
LotusExternalLib.emitTrancheState(id, trancheIndex, tranche);
SafeTransferLib.safeTransfer(marketParams.loanToken, receiver, assets);
return (assets, shares);
}
/* BORROWER FUNCTIONS */
/// @inheritdoc ILotus
function borrow(
MarketParams memory marketParams,
uint256 trancheIndex,
uint256 assets,
uint256 shares,
address onBehalf,
address receiver,
bytes calldata riskEngineData
) external notInRiskEngineCallWindow returns (uint256 borrowedAssets, uint256 borrowedShares) {
Id id = marketParams.id();
uint256 numTranches = _validateMarket(id);
_validateInputs(assets, shares, receiver, onBehalf, trancheIndex, numTranches, true, true);
_enforceNotPaused(id);
_accrueInterest(marketParams, id, riskEngineData);
uint256 trancheFreeSupply = _getValidatedFreeSupply(marketParams, id, trancheIndex, numTranches, riskEngineData);
Tranche storage tranche = marketTranches[id][trancheIndex];
// Mint only the shares the paid-out assets cost, so a borrow by shares cannot carry up to
// one unit of shares with no assets behind them.
if (assets == 0) assets = shares.toAssetsDown(tranche.borrowAssets, tranche.borrowShares);
shares = assets.toSharesUp(tranche.borrowAssets, tranche.borrowShares);
if (assets == 0) revert LotusErrorsLib.InvalidZeroAssetBorrow();
if (assets > trancheFreeSupply) revert LotusErrorsLib.InsufficientLiquidity(assets);
_updateBorrowPosition(id, onBehalf, tranche, trancheIndex, shares, assets, true);
_validatePositionHealth(marketParams, id, trancheIndex, onBehalf, assets);
Hooks.afterBorrow(
marketHookConfig[id],
ILotusHooks.BorrowParams({
id: id,
trancheIndex: trancheIndex,
sender: msg.sender,
onBehalf: onBehalf,
receiver: receiver,
assets: assets,
shares: shares
})
);
emit LotusEventsLib.Borrowed(id, msg.sender, onBehalf, receiver, trancheIndex, assets, shares);
LotusExternalLib.emitTrancheState(id, trancheIndex, tranche);
SafeTransferLib.safeTransfer(marketParams.loanToken, receiver, assets);
return (assets, shares);
}
/// @inheritdoc ILotus
function repay(
MarketParams memory marketParams,
uint256 trancheIndex,
uint256 assets,
uint256 shares,
address onBehalf,
bytes calldata data,
bytes calldata riskEngineData
) external notInRiskEngineCallWindow returns (uint256 repaidAssets, uint256 repaidShares) {
Id id = marketParams.id();
uint256 numTranches = _validateMarket(id);
_validateInputs(assets, shares, address(0), onBehalf, trancheIndex, numTranches, false, false);
_enforceNotPaused(id);
_accrueInterest(marketParams, id, riskEngineData);
Tranche storage tranche = marketTranches[id][trancheIndex];
Position storage position = _positions[id][onBehalf][trancheIndex];
bool byShares = assets == 0;
(assets, shares) =
_convertAssetsAndSharesProtocolFavorable(assets, shares, tranche.borrowAssets, tranche.borrowShares);
// A partial repay by shares is charged `toAssetsUp(shares)`, up to one unit more than those
// shares are worth. Burn the shares the charged assets buy, rounded down as for a repay by
// assets and capped at the position, so the repay cannot clear tranche debt while leaving
// the matching shares outstanding.
if (byShares && shares < position.borrowShares) {
uint256 owedShares = assets.toSharesDown(tranche.borrowAssets, tranche.borrowShares);
if (owedShares > shares) shares = owedShares < position.borrowShares ? owedShares : position.borrowShares;
}
if (shares == 0) revert LotusErrorsLib.InvalidZeroShareRepay();
uint64 cooldownUntil = borrowCooldownUntil(id, trancheIndex);
if (block.timestamp < cooldownUntil) {
// `borrowTs` never exceeds the current timestamp.
unchecked {
// Keyed on the borrower, not the caller, so public routers cannot launder the gate.
if (block.timestamp - position.borrowTs < MIN_BORROW_DURATION && !isBorrowCooldownExempt[onBehalf]) {
revert LotusErrorsLib.BorrowTooYoung(cooldownUntil);
}
}
}
// A partial repay must settle at least `MIN_PARTIAL_REPAY_ASSETS`, rejecting one-unit dust. Full position
// closes are exempt so any borrower can always exit regardless of dust.
if (shares < position.borrowShares && assets < MIN_PARTIAL_REPAY_ASSETS) {
revert LotusErrorsLib.InsufficientRepayAssets(assets);
}
_updateBorrowPosition(id, onBehalf, tranche, trancheIndex, shares, assets, false);
emit LotusEventsLib.Repaid(id, msg.sender, onBehalf, trancheIndex, assets, shares);
LotusExternalLib.emitTrancheState(id, trancheIndex, tranche);
if (data.length > 0) ILotusRepayCallback(msg.sender).onLotusRepay(assets, data);
SafeTransferLib.safeTransferFrom(marketParams.loanToken, msg.sender, address(this), assets);
return (assets, shares);
}
/// @inheritdoc ILotus
function supplyCollateral(
MarketParams memory marketParams,
uint256 trancheIndex,
uint256 assets,
address onBehalf,
bytes calldata data
) external notInRiskEngineCallWindow {
Id id = marketParams.id();
uint256 numTranches = _validateMarket(id);
_validateInputs(assets, 0, address(0), onBehalf, trancheIndex, numTranches, false, false);
_enforceNotPaused(id);
_updateCollateralPosition(id, onBehalf, trancheIndex, assets, true);
Hooks.afterSupplyCollateral(
marketHookConfig[id],
ILotusHooks.SupplyCollateralParams({
id: id, trancheIndex: trancheIndex, sender: msg.sender, onBehalf: onBehalf, assets: assets
})
);
emit LotusEventsLib.CollateralSupplied(id, msg.sender, onBehalf, trancheIndex, assets);
if (data.length > 0) ILotusSupplyCollateralCallback(msg.sender).onLotusSupplyCollateral(assets, data);
address collateralToken = _trancheConfigs[marketParams.trancheConfigsHash][trancheIndex].collateralToken;
SafeTransferLib.safeTransferFrom(collateralToken, msg.sender, address(this), assets);
}
/// @inheritdoc ILotus
function withdrawCollateral(
MarketParams memory marketParams,
uint256 trancheIndex,
uint256 assets,
address onBehalf,
address receiver,
bytes calldata riskEngineData
) external notInRiskEngineCallWindow {
Id id = marketParams.id();
uint256 numTranches = _validateMarket(id);
_validateInputs(assets, 0, receiver, onBehalf, trancheIndex, numTranches, true, true);
_enforceNotPaused(id);
_accrueInterest(marketParams, id, riskEngineData);
_updateCollateralPosition(id, onBehalf, trancheIndex, assets, false);
_validatePositionHealth(marketParams, id, trancheIndex, onBehalf, assets);
Hooks.afterWithdrawCollateral(
marketHookConfig[id],
ILotusHooks.WithdrawCollateralParams({
id: id,
trancheIndex: trancheIndex,
sender: msg.sender,
onBehalf: onBehalf,
receiver: receiver,
assets: assets
})
);
emit LotusEventsLib.CollateralWithdrawn(id, msg.sender, onBehalf, receiver, trancheIndex, assets);
address collateralToken = _trancheConfigs[marketParams.trancheConfigsHash][trancheIndex].collateralToken;
SafeTransferLib.safeTransfer(collateralToken, receiver, assets);
}
/* LIQUIDATION */
/// @inheritdoc ILotus
function liquidate(
MarketParams memory marketParams,
uint256 trancheIndex,
address borrower,
bytes calldata riskEngineData,
bytes calldata callbackData,
bytes calldata lmData
) external notInRiskEngineCallWindow nonReentrant returns (uint256 seizedAssets, uint256 repaidAssets) {
Id id = marketParams.id();
uint256 numTranches = _validateMarket(id);
_validateLiquidationInputs(borrower);
_validateTrancheIndex(trancheIndex, numTranches);
_enforceNotPaused(id);
_accrueInterest(marketParams, id, riskEngineData);
Tranche storage tranche = marketTranches[id][trancheIndex];
TrancheConfig memory config = _trancheConfigs[marketParams.trancheConfigsHash][trancheIndex];
uint256 collateralPrice = IOracle(config.oracle).price();
if (collateralPrice == 0) {
revert LotusErrorsLib.InvalidCollateralPrice();
}
if (_isHealthy(id, trancheIndex, borrower, collateralPrice, config.lltv)) {
revert LotusErrorsLib.NotUnderwater(borrower);
}
Position storage position = _positions[id][borrower][trancheIndex];
uint256 repaidShares;
LiquidationQuoteContext memory quoteContext = LiquidationQuoteContext({
id: id,
trancheIndex: trancheIndex,
tranche: tranche,
collateralPrice: collateralPrice,
borrower: borrower,
lltv: config.lltv,
position: position
});
(seizedAssets, repaidShares, repaidAssets) =
ILiquidationModule(marketParams.liquidationModule).calculateLiquidation(quoteContext, lmData);
if (repaidShares > position.borrowShares) {
revert LotusErrorsLib.ExcessiveRepay(repaidShares, position.borrowShares);
}
if (seizedAssets > position.collateral) {
revert LotusErrorsLib.ExcessiveSeizure(seizedAssets, position.collateral);
}
position.borrowShares -= repaidShares.toUint128();
tranche.borrowShares -= repaidShares.toUint128();
tranche.borrowAssets = uint256(tranche.borrowAssets).zeroFloorSub(repaidAssets).toUint128();
position.collateral -= seizedAssets.toUint128();
(uint256 badDebtShares, uint256 badDebtAssets) =
_calculateBadDebt(position.collateral, position.borrowShares, tranche.borrowAssets, tranche.borrowShares);
if (badDebtAssets > 0) {
_handleBadDebt(id, borrower, trancheIndex, tranche, badDebtShares, badDebtAssets);
}
emit LotusEventsLib.Liquidated(
id,
trancheIndex,
msg.sender,
borrower,
repaidAssets,
repaidShares,
seizedAssets,
badDebtAssets,
badDebtShares
);
LotusExternalLib.emitTrancheState(id, trancheIndex, tranche);
address collateralToken = config.collateralToken;
SafeTransferLib.safeApprove(collateralToken, marketParams.liquidationModule, seizedAssets);
ILiquidationModule(marketParams.liquidationModule)
.executeLiquidation(
id,
trancheIndex,
borrower,
msg.sender,
marketParams.loanToken,
collateralToken,
seizedAssets,
repaidAssets,
callbackData
);
SafeTransferLib.safeApprove(collateralToken, marketParams.liquidationModule, 0);
return (seizedAssets, repaidAssets);
}
/* FLASH LOANS */
/// @inheritdoc ILotus
function flashFee(address token, uint256 assets) public view returns (uint256 fee) {
return _computeFlashLoanFee(token, assets);
}
/// @inheritdoc ILotus
/// @dev No dedicated modifier is used here because token support, fee accounting, and callback target selection all
/// depend on the per-call token and current caller.
function flashLoan(address token, uint256 assets, bytes calldata data) external {
_checkNotGlobalPaused();
if (assets == 0) revert LotusErrorsLib.ZeroValue();
uint256 fee = _computeFlashLoanFee(token, assets);
uint256 repayment = assets + fee;
SafeTransferLib.safeTransfer(token, msg.sender, assets);
bytes4 callbackSelector = ILotusFlashLoanCallback(msg.sender).onLotusFlashLoan(token, assets, fee, data);
if (callbackSelector != ILotusFlashLoanCallback.onLotusFlashLoan.selector) {
revert LotusErrorsLib.InvalidFlashLoanCallbackResponse(
ILotusFlashLoanCallback.onLotusFlashLoan.selector, callbackSelector
);
}
SafeTransferLib.safeTransferFrom(token, msg.sender, address(this), repayment);
if (fee != 0 && feeRecipient != address(this)) {
SafeTransferLib.safeTransfer(token, feeRecipient, fee);
}
emit LotusEventsLib.FlashLoanExecuted(msg.sender, token, assets, fee);
}
/* INTEREST MANAGEMENT */
/// @inheritdoc ILotus
function accrueInterest(MarketParams memory marketParams, bytes calldata riskEngineData)
external
notInRiskEngineCallWindow
nonReentrant
{
Id id = marketParams.id();
_validateMarket(id);
_enforceNotPaused(id);
_accrueInterest(marketParams, id, riskEngineData);
emit LotusEventsLib.InterestAccrued(id);
}
/* AUTHORIZATION */
/// @inheritdoc ILotus
function setAuthorization(address authorized, bool newIsAuthorized) external {
if (newIsAuthorized == isAuthorized[msg.sender][authorized]) revert LotusErrorsLib.AuthorizationAlreadySet();
uint256 usedNonce = nonce[msg.sender]++;
emit LotusEventsLib.NonceIncremented(msg.sender, msg.sender, usedNonce);
isAuthorized[msg.sender][authorized] = newIsAuthorized;
emit LotusEventsLib.AuthorizationUpdated(msg.sender, msg.sender, authorized, newIsAuthorized);
}
/// @inheritdoc ILotus
function setAuthorizationWithSig(Authorization memory authorization, Signature calldata signature) external {
LotusExternalLib.setAuthorizationWithSig(isAuthorized, nonce, DOMAIN_SEPARATOR, authorization, signature);
}
/* VIEW FUNCTIONS */
/// @inheritdoc ILotus
function getMarketParams(Id id) external view returns (MarketParams memory) {
return idToMarketParams[id];
}
/// @inheritdoc ILotus
function getTrancheConfig(Id id, uint256 trancheIndex) external view returns (TrancheConfig memory) {
return _trancheConfigs[idToMarketParams[id].trancheConfigsHash][trancheIndex];
}
/// @inheritdoc ILotus
function getTrancheConfigs(Id id) external view returns (TrancheConfig[] memory) {
return _trancheConfigs[idToMarketParams[id].trancheConfigsHash];
}
/// @inheritdoc ILotus
function getMarketTranches(Id id) external view returns (Tranche[] memory) {
return marketTranches[id];
}
/// @inheritdoc ILotus
function getMarketTranche(Id id, uint256 trancheIndex) external view returns (Tranche memory) {
return marketTranches[id][trancheIndex];
}
/// @inheritdoc ILotus
function borrowCooldownUntil(Id id, uint256 trancheIndex) public view returns (uint64) {
return _borrowCooldownUntil[id][trancheIndex];
}
/// @inheritdoc ILotus
function lastUpdate(Id id, uint256 trancheIndex) external view returns (uint64) {
Tranche[] storage tranches = marketTranches[id];
if (trancheIndex >= tranches.length) return 0;
return uint64(tranches[trancheIndex].lastUpdate);
}
/// @inheritdoc ILotus
function getNumMarketTranches(Id id) external view returns (uint256) {
return marketTranches[id].length;
}
/// @inheritdoc ILotus
function getMarketPauseState(Id id) external view returns (bool paused, uint64 unpausedAt, uint64 syncedAt) {
return LotusExternalLib.pauseState(_pause, id);
}
/// @inheritdoc ILotus
function getMarketRiskEngine(Id id) external view returns (IRiskEngine) {
return IRiskEngine(idToMarketParams[id].riskEngine);
}
/// @inheritdoc ILotus
function getPosition(Id id, address user, uint256 trancheIndex) external view returns (Position memory) {
return _positions[id][user][trancheIndex];
}
/// @inheritdoc ILotus
function getMaxBorrowAndBorrowed(MarketParams memory marketParams, uint256 trancheIndex, address borrower)
external
view
returns (uint256 borrowed, uint256 maxBorrow)
{
Id id = marketParams.id();
uint256 numTranches = _validateMarket(id);
_validateTrancheIndex(trancheIndex, numTranches);
bytes32 trancheConfigsHash = idToMarketParams[id].trancheConfigsHash;
TrancheConfig memory config = _trancheConfigs[trancheConfigsHash][trancheIndex];
uint256 collateralPrice = IOracle(config.oracle).price();
Position storage position = _positions[id][borrower][trancheIndex];
return _getMaxBorrowAndBorrowed(
id, trancheIndex, position.borrowShares, position.collateral, collateralPrice, config.lltv
);
}
/// @inheritdoc ILotus
function getJrSupply(Id id, uint256 trancheIndex) external view returns (uint256) {
Tranche[] storage tranches = marketTranches[id];
uint256 numTranches = _validateMarket(id);
_validateTrancheIndex(trancheIndex, numTranches);
return _getJrSupplyAt(tranches, numTranches, trancheIndex);
}
/// @inheritdoc ILotus
function getFreeSupply(Id id, uint256 trancheIndex) external view returns (uint256) {
return _getFreeSupply(id, trancheIndex, "");
}
/// @inheritdoc ILotus
function getFreeSupply(Id id, uint256 trancheIndex, bytes calldata riskEngineData) external view returns (uint256) {
return _getFreeSupply(id, trancheIndex, riskEngineData);
}
function _getFreeSupply(Id id, uint256 trancheIndex, bytes memory riskEngineData) internal view returns (uint256) {
Tranche[] storage tranches = marketTranches[id];
uint256 numTranches = _validateMarket(id);
_validateTrancheIndex(trancheIndex, numTranches);
Tranche[] memory snap = _readTranches(tranches, numTranches);
uint256 freeSupply =
IRiskEngine(idToMarketParams[id].riskEngine).getFreeSupply(id, snap, trancheIndex, riskEngineData);
_validateFreeSupply(snap, numTranches, trancheIndex, freeSupply);
return freeSupply;
}
/// @inheritdoc ILotus
function getJrNetSupply(Id id) external view returns (uint256[] memory) {
Tranche[] storage tranches = marketTranches[id];
uint256 numTranches = _validateMarket(id);
return _getJrNetSupply(tranches, numTranches);
}
/// @inheritdoc ILotus
function getMarketHookConfig(Id id) external view returns (address hook, uint256 permissions) {
Hooks.HookConfig memory hookConfig = marketHookConfig[id];
return (hookConfig.hook, hookConfig.permissions);
}
/* INTERNAL FUNCTIONS */
/* VALIDATION HELPERS */
/// @dev Reverts when Lotus is reentered during the guarded risk engine external call window.
function _revertIfInRiskEngineCallWindow() internal view {
uint256 slot = _RISK_ENGINE_CALL_GUARD_SLOT;
bool locked;
assembly ("memory-safe") {
locked := tload(slot)
}
if (locked) revert LotusErrorsLib.RiskEngineCallReentrancy();
}
/// @dev Marks entry into the narrow window where Lotus is inside an external risk engine call.
function _enterRiskEngineCallWindow() internal {
uint256 slot = _RISK_ENGINE_CALL_GUARD_SLOT;
bool locked;
assembly ("memory-safe") {
locked := tload(slot)
}
if (locked) revert LotusErrorsLib.RiskEngineCallReentrancy();
assembly ("memory-safe") {
tstore(slot, 1)
}
}
/// @dev Clears the guarded risk engine external call window marker.
function _exitRiskEngineCallWindow() internal {
uint256 slot = _RISK_ENGINE_CALL_GUARD_SLOT;
assembly ("memory-safe") {
tstore(slot, 0)
}
}
/// @dev Returns whether the sender is authorized to manage `onBehalf`'s positions.
function _isSenderAuthorized(address onBehalf) internal view returns (bool) {
return msg.sender == onBehalf || isAuthorized[onBehalf][msg.sender];
}
/// @dev Validates that a market has been created.
function _validateMarket(Id id) internal view returns (uint256 numTranches) {
numTranches = marketTranches[id].length;
if (numTranches == 0) revert LotusErrorsLib.MarketNotCreated(id);
}
/// @dev Validates that a tranche index is within valid range.
function _validateTrancheIndex(uint256 trancheIndex, uint256 numTranches) internal pure {
if (trancheIndex >= numTranches) revert LotusErrorsLib.InvalidTrancheIndex(trancheIndex);
}
/// @dev Validates shared inputs for state-changing entry points.
function _validateInputs(
uint256 assets,
uint256 shares,
address receiver,
address onBehalf,
uint256 trancheIndex,
uint256 numTranches,
bool requiresAuthorization,
bool hasReceiver
) internal view {
if (onBehalf == address(0)) revert LotusErrorsLib.ZeroAddress();
if (!UtilsLib.exactlyOneZero(assets, shares)) revert LotusErrorsLib.InconsistentInput();
if (hasReceiver && receiver == address(0)) {
revert LotusErrorsLib.ZeroAddress();
}
if (requiresAuthorization && !_isSenderAuthorized(onBehalf)) {
revert LotusErrorsLib.Unauthorized();
}
_validateTrancheIndex(trancheIndex, numTranches);
}
/// @dev Validates position health and reverts with appropriate error if unhealthy.
/// @param operationAmount Relevant amount for withdrawal error messaging.
function _validatePositionHealth(
MarketParams memory marketParams,
Id id,
uint256 trancheIndex,
address onBehalf,
uint256 operationAmount
) internal view {
if (!_isHealthy(marketParams, id, trancheIndex, onBehalf)) {
revert LotusErrorsLib.UnhealthyAfter(operationAmount);
}
}
/// @dev Validates liquidation-specific inputs.
function _validateLiquidationInputs(address borrower) internal pure {
if (borrower == address(0)) revert LotusErrorsLib.ZeroAddress();
}
/* POSITION HELPERS */
/// @dev Converts assets and shares with protocol-favorable rounding (supply, repay, liquidate).
/// Uses sharesDown for assets->shares and assetsUp for shares->assets.
function _convertAssetsAndSharesProtocolFavorable(
uint256 assets,
uint256 shares,
uint256 totalAssets,
uint256 totalShares
) internal pure returns (uint256, uint256) {
if (assets > 0) {
shares = assets.toSharesDown(totalAssets, totalShares);
} else {
assets = shares.toAssetsUp(totalAssets, totalShares);
}
return (assets, shares);
}
/// @dev Converts assets and shares with user-favorable rounding (withdraw).
/// Uses sharesUp for assets->shares and assetsDown for shares->assets.
function _convertAssetsAndSharesUserFavorable(
uint256 assets,
uint256 shares,
uint256 totalAssets,
uint256 totalShares
) internal pure returns (uint256, uint256) {
if (assets > 0) {
shares = assets.toSharesUp(totalAssets, totalShares);
} else {
assets = shares.toAssetsDown(totalAssets, totalShares);
}
return (assets, shares);
}
/// @dev `_convertAssetsAndSharesUserFavorable` against a tranche's supply totals. Reading the packed
/// `supplyAssets` here keeps `withdraw` within the stack limit under the unoptimized coverage build.
function _convertSupplyUserFavorable(uint256 assets, uint256 shares, Tranche storage tranche)
internal
view
returns (uint256, uint256)
{
return _convertAssetsAndSharesUserFavorable(assets, shares, tranche.supplyAssets, tranche.supplyShares);
}
/// @dev Updates supply position by adding or subtracting shares and assets.
function _updateSupplyPosition(
Id id,
address onBehalf,
Tranche storage tranche,
uint256 trancheIndex,
uint256 shares,
uint256 assets,
bool isSupply
) internal {
Position storage position = _positions[id][onBehalf][trancheIndex];
if (isSupply) {
position.supplyShares += shares;
tranche.supplyShares += shares;
tranche.supplyAssets += assets.toUint128();
} else {
position.supplyShares -= shares;
tranche.supplyShares -= shares;
tranche.supplyAssets -= assets.toUint128();
}
}
/// @dev Updates borrow position by adding or subtracting shares and assets.
function _updateBorrowPosition(
Id id,
address onBehalf,
Tranche storage tranche,
uint256 trancheIndex,
uint256 shares,
uint256 assets,
bool isBorrow
) internal {
Position storage position = _positions[id][onBehalf][trancheIndex];
if (isBorrow) {
uint128 newShares = shares.toUint128();
uint256 oldShares = position.borrowShares;
// Share-weighted borrow timestamp, rounded up toward now; resets to now when `oldShares` is zero.
unchecked {
uint256 totalShares = oldShares + newShares;
// forge-lint: disable-next-item(unsafe-typecast)
position.borrowTs = uint64(
(uint256(position.borrowTs) * oldShares + block.timestamp * newShares + totalShares - 1)
/ totalShares
);
}
position.borrowShares += newShares;
tranche.borrowShares += newShares;
tranche.borrowAssets += assets.toUint128();
} else {
position.borrowShares -= shares.toUint128();
tranche.borrowShares -= shares.toUint128();
tranche.borrowAssets = uint256(tranche.borrowAssets).zeroFloorSub(assets).toUint128();
}
}
/// @dev Updates collateral position.
function _updateCollateralPosition(Id id, address onBehalf, uint256 trancheIndex, uint256 assets, bool isSupply)
internal
{
Position storage position = _positions[id][onBehalf][trancheIndex];
if (isSupply) {
position.collateral += assets.toUint128();
} else {
position.collateral -= assets.toUint128();
}
}
/* BAD DEBT HELPERS */
/// @dev Calculates bad debt amounts without modifying state.
/// @dev Bad debt is only realized when the position has no collateral.
/// @dev When collateral is zero, bad debt assets are capped by current tranche borrow assets.
function _calculateBadDebt(
uint128 positionCollateral,
uint128 positionBorrowShares,
uint128 borrowAssets,
uint128 borrowShares
) internal pure returns (uint256 badDebtShares, uint256 badDebtAssets) {
if (positionCollateral == 0) {
badDebtShares = positionBorrowShares;
badDebtAssets = uint256(borrowAssets).min(badDebtShares.toAssetsUp(borrowAssets, borrowShares));
}
}
/// @dev Applies bad debt state changes after interest has been accrued.
/// @dev Clears the borrower's borrow shares for the tranche, reduces tranche borrow totals,
/// @dev then cascades losses to tranche suppliers via `_processBadDebt`.
function _handleBadDebt(
Id id,
address borrower,
uint256 trancheIndex,
Tranche storage tranche,
uint256 badDebtShares,
uint256 badDebtAssets
) internal {
if (badDebtAssets == 0) return;
Position storage position = _positions[id][borrower][trancheIndex];
tranche.borrowShares -= badDebtShares.toUint128();
position.borrowShares = 0;
tranche.borrowAssets -= badDebtAssets.toUint128();
LotusExternalLib.armBorrowCooldown(
_borrowCooldownUntil,
marketTranches,
id,
trancheIndex,
badDebtAssets,
MIN_BORROW_DURATION,
FULL_COOLDOWN_BAD_DEBT_RATIO
);
_processBadDebt(id, trancheIndex, badDebtAssets);
}
/// @dev Processes cascading bad debt across tranche supply balances via the risk engine.
function _processBadDebt(Id id, uint256 trancheIndex, uint256 badDebtAssets) internal {
if (badDebtAssets == 0) return;
Tranche[] storage tranches = marketTranches[id];
uint256 numTranches = tranches.length;
Tranche[] memory snap = _readTranches(tranches, numTranches);
BadDebtDeltas memory deltas;
_enterRiskEngineCallWindow();
deltas = IRiskEngine(idToMarketParams[id].riskEngine).distributeBadDebt(id, snap, trancheIndex, badDebtAssets);
_exitRiskEngineCallWindow();
if (deltas.supplyReductions.length != numTranches) revert LotusErrorsLib.DeltaLengthMismatch();
uint256 totalReduced;
for (uint256 i = 0; i < numTranches;) {
uint256 reduction = deltas.supplyReductions[i];
if (i < trancheIndex && reduction != 0) revert LotusErrorsLib.BadDebtDirectionViolation();
if (reduction > snap[i].supplyAssets) revert LotusErrorsLib.ExcessiveBadDebtReduction();
if (reduction != 0) {
tranches[i].supplyAssets -= reduction.toUint128();
totalReduced += reduction;
LotusExternalLib.emitBadDebtAllocation(id, trancheIndex, i, reduction, tranches[i]);
}
unchecked {
++i;
}
}
if (totalReduced != badDebtAssets) revert LotusErrorsLib.BadDebtTotalMismatch();
}
/* TRANCHE READ HELPERS */
/// @dev Reads all tranches from storage into a memory array.
function _readTranches(Tranche[] storage tranches, uint256 count)
internal
view
returns (Tranche[] memory tranchesMemory)
{
tranchesMemory = new Tranche[](count);
for (uint256 i = 0; i < count;) {
tranchesMemory[i] = tranches[i];
unchecked {
++i;
}
}
}
/* TRANCHE METRICS HELPERS */
/// @dev Computes the junior net supply for each tranche.
function _getJrNetSupply(Tranche[] storage tranches, uint256 numTranches)
internal
view
returns (uint256[] memory jrNetSupply)
{
jrNetSupply = new uint256[](numTranches);
uint256 cumJrSupply = 0;
uint256 cumJrBorrow = 0;
for (uint256 i = numTranches; i > 0;) {
unchecked {
i--;
}
(uint256 supplyAssets, uint256 borrowAssets) = _readTrancheAssembly(tranches[i]);
cumJrSupply += supplyAssets;
cumJrBorrow += borrowAssets;
jrNetSupply[i] = cumJrSupply.zeroFloorSub(cumJrBorrow);
}
}
/// @dev Computes the junior supply for a single tranche.
function _getJrSupplyAt(Tranche[] storage tranches, uint256 numTranches, uint256 trancheIndex)
internal
view
returns (uint256 jrSupply)
{
for (uint256 i = numTranches; i > trancheIndex;) {
unchecked {
i--;
}
jrSupply += tranches[i].supplyAssets;
}
}
/// @dev Computes the maximum free supply supported by the current waterfall-backed snapshot.
function _computePhysicalFreeSupply(Tranche[] memory tranches, uint256 numTranches, uint256 trancheIndex)
internal
pure
returns (uint256 freeSupply)
{
uint256 cumJrSupply;
uint256 cumJrBorrow;
freeSupply = type(uint256).max;
for (uint256 i = numTranches; i > 0;) {
unchecked {
i--;
}
cumJrSupply += tranches[i].supplyAssets;
cumJrBorrow += tranches[i].borrowAssets;
if (i <= trancheIndex) {
uint256 jrNet = cumJrSupply.zeroFloorSub(cumJrBorrow);
if (jrNet < freeSupply) freeSupply = jrNet;
}
}
if (freeSupply == type(uint256).max) freeSupply = 0;
}
/// @dev Reverts if the risk engine-reported free supply exceeds Lotus's waterfall-backed liquidity cap.
function _validateFreeSupply(Tranche[] memory snap, uint256 numTranches, uint256 trancheIndex, uint256 freeSupply)
internal
pure
{
uint256 liquidityCap = _computePhysicalFreeSupply(snap, numTranches, trancheIndex);
_validateFreeSupply(liquidityCap, freeSupply);
}
/// @dev Reverts if the risk engine-reported free supply exceeds Lotus's trusted liquidity cap.
function _validateFreeSupply(uint256 liquidityCap, uint256 freeSupply) internal pure {
if (freeSupply > liquidityCap) revert LotusErrorsLib.FreeSupplyExceedsPhysical();
}
/// @dev Returns the risk engine-effective free supply at `trancheIndex` for the current snapshot,
/// validated against Lotus's waterfall-backed liquidity cap.
function _getValidatedFreeSupply(
MarketParams memory marketParams,
Id id,
uint256 trancheIndex,
uint256 numTranches,
bytes calldata riskEngineData
) internal view returns (uint256 trancheFreeSupply) {
Tranche[] memory snap = _readTranches(marketTranches[id], numTranches);
trancheFreeSupply = IRiskEngine(marketParams.riskEngine).getFreeSupply(id, snap, trancheIndex, riskEngineData);
_validateFreeSupply(snap, numTranches, trancheIndex, trancheFreeSupply);
}
/// @dev Assembly-optimized storage read for the Tranche struct (3 slots).
/// Layout: slot 0 `supplyAssets` (low 128) | `fee` (next 64) | `lastUpdate` (high 64), slot 1 `supplyShares`,
/// slot 2 `borrowAssets` (low 128) | `borrowShares` (high 128).
function _readTrancheAssembly(Tranche storage tranche)
internal
view
returns (uint256 supplyAssets, uint256 borrowAssets)
{
assembly ("memory-safe") {
let mask128 := 0xffffffffffffffffffffffffffffffff
supplyAssets := and(sload(tranche.slot), mask128)
borrowAssets := and(sload(add(tranche.slot, 2)), mask128)
}
}
/// @dev Validates the risk engine-returned borrow interest against Lotus's maximum allowed interest envelope.
/// @dev This keeps the write-path boundary flexible while still capping the charged interest at the
/// @dev protocol's maximum borrow rate over the elapsed time.
function _validateBorrowInterest(Tranche memory snapTranche, uint256 borrowInterest) internal view {
if (borrowInterest == 0) return;
if (snapTranche.lastUpdate == uint64(block.timestamp) || snapTranche.borrowAssets == 0) {
revert LotusErrorsLib.UnexpectedBorrowInterest();
}
uint256 elapsedTime = block.timestamp - uint256(snapTranche.lastUpdate);
uint256 maxBorrowInterest = uint256(snapTranche.borrowAssets)
.mulWad(InterestMathLib.wTaylorCompounded(MAX_BORROW_RATE_PER_SECOND, elapsedTime));
if (borrowInterest > maxBorrowInterest) revert LotusErrorsLib.BorrowInterestTooHigh();
}
/* PAUSE HELPERS */
/// @dev Reverts only on a global pause. For functions without a market context (`flashLoan`,
/// `createMarket`).
function _checkNotGlobalPaused() internal view {
if (_pause.globalPaused) revert LotusErrorsLib.ProtocolPaused();
}
/// @dev Single gate called at the start of each per-market state-changing function:
/// (1) reverts if the protocol or this market is paused;
/// (2) lazily advances each tranche's `lastUpdate` to the unpause timestamp if a global
/// or per-market unpause has happened since this market was last synced - so no interest
/// accrues over the pause window, while the active period after the unpause is still charged.
function _enforceNotPaused(Id id) internal {
LotusExternalLib.enforceNotPaused(_pause, marketTranches[id], id);
}
/* INTEREST ACCRUAL HELPERS */
/// @dev Accrues interest for all tranches via the risk engine cascade.
/// @dev Lotus caps risk engine-returned borrowInterest per tranche against the maximum borrow-rate envelope.
/// @dev The cascade conservation check ensures the risk engine's supply allocation is fully funded by
/// @dev risk engine-reported borrowInterest.
function _accrueInterest(MarketParams memory marketParams, Id id, bytes calldata riskEngineData)
internal
returns (uint256 freeSupply)
{
Tranche[] storage tranches = marketTranches[id];
uint256 numTranches = tranches.length;
Tranche[] memory snap = _readTranches(tranches, numTranches);
AccrualDelta[] memory deltas;
_enterRiskEngineCallWindow();
(deltas, freeSupply) = IRiskEngine(marketParams.riskEngine).accrueInterest(id, snap, riskEngineData);
_exitRiskEngineCallWindow();
if (deltas.length != numTranches) revert LotusErrorsLib.DeltaLengthMismatch();
_validateFreeSupply(snap, numTranches, numTranches - 1, freeSupply);
// Single-pass: validate borrowInterest, run cascade conservation check, and write state.
// The risk engine controls how much interest enters the cascade and where it goes,
// while Lotus enforces the maximum interest envelope and exact conservation.
uint256 cascading;
for (uint256 i = 0; i < numTranches;) {
uint256 borrowInterest = deltas[i].borrowInterest;
uint256 supplyInterest = deltas[i].supplyInterest;
_validateBorrowInterest(snap[i], borrowInterest);
cascading += borrowInterest;
if (supplyInterest > cascading) revert LotusErrorsLib.InterestDirectionViolation();
cascading -= supplyInterest;
Tranche storage tranche = tranches[i];
if (borrowInterest != 0) {
tranche.borrowAssets += borrowInterest.toUint128();
}
uint256 feeShares;
if (supplyInterest != 0) {
tranche.supplyAssets += supplyInterest.toUint128();
feeShares = _distributeFees(tranche, supplyInterest, i, id, tranche.fee);
}
if (snap[i].lastUpdate != uint64(block.timestamp)) {
tranche.lastUpdate = uint64(block.timestamp);
}
if (borrowInterest != 0 || supplyInterest != 0) {
LotusExternalLib.emitAccrual(id, i, tranche, borrowInterest, supplyInterest, feeShares);
}
unchecked {
++i;
}
}
if (cascading != 0) revert LotusErrorsLib.UnexpectedCarryForward();
}
/// @dev Mints protocol fee shares from newly accrued tranche supply interest.
/// @dev Uses preloaded `trancheFee` (from packed storage) to avoid an extra `sload`.
function _distributeFees(
Tranche storage tranche,
uint256 trancheSupplyInterest,
uint256 trancheIndex,
Id id,
uint64 trancheFee
) internal returns (uint256 feeShares) {
if (trancheFee != 0) {
// Round toward the protocol so a dust accrual can't truncate the fee to zero.
uint256 feeAmount = trancheSupplyInterest.mulWadUp(trancheFee);
feeShares = feeAmount.toSharesUp(tranche.supplyAssets - feeAmount, tranche.supplyShares);
Position storage position = _positions[id][feeRecipient][trancheIndex];
position.supplyShares += feeShares;
tranche.supplyShares += feeShares;
}
}
/* HEALTH CHECK FUNCTIONS */
/// @dev Returns whether a borrower's position is within its borrow limit, using the tranche oracle price and the
/// configured LLTV reduced by `borrowLtvBuffer`. Only `borrow` and `withdrawCollateral` use this check; liquidation
/// and every other health computation use the plain LLTV.
function _isHealthy(MarketParams memory marketParams, Id id, uint256 trancheIndex, address borrower)
internal
view
returns (bool)
{
Position storage position = _positions[id][borrower][trancheIndex];
uint128 borrowShares = position.borrowShares;
if (borrowShares == 0) return true;
TrancheConfig memory config = _trancheConfigs[marketParams.trancheConfigsHash][trancheIndex];
uint256 collateralPrice = IOracle(config.oracle).price();
// Rounds down and never exceeds `config.lltv`, so the cast cannot truncate.
// forge-lint: disable-next-line(unsafe-typecast)
uint128 borrowLimitLltv = uint128(uint256(config.lltv).mulWad(WAD - borrowLtvBuffer));
return _isHealthy(id, trancheIndex, borrowShares, position.collateral, collateralPrice, borrowLimitLltv);
}
/// @dev Returns whether a borrower's position is healthy using caller-supplied price and LLTV values.
function _isHealthy(Id id, uint256 trancheIndex, address borrower, uint256 collateralPrice, uint128 lltvCfg)
internal
view
returns (bool)
{
Position storage position = _positions[id][borrower][trancheIndex];
return _isHealthy(id, trancheIndex, position.borrowShares, position.collateral, collateralPrice, lltvCfg);
}
/// @dev Returns whether borrowed assets are less than or equal to max borrowable assets.
function _isHealthy(
Id id,
uint256 trancheIndex,
uint128 borrowShares,
uint128 collateral,
uint256 collateralPrice,
uint128 lltvCfg
) internal view returns (bool) {
(uint256 borrowed, uint256 maxBorrow) = _getMaxBorrowAndBorrowed(
id, trancheIndex, borrowShares, collateral, collateralPrice, lltvCfg
);
return maxBorrow >= borrowed;
}
/// @dev Computes current borrowed assets and max borrowable assets for health checks.
function _getMaxBorrowAndBorrowed(
Id id,
uint256 trancheIndex,
uint128 borrowShares,
uint128 collateral,
uint256 collateralPrice,
uint128 lltvCfg
) internal view returns (uint256 borrowed, uint256 maxBorrow) {
Tranche storage tranche = marketTranches[id][trancheIndex];
borrowed = uint256(borrowShares).toAssetsUp(tranche.borrowAssets, tranche.borrowShares);
maxBorrow = uint256(collateral).mulDiv(collateralPrice, ORACLE_PRICE_SCALE).mulWad(lltvCfg);
}
/// @dev Validates and sets the global borrow LTV buffer and emits the update event.
function _setBorrowLtvBuffer(uint64 newBuffer) internal {
if (newBuffer < MIN_BORROW_LTV_BUFFER || newBuffer > MAX_BORROW_LTV_BUFFER) {
revert LotusErrorsLib.InvalidBorrowLtvBuffer(newBuffer);
}
borrowLtvBuffer = newBuffer;
emit LotusEventsLib.BorrowLtvBufferUpdated(newBuffer);
}
/// @dev Sets the protocol fee recipient and emits the fee recipient update event.
function _setFeeRecipient(address newFeeRecipient) internal {
if (newFeeRecipient == address(0) || newFeeRecipient == address(this)) {
revert LotusErrorsLib.InvalidFeeRecipient(newFeeRecipient);
}
feeRecipient = newFeeRecipient;
emit LotusEventsLib.FeeRecipientUpdated(newFeeRecipient);
}
function _onlyOwnerOrModuleManager() internal view {
if (msg.sender != owner() && !isModuleManager[msg.sender]) {
revert LotusErrorsLib.NotOwnerOrModuleManager();
}
}
function _computeFlashLoanFee(address token, uint256 assets) internal view returns (uint256 fee) {
return assets.mulWadUp(flashLoanFee[token]);
}
}
lib/solady/src/utils/FixedPointMathLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
library FixedPointMathLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The operation failed, as the output exceeds the maximum value of uint256.
error ExpOverflow();
/// @dev The operation failed, as the output exceeds the maximum value of uint256.
error FactorialOverflow();
/// @dev The operation failed, due to an overflow.
error RPowOverflow();
/// @dev The mantissa is too big to fit.
error MantissaOverflow();
/// @dev The operation failed, due to an multiplication overflow.
error MulWadFailed();
/// @dev The operation failed, due to an multiplication overflow.
error SMulWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error DivWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error SDivWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error MulDivFailed();
/// @dev The division failed, as the denominator is zero.
error DivFailed();
/// @dev The full precision multiply-divide operation failed, either due
/// to the result being larger than 256 bits, or a division by a zero.
error FullMulDivFailed();
/// @dev The output is undefined, as the input is less-than-or-equal to zero.
error LnWadUndefined();
/// @dev The input outside the acceptable domain.
error OutOfDomain();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The scalar of ETH and most ERC20s.
uint256 internal constant WAD = 1e18;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* SIMPLIFIED FIXED POINT OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to `(x * y) / WAD` rounded down.
function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
if gt(x, div(not(0), y)) {
if y {
mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
revert(0x1c, 0x04)
}
}
z := div(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down.
function sMulWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`.
if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) {
mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`.
revert(0x1c, 0x04)
}
z := sdiv(z, WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded up.
function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
if iszero(eq(div(z, y), x)) {
if y {
mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
revert(0x1c, 0x04)
}
}
z := add(iszero(iszero(mod(z, WAD))), div(z, WAD))
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks.
function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down.
function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
revert(0x1c, 0x04)
}
z := div(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down.
function sDivWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, WAD)
// Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`.
if iszero(mul(y, eq(sdiv(z, WAD), x))) {
mstore(0x00, 0x5c43740d) // `SDivWadFailed()`.
revert(0x1c, 0x04)
}
z := sdiv(z, y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded up.
function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks.
function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
}
}
/// @dev Equivalent to `x` to the power of `y`.
/// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`.
/// Note: This function is an approximation.
function powWad(int256 x, int256 y) internal pure returns (int256) {
// Using `ln(x)` means `x` must be greater than 0.
return expWad((lnWad(x) * y) / int256(WAD));
}
/// @dev Returns `exp(x)`, denominated in `WAD`.
/// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
/// Note: This function is an approximation. Monotonically increasing.
function expWad(int256 x) internal pure returns (int256 r) {
unchecked {
// When the result is less than 0.5 we return zero.
// This happens when `x <= (log(1e-18) * 1e18) ~ -4.15e19`.
if (x <= -41446531673892822313) return r;
/// @solidity memory-safe-assembly
assembly {
// When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as
// an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`.
if iszero(slt(x, 135305999368893231589)) {
mstore(0x00, 0xa37bfec9) // `ExpOverflow()`.
revert(0x1c, 0x04)
}
}
// `x` is now in the range `(-42, 136) * 1e18`. Convert to `(-42, 136) * 2**96`
// for more intermediate precision and a binary basis. This base conversion
// is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
x = (x << 78) / 5 ** 18;
// Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
// of two such that exp(x) = exp(x') * 2**k, where k is an integer.
// Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96;
x = x - k * 54916777467707473351141471128;
// `k` is in the range `[-61, 195]`.
// Evaluate using a (6, 7)-term rational approximation.
// `p` is made monic, we'll multiply by a scale factor later.
int256 y = x + 1346386616545796478920950773328;
y = ((y * x) >> 96) + 57155421227552351082224309758442;
int256 p = y + x - 94201549194550492254356042504812;
p = ((p * y) >> 96) + 28719021644029726153956944680412240;
p = p * x + (4385272521454847904659076985693276 << 96);
// We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
int256 q = x - 2855989394907223263936484059900;
q = ((q * x) >> 96) + 50020603652535783019961831881945;
q = ((q * x) >> 96) - 533845033583426703283633433725380;
q = ((q * x) >> 96) + 3604857256930695427073651918091429;
q = ((q * x) >> 96) - 14423608567350463180887372962807573;
q = ((q * x) >> 96) + 26449188498355588339934803723976023;
/// @solidity memory-safe-assembly
assembly {
// Div in assembly because solidity adds a zero check despite the unchecked.
// The q polynomial won't have zeros in the domain as all its roots are complex.
// No scaling is necessary because p is already `2**96` too large.
r := sdiv(p, q)
}
// r should be in the range `(0.09, 0.25) * 2**96`.
// We now need to multiply r by:
// - The scale factor `s ≈ 6.031367120`.
// - The `2**k` factor from the range reduction.
// - The `1e18 / 2**96` factor for base conversion.
// We do this all at once, with an intermediate result in `2**213`
// basis, so the final right shift is always by a positive amount.
r = int256(
(uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k)
);
}
}
/// @dev Returns `ln(x)`, denominated in `WAD`.
/// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
/// Note: This function is an approximation. Monotonically increasing.
function lnWad(int256 x) internal pure returns (int256 r) {
/// @solidity memory-safe-assembly
assembly {
// We want to convert `x` from `10**18` fixed point to `2**96` fixed point.
// We do this by multiplying by `2**96 / 10**18`. But since
// `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here
// and add `ln(2**96 / 10**18)` at the end.
// Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`.
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// We place the check here for more optimal stack operations.
if iszero(sgt(x, 0)) {
mstore(0x00, 0x1615e638) // `LnWadUndefined()`.
revert(0x1c, 0x04)
}
// forgefmt: disable-next-item
r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff))
// Reduce range of x to (1, 2) * 2**96
// ln(2^k * x) = k * ln(2) + ln(x)
x := shr(159, shl(r, x))
// Evaluate using a (8, 8)-term rational approximation.
// `p` is made monic, we will multiply by a scale factor later.
// forgefmt: disable-next-item
let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir.
sar(96, mul(add(43456485725739037958740375743393,
sar(96, mul(add(24828157081833163892658089445524,
sar(96, mul(add(3273285459638523848632254066296,
x), x))), x))), x)), 11111509109440967052023855526967)
p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857)
p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526)
p := sub(mul(p, x), shl(96, 795164235651350426258249787498))
// We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
// `q` is monic by convention.
let q := add(5573035233440673466300451813936, x)
q := add(71694874799317883764090561454958, sar(96, mul(x, q)))
q := add(283447036172924575727196451306956, sar(96, mul(x, q)))
q := add(401686690394027663651624208769553, sar(96, mul(x, q)))
q := add(204048457590392012362485061816622, sar(96, mul(x, q)))
q := add(31853899698501571402653359427138, sar(96, mul(x, q)))
q := add(909429971244387300277376558375, sar(96, mul(x, q)))
// `p / q` is in the range `(0, 0.125) * 2**96`.
// Finalization, we need to:
// - Multiply by the scale factor `s = 5.549…`.
// - Add `ln(2**96 / 10**18)`.
// - Add `k * ln(2)`.
// - Multiply by `10**18 / 2**96 = 5**18 >> 78`.
// The q polynomial is known not to have zeros in the domain.
// No scaling required because p is already `2**96` too large.
p := sdiv(p, q)
// Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`.
p := mul(1677202110996718588342820967067443963516166, p)
// Add `ln(2) * k * 5**18 * 2**192`.
// forgefmt: disable-next-item
p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p)
// Add `ln(2**96 / 10**18) * 5**18 * 2**192`.
p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p)
// Base conversion: mul `2**18 / 2**192`.
r := sar(174, p)
}
}
/// @dev Returns `W_0(x)`, denominated in `WAD`.
/// See: https://en.wikipedia.org/wiki/Lambert_W_function
/// a.k.a. Product log function. This is an approximation of the principal branch.
/// Note: This function is an approximation. Monotonically increasing.
function lambertW0Wad(int256 x) internal pure returns (int256 w) {
// forgefmt: disable-next-item
unchecked {
if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`.
(int256 wad, int256 p) = (int256(WAD), x);
uint256 c; // Whether we need to avoid catastrophic cancellation.
uint256 i = 4; // Number of iterations.
if (w <= 0x1ffffffffffff) {
if (-0x4000000000000 <= w) {
i = 1; // Inputs near zero only take one step to converge.
} else if (w <= -0x3ffffffffffffff) {
i = 32; // Inputs near `-1/e` take very long to converge.
}
} else if (uint256(w >> 63) == uint256(0)) {
/// @solidity memory-safe-assembly
assembly {
// Inline log2 for more performance, since the range is small.
let v := shr(49, w)
let l := shl(3, lt(0xff, v))
l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020504060203020504030106050205030304010505030400000000)), 49)
w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13))
c := gt(l, 60)
i := add(2, add(gt(l, 53), c))
}
} else {
int256 ll = lnWad(w = lnWad(w));
/// @solidity memory-safe-assembly
assembly {
// `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`.
w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll))
i := add(3, iszero(shr(68, x)))
c := iszero(shr(143, x))
}
if (c == uint256(0)) {
do { // If `x` is big, use Newton's so that intermediate values won't overflow.
int256 e = expWad(w);
/// @solidity memory-safe-assembly
assembly {
let t := mul(w, div(e, wad))
w := sub(w, sdiv(sub(t, x), div(add(e, t), wad)))
}
if (p <= w) break;
p = w;
} while (--i != uint256(0));
/// @solidity memory-safe-assembly
assembly {
w := sub(w, sgt(w, 2))
}
return w;
}
}
do { // Otherwise, use Halley's for faster convergence.
int256 e = expWad(w);
/// @solidity memory-safe-assembly
assembly {
let t := add(w, wad)
let s := sub(mul(w, e), mul(x, wad))
w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t)))))
}
if (p <= w) break;
p = w;
} while (--i != c);
/// @solidity memory-safe-assembly
assembly {
w := sub(w, sgt(w, 2))
}
// For certain ranges of `x`, we'll use the quadratic-rate recursive formula of
// R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation.
if (c == uint256(0)) return w;
int256 t = w | 1;
/// @solidity memory-safe-assembly
assembly {
x := sdiv(mul(x, wad), t)
}
x = (t * (wad + lnWad(x)));
/// @solidity memory-safe-assembly
assembly {
w := sdiv(x, add(wad, t))
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* GENERAL NUMBER UTILITIES */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `a * b == x * y`, with full precision.
function fullMulEq(uint256 a, uint256 b, uint256 x, uint256 y)
internal
pure
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
result := and(eq(mul(a, b), mul(x, y)), eq(mulmod(x, y, not(0)), mulmod(a, b, not(0))))
}
}
/// @dev Calculates `floor(x * y / d)` with full precision.
/// Throws if result overflows a uint256 or when `d` is zero.
/// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv
function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// 512-bit multiply `[p1 p0] = x * y`.
// Compute the product mod `2**256` and mod `2**256 - 1`
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that `product = p1 * 2**256 + p0`.
// Temporarily use `z` as `p0` to save gas.
z := mul(x, y) // Lower 256 bits of `x * y`.
for {} 1 {} {
// If overflows.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
/*------------------- 512 by 256 division --------------------*/
// Make division exact by subtracting the remainder from `[p1 p0]`.
let r := mulmod(x, y, d) // Compute remainder using mulmod.
let t := and(d, sub(0, d)) // The least significant bit of `d`. `t >= 1`.
// Make sure `z` is less than `2**256`. Also prevents `d == 0`.
// Placing the check here seems to give more optimal stack operations.
if iszero(gt(d, p1)) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
d := div(d, t) // Divide `d` by `t`, which is a power of two.
// Invert `d mod 2**256`
// Now that `d` is an odd number, it has an inverse
// modulo `2**256` such that `d * inv = 1 mod 2**256`.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, `d * inv = 1 mod 2**4`.
let inv := xor(2, mul(3, d))
// Now use 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.
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128
z :=
mul(
// Divide [p1 p0] by the factors of two.
// Shift in bits from `p1` into `p0`. For this we need
// to flip `t` such that it is `2**256 / t`.
or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
mul(sub(2, mul(d, inv)), inv) // inverse mod 2**256
)
break
}
z := div(z, d)
break
}
}
}
/// @dev Calculates `floor(x * y / d)` with full precision.
/// Behavior is undefined if `d` is zero or the final result cannot fit in 256 bits.
/// Performs the full 512 bit calculation regardless.
function fullMulDivUnchecked(uint256 x, uint256 y, uint256 d)
internal
pure
returns (uint256 z)
{
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z)))
let t := and(d, sub(0, d))
let r := mulmod(x, y, d)
d := div(d, t)
let inv := xor(2, mul(3, d))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
z :=
mul(
or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
mul(sub(2, mul(d, inv)), inv)
)
}
}
/// @dev Calculates `floor(x * y / d)` with full precision, rounded up.
/// Throws if result overflows a uint256 or when `d` is zero.
/// Credit to Uniswap-v3-core under MIT license:
/// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol
function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
z = fullMulDiv(x, y, d);
/// @solidity memory-safe-assembly
assembly {
if mulmod(x, y, d) {
z := add(z, 1)
if iszero(z) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
}
}
}
/// @dev Calculates `floor(x * y / 2 ** n)` with full precision.
/// Throws if result overflows a uint256.
/// Credit to Philogy under MIT license:
/// https://github.com/SorellaLabs/angstrom/blob/main/contracts/src/libraries/X128MathLib.sol
function fullMulDivN(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Temporarily use `z` as `p0` to save gas.
z := mul(x, y) // Lower 256 bits of `x * y`. We'll call this `z`.
for {} 1 {} {
if iszero(or(iszero(x), eq(div(z, x), y))) {
let k := and(n, 0xff) // `n`, cleaned.
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
// | p1 | z |
// Before: | p1_0 ¦ p1_1 | z_0 ¦ z_1 |
// Final: | 0 ¦ p1_0 | p1_1 ¦ z_0 |
// Check that final `z` doesn't overflow by checking that p1_0 = 0.
if iszero(shr(k, p1)) {
z := add(shl(sub(256, k), p1), shr(k, z))
break
}
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
z := shr(and(n, 0xff), z)
break
}
}
}
/// @dev Returns `floor(x * y / d)`.
/// Reverts if `x * y` overflows, or `d` is zero.
function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
mstore(0x00, 0xad251c27) // `MulDivFailed()`.
revert(0x1c, 0x04)
}
z := div(z, d)
}
}
/// @dev Returns `ceil(x * y / d)`.
/// Reverts if `x * y` overflows, or `d` is zero.
function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
mstore(0x00, 0xad251c27) // `MulDivFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(z, d))), div(z, d))
}
}
/// @dev Returns `x`, the modular multiplicative inverse of `a`, such that `(a * x) % n == 1`.
function invMod(uint256 a, uint256 n) internal pure returns (uint256 x) {
/// @solidity memory-safe-assembly
assembly {
let g := n
let r := mod(a, n)
for { let y := 1 } 1 {} {
let q := div(g, r)
let t := g
g := r
r := sub(t, mul(r, q))
let u := x
x := y
y := sub(u, mul(y, q))
if iszero(r) { break }
}
x := mul(eq(g, 1), add(x, mul(slt(x, 0), n)))
}
}
/// @dev Returns `ceil(x / d)`.
/// Reverts if `d` is zero.
function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
if iszero(d) {
mstore(0x00, 0x65244e4e) // `DivFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(x, d))), div(x, d))
}
}
/// @dev Returns `max(0, x - y)`. Alias for `saturatingSub`.
function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(gt(x, y), sub(x, y))
}
}
/// @dev Returns `max(0, x - y)`.
function saturatingSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(gt(x, y), sub(x, y))
}
}
/// @dev Returns `min(2 ** 256 - 1, x + y)`.
function saturatingAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(sub(0, lt(add(x, y), x)), add(x, y))
}
}
/// @dev Returns `min(2 ** 256 - 1, x * y)`.
function saturatingMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(sub(or(iszero(x), eq(div(mul(x, y), x), y)), 1), mul(x, y))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, address x, address y) internal pure returns (address z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `x != 0 ? x : y`, without branching.
function coalesce(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(x, mul(y, iszero(x)))
}
}
/// @dev Returns `x != bytes32(0) ? x : y`, without branching.
function coalesce(bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(x, mul(y, iszero(x)))
}
}
/// @dev Returns `x != address(0) ? x : y`, without branching.
function coalesce(address x, address y) internal pure returns (address z) {
/// @solidity memory-safe-assembly
assembly {
z := or(x, mul(y, iszero(shl(96, x))))
}
}
/// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`.
/// Reverts if the computation overflows.
function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`.
if x {
z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x`
let half := shr(1, b) // Divide `b` by 2.
// Divide `y` by 2 every iteration.
for { y := shr(1, y) } y { y := shr(1, y) } {
let xx := mul(x, x) // Store x squared.
let xxRound := add(xx, half) // Round to the nearest number.
// Revert if `xx + half` overflowed, or if `x ** 2` overflows.
if or(lt(xxRound, xx), shr(128, x)) {
mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
revert(0x1c, 0x04)
}
x := div(xxRound, b) // Set `x` to scaled `xxRound`.
// If `y` is odd:
if and(y, 1) {
let zx := mul(z, x) // Compute `z * x`.
let zxRound := add(zx, half) // Round to the nearest number.
// If `z * x` overflowed or `zx + half` overflowed:
if or(xor(div(zx, x), z), lt(zxRound, zx)) {
// Revert if `x` is non-zero.
if x {
mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
revert(0x1c, 0x04)
}
}
z := div(zxRound, b) // Return properly scaled `zxRound`.
}
}
}
}
}
/// @dev Returns the square root of `x`, rounded down.
function sqrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`.
z := 181 // The "correct" value is 1, but this saves a multiplication later.
// This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
// start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.
// Let `y = x / 2**r`. We check `y >= 2**(k + 8)`
// but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`.
let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffffff, shr(r, x))))
z := shl(shr(1, r), z)
// Goal was to get `z*z*y` within a small factor of `x`. More iterations could
// get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`.
// We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small.
// That's not possible if `x < 256` but we can just verify those cases exhaustively.
// Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`.
// Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`.
// Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps.
// For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)`
// is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`,
// with largest error when `s = 1` and when `s = 256` or `1/256`.
// Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`.
// Then we can estimate `sqrt(y)` using
// `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`.
// There is no overflow risk here since `y < 2**136` after the first branch above.
z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181.
// Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
// If `x+1` is a perfect square, the Babylonian method cycles between
// `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor.
// See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
z := sub(z, lt(div(x, z), z))
}
}
/// @dev Returns the cube root of `x`, rounded down.
/// Credit to bout3fiddy and pcaversaccio under AGPLv3 license:
/// https://github.com/pcaversaccio/snekmate/blob/main/src/snekmate/utils/math.vy
/// Formally verified by xuwinnie:
/// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
function cbrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// Makeshift lookup table to nudge the approximate log2 result.
z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3)))
// Newton-Raphson's.
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
// Round down.
z := sub(z, lt(div(x, mul(z, z)), z))
}
}
/// @dev Returns the square root of `x`, denominated in `WAD`, rounded down.
function sqrtWad(uint256 x) internal pure returns (uint256 z) {
unchecked {
if (x <= type(uint256).max / 10 ** 18) return sqrt(x * 10 ** 18);
z = (1 + sqrt(x)) * 10 ** 9;
z = (fullMulDivUnchecked(x, 10 ** 18, z) + z) >> 1;
}
/// @solidity memory-safe-assembly
assembly {
z := sub(z, gt(999999999999999999, sub(mulmod(z, z, x), 1))) // Round down.
}
}
/// @dev Returns the cube root of `x`, denominated in `WAD`, rounded down.
/// Formally verified by xuwinnie:
/// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
function cbrtWad(uint256 x) internal pure returns (uint256 z) {
unchecked {
if (x <= type(uint256).max / 10 ** 36) return cbrt(x * 10 ** 36);
z = (1 + cbrt(x)) * 10 ** 12;
z = (fullMulDivUnchecked(x, 10 ** 36, z * z) + z + z) / 3;
}
/// @solidity memory-safe-assembly
assembly {
let p := x
for {} 1 {} {
if iszero(shr(229, p)) {
if iszero(shr(199, p)) {
p := mul(p, 100000000000000000) // 10 ** 17.
break
}
p := mul(p, 100000000) // 10 ** 8.
break
}
if iszero(shr(249, p)) { p := mul(p, 100) }
break
}
let t := mulmod(mul(z, z), z, p)
z := sub(z, gt(lt(t, shr(1, p)), iszero(t))) // Round down.
}
}
/// @dev Returns `sqrt(x * y)`. Also called the geometric mean.
function mulSqrt(uint256 x, uint256 y) internal pure returns (uint256 z) {
if (x == y) return x;
uint256 p = rawMul(x, y);
if (y == rawDiv(p, x)) return sqrt(p);
for (z = saturatingMul(rawAdd(sqrt(x), 1), rawAdd(sqrt(y), 1));; z = avg(z, p)) {
if ((p = fullMulDivUnchecked(x, y, z)) >= z) break;
}
}
/// @dev Returns the factorial of `x`.
function factorial(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := 1
if iszero(lt(x, 58)) {
mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`.
revert(0x1c, 0x04)
}
for {} x { x := sub(x, 1) } { z := mul(z, x) }
}
}
/// @dev Returns the log2 of `x`.
/// Equivalent to computing the index of the most significant bit (MSB) of `x`.
/// Returns 0 if `x` is zero.
function log2(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020504060203020504030106050205030304010505030400000000))
}
}
/// @dev Returns the log2 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log2Up(uint256 x) internal pure returns (uint256 r) {
r = log2(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(shl(r, 1), x))
}
}
/// @dev Returns the log10 of `x`.
/// Returns 0 if `x` is zero.
function log10(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
if iszero(lt(x, 100000000000000000000000000000000000000)) {
x := div(x, 100000000000000000000000000000000000000)
r := 38
}
if iszero(lt(x, 100000000000000000000)) {
x := div(x, 100000000000000000000)
r := add(r, 20)
}
if iszero(lt(x, 10000000000)) {
x := div(x, 10000000000)
r := add(r, 10)
}
if iszero(lt(x, 100000)) {
x := div(x, 100000)
r := add(r, 5)
}
r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999)))))
}
}
/// @dev Returns the log10 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log10Up(uint256 x) internal pure returns (uint256 r) {
r = log10(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(exp(10, r), x))
}
}
/// @dev Returns the log256 of `x`.
/// Returns 0 if `x` is zero.
function log256(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(shr(3, r), lt(0xff, shr(r, x)))
}
}
/// @dev Returns the log256 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log256Up(uint256 x) internal pure returns (uint256 r) {
r = log256(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(shl(shl(3, r), 1), x))
}
}
/// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`.
/// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent).
function sci(uint256 x) internal pure returns (uint256 mantissa, uint256 exponent) {
/// @solidity memory-safe-assembly
assembly {
mantissa := x
if mantissa {
if iszero(mod(mantissa, 1000000000000000000000000000000000)) {
mantissa := div(mantissa, 1000000000000000000000000000000000)
exponent := 33
}
if iszero(mod(mantissa, 10000000000000000000)) {
mantissa := div(mantissa, 10000000000000000000)
exponent := add(exponent, 19)
}
if iszero(mod(mantissa, 1000000000000)) {
mantissa := div(mantissa, 1000000000000)
exponent := add(exponent, 12)
}
if iszero(mod(mantissa, 1000000)) {
mantissa := div(mantissa, 1000000)
exponent := add(exponent, 6)
}
if iszero(mod(mantissa, 10000)) {
mantissa := div(mantissa, 10000)
exponent := add(exponent, 4)
}
if iszero(mod(mantissa, 100)) {
mantissa := div(mantissa, 100)
exponent := add(exponent, 2)
}
if iszero(mod(mantissa, 10)) {
mantissa := div(mantissa, 10)
exponent := add(exponent, 1)
}
}
}
}
/// @dev Convenience function for packing `x` into a smaller number using `sci`.
/// The `mantissa` will be in bits [7..255] (the upper 249 bits).
/// The `exponent` will be in bits [0..6] (the lower 7 bits).
/// Use `SafeCastLib` to safely ensure that the `packed` number is small
/// enough to fit in the desired unsigned integer type:
/// ```
/// uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether));
/// ```
function packSci(uint256 x) internal pure returns (uint256 packed) {
(x, packed) = sci(x); // Reuse for `mantissa` and `exponent`.
/// @solidity memory-safe-assembly
assembly {
if shr(249, x) {
mstore(0x00, 0xce30380c) // `MantissaOverflow()`.
revert(0x1c, 0x04)
}
packed := or(shl(7, x), packed)
}
}
/// @dev Convenience function for unpacking a packed number from `packSci`.
function unpackSci(uint256 packed) internal pure returns (uint256 unpacked) {
unchecked {
unpacked = (packed >> 7) * 10 ** (packed & 0x7f);
}
}
/// @dev Returns the average of `x` and `y`. Rounds towards zero.
function avg(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = (x & y) + ((x ^ y) >> 1);
}
}
/// @dev Returns the average of `x` and `y`. Rounds towards negative infinity.
function avg(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = (x >> 1) + (y >> 1) + (x & y & 1);
}
}
/// @dev Returns the absolute value of `x`.
function abs(int256 x) internal pure returns (uint256 z) {
unchecked {
z = (uint256(x) + uint256(x >> 255)) ^ uint256(x >> 255);
}
}
/// @dev Returns the absolute distance between `x` and `y`.
function dist(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(xor(sub(0, gt(x, y)), sub(y, x)), gt(x, y))
}
}
/// @dev Returns the absolute distance between `x` and `y`.
function dist(int256 x, int256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(xor(sub(0, sgt(x, y)), sub(y, x)), sgt(x, y))
}
}
/// @dev Returns the minimum of `x` and `y`.
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), lt(y, x)))
}
}
/// @dev Returns the minimum of `x` and `y`.
function min(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), slt(y, x)))
}
}
/// @dev Returns the maximum of `x` and `y`.
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), gt(y, x)))
}
}
/// @dev Returns the maximum of `x` and `y`.
function max(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), sgt(y, x)))
}
}
/// @dev Returns `x`, bounded to `minValue` and `maxValue`.
function clamp(uint256 x, uint256 minValue, uint256 maxValue)
internal
pure
returns (uint256 z)
{
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, minValue), gt(minValue, x)))
z := xor(z, mul(xor(z, maxValue), lt(maxValue, z)))
}
}
/// @dev Returns `x`, bounded to `minValue` and `maxValue`.
function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, minValue), sgt(minValue, x)))
z := xor(z, mul(xor(z, maxValue), slt(maxValue, z)))
}
}
/// @dev Returns greatest common divisor of `x` and `y`.
function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
for { z := x } y {} {
let t := y
y := mod(z, y)
z := t
}
}
}
/// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`,
/// with `t` clamped between `begin` and `end` (inclusive).
/// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
/// If `begins == end`, returns `t <= begin ? a : b`.
function lerp(uint256 a, uint256 b, uint256 t, uint256 begin, uint256 end)
internal
pure
returns (uint256)
{
if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
if (t <= begin) return a;
if (t >= end) return b;
unchecked {
if (b >= a) return a + fullMulDiv(b - a, t - begin, end - begin);
return a - fullMulDiv(a - b, t - begin, end - begin);
}
}
/// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`.
/// with `t` clamped between `begin` and `end` (inclusive).
/// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
/// If `begins == end`, returns `t <= begin ? a : b`.
function lerp(int256 a, int256 b, int256 t, int256 begin, int256 end)
internal
pure
returns (int256)
{
if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
if (t <= begin) return a;
if (t >= end) return b;
// forgefmt: disable-next-item
unchecked {
if (b >= a) return int256(uint256(a) + fullMulDiv(uint256(b - a),
uint256(t - begin), uint256(end - begin)));
return int256(uint256(a) - fullMulDiv(uint256(a - b),
uint256(t - begin), uint256(end - begin)));
}
}
/// @dev Returns if `x` is an even number. Some people may need this.
function isEven(uint256 x) internal pure returns (bool) {
return x & uint256(1) == uint256(0);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* RAW NUMBER OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `x + y`, without checking for overflow.
function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x + y;
}
}
/// @dev Returns `x + y`, without checking for overflow.
function rawAdd(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x + y;
}
}
/// @dev Returns `x - y`, without checking for underflow.
function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x - y;
}
}
/// @dev Returns `x - y`, without checking for underflow.
function rawSub(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x - y;
}
}
/// @dev Returns `x * y`, without checking for overflow.
function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x * y;
}
}
/// @dev Returns `x * y`, without checking for overflow.
function rawMul(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x * y;
}
}
/// @dev Returns `x / y`, returning 0 if `y` is zero.
function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(x, y)
}
}
/// @dev Returns `x / y`, returning 0 if `y` is zero.
function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(x, y)
}
}
/// @dev Returns `x % y`, returning 0 if `y` is zero.
function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mod(x, y)
}
}
/// @dev Returns `x % y`, returning 0 if `y` is zero.
function rawSMod(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := smod(x, y)
}
}
/// @dev Returns `(x + y) % d`, return 0 if `d` if zero.
function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := addmod(x, y, d)
}
}
/// @dev Returns `(x * y) % d`, return 0 if `d` if zero.
function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mulmod(x, y, d)
}
}
}
lib/solady/src/utils/ReentrancyGuardTransient.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @notice Reentrancy guard mixin (transient storage variant).
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/ReentrancyGuardTransient.sol)
///
/// @dev Note: This implementation utilizes the `TSTORE` and `TLOAD` opcodes.
/// Please ensure that the chain you are deploying on supports them.
abstract contract ReentrancyGuardTransient {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Unauthorized reentrant call.
error Reentrancy();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to: `uint32(bytes4(keccak256("Reentrancy()"))) | 1 << 71`.
/// 9 bytes is large enough to avoid collisions in practice,
/// but not too large to result in excessive bytecode bloat.
uint256 private constant _REENTRANCY_GUARD_SLOT = 0x8000000000ab143c06;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* REENTRANCY GUARD */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Guards a function from reentrancy.
modifier nonReentrant() virtual {
if (_useTransientReentrancyGuardOnlyOnMainnet()) {
uint256 s = _REENTRANCY_GUARD_SLOT;
if (block.chainid == 1) {
/// @solidity memory-safe-assembly
assembly {
if tload(s) {
mstore(0x00, s) // `Reentrancy()`.
revert(0x1c, 0x04)
}
tstore(s, address())
}
} else {
/// @solidity memory-safe-assembly
assembly {
if eq(sload(s), address()) {
mstore(0x00, s) // `Reentrancy()`.
revert(0x1c, 0x04)
}
sstore(s, address())
}
}
} else {
/// @solidity memory-safe-assembly
assembly {
if tload(_REENTRANCY_GUARD_SLOT) {
mstore(0x00, 0xab143c06) // `Reentrancy()`.
revert(0x1c, 0x04)
}
tstore(_REENTRANCY_GUARD_SLOT, address())
}
}
_;
if (_useTransientReentrancyGuardOnlyOnMainnet()) {
uint256 s = _REENTRANCY_GUARD_SLOT;
if (block.chainid == 1) {
/// @solidity memory-safe-assembly
assembly {
tstore(s, 0)
}
} else {
/// @solidity memory-safe-assembly
assembly {
sstore(s, s)
}
}
} else {
/// @solidity memory-safe-assembly
assembly {
tstore(_REENTRANCY_GUARD_SLOT, 0)
}
}
}
/// @dev Guards a view function from read-only reentrancy.
modifier nonReadReentrant() virtual {
if (_useTransientReentrancyGuardOnlyOnMainnet()) {
uint256 s = _REENTRANCY_GUARD_SLOT;
if (block.chainid == 1) {
/// @solidity memory-safe-assembly
assembly {
if tload(s) {
mstore(0x00, s) // `Reentrancy()`.
revert(0x1c, 0x04)
}
}
} else {
/// @solidity memory-safe-assembly
assembly {
if eq(sload(s), address()) {
mstore(0x00, s) // `Reentrancy()`.
revert(0x1c, 0x04)
}
}
}
} else {
/// @solidity memory-safe-assembly
assembly {
if tload(_REENTRANCY_GUARD_SLOT) {
mstore(0x00, 0xab143c06) // `Reentrancy()`.
revert(0x1c, 0x04)
}
}
}
_;
}
/// @dev For widespread compatibility with L2s.
/// Only Ethereum mainnet is expensive anyways.
function _useTransientReentrancyGuardOnlyOnMainnet() internal view virtual returns (bool) {
return true;
}
}
lib/solady/src/utils/SafeCastLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Safe integer casting library that reverts on overflow.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeCastLib.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeCast.sol)
/// @dev Optimized for runtime gas for very high number of optimizer runs (i.e. >= 1000000).
library SafeCastLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Unable to cast to the target type due to overflow.
error Overflow();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* UNSIGNED INTEGER SAFE CASTING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Casts `x` to a uint8. Reverts on overflow.
function toUint8(uint256 x) internal pure returns (uint8) {
if (x >= 1 << 8) _revertOverflow();
return uint8(x);
}
/// @dev Casts `x` to a uint16. Reverts on overflow.
function toUint16(uint256 x) internal pure returns (uint16) {
if (x >= 1 << 16) _revertOverflow();
return uint16(x);
}
/// @dev Casts `x` to a uint24. Reverts on overflow.
function toUint24(uint256 x) internal pure returns (uint24) {
if (x >= 1 << 24) _revertOverflow();
return uint24(x);
}
/// @dev Casts `x` to a uint32. Reverts on overflow.
function toUint32(uint256 x) internal pure returns (uint32) {
if (x >= 1 << 32) _revertOverflow();
return uint32(x);
}
/// @dev Casts `x` to a uint40. Reverts on overflow.
function toUint40(uint256 x) internal pure returns (uint40) {
if (x >= 1 << 40) _revertOverflow();
return uint40(x);
}
/// @dev Casts `x` to a uint48. Reverts on overflow.
function toUint48(uint256 x) internal pure returns (uint48) {
if (x >= 1 << 48) _revertOverflow();
return uint48(x);
}
/// @dev Casts `x` to a uint56. Reverts on overflow.
function toUint56(uint256 x) internal pure returns (uint56) {
if (x >= 1 << 56) _revertOverflow();
return uint56(x);
}
/// @dev Casts `x` to a uint64. Reverts on overflow.
function toUint64(uint256 x) internal pure returns (uint64) {
if (x >= 1 << 64) _revertOverflow();
return uint64(x);
}
/// @dev Casts `x` to a uint72. Reverts on overflow.
function toUint72(uint256 x) internal pure returns (uint72) {
if (x >= 1 << 72) _revertOverflow();
return uint72(x);
}
/// @dev Casts `x` to a uint80. Reverts on overflow.
function toUint80(uint256 x) internal pure returns (uint80) {
if (x >= 1 << 80) _revertOverflow();
return uint80(x);
}
/// @dev Casts `x` to a uint88. Reverts on overflow.
function toUint88(uint256 x) internal pure returns (uint88) {
if (x >= 1 << 88) _revertOverflow();
return uint88(x);
}
/// @dev Casts `x` to a uint96. Reverts on overflow.
function toUint96(uint256 x) internal pure returns (uint96) {
if (x >= 1 << 96) _revertOverflow();
return uint96(x);
}
/// @dev Casts `x` to a uint104. Reverts on overflow.
function toUint104(uint256 x) internal pure returns (uint104) {
if (x >= 1 << 104) _revertOverflow();
return uint104(x);
}
/// @dev Casts `x` to a uint112. Reverts on overflow.
function toUint112(uint256 x) internal pure returns (uint112) {
if (x >= 1 << 112) _revertOverflow();
return uint112(x);
}
/// @dev Casts `x` to a uint120. Reverts on overflow.
function toUint120(uint256 x) internal pure returns (uint120) {
if (x >= 1 << 120) _revertOverflow();
return uint120(x);
}
/// @dev Casts `x` to a uint128. Reverts on overflow.
function toUint128(uint256 x) internal pure returns (uint128) {
if (x >= 1 << 128) _revertOverflow();
return uint128(x);
}
/// @dev Casts `x` to a uint136. Reverts on overflow.
function toUint136(uint256 x) internal pure returns (uint136) {
if (x >= 1 << 136) _revertOverflow();
return uint136(x);
}
/// @dev Casts `x` to a uint144. Reverts on overflow.
function toUint144(uint256 x) internal pure returns (uint144) {
if (x >= 1 << 144) _revertOverflow();
return uint144(x);
}
/// @dev Casts `x` to a uint152. Reverts on overflow.
function toUint152(uint256 x) internal pure returns (uint152) {
if (x >= 1 << 152) _revertOverflow();
return uint152(x);
}
/// @dev Casts `x` to a uint160. Reverts on overflow.
function toUint160(uint256 x) internal pure returns (uint160) {
if (x >= 1 << 160) _revertOverflow();
return uint160(x);
}
/// @dev Casts `x` to a uint168. Reverts on overflow.
function toUint168(uint256 x) internal pure returns (uint168) {
if (x >= 1 << 168) _revertOverflow();
return uint168(x);
}
/// @dev Casts `x` to a uint176. Reverts on overflow.
function toUint176(uint256 x) internal pure returns (uint176) {
if (x >= 1 << 176) _revertOverflow();
return uint176(x);
}
/// @dev Casts `x` to a uint184. Reverts on overflow.
function toUint184(uint256 x) internal pure returns (uint184) {
if (x >= 1 << 184) _revertOverflow();
return uint184(x);
}
/// @dev Casts `x` to a uint192. Reverts on overflow.
function toUint192(uint256 x) internal pure returns (uint192) {
if (x >= 1 << 192) _revertOverflow();
return uint192(x);
}
/// @dev Casts `x` to a uint200. Reverts on overflow.
function toUint200(uint256 x) internal pure returns (uint200) {
if (x >= 1 << 200) _revertOverflow();
return uint200(x);
}
/// @dev Casts `x` to a uint208. Reverts on overflow.
function toUint208(uint256 x) internal pure returns (uint208) {
if (x >= 1 << 208) _revertOverflow();
return uint208(x);
}
/// @dev Casts `x` to a uint216. Reverts on overflow.
function toUint216(uint256 x) internal pure returns (uint216) {
if (x >= 1 << 216) _revertOverflow();
return uint216(x);
}
/// @dev Casts `x` to a uint224. Reverts on overflow.
function toUint224(uint256 x) internal pure returns (uint224) {
if (x >= 1 << 224) _revertOverflow();
return uint224(x);
}
/// @dev Casts `x` to a uint232. Reverts on overflow.
function toUint232(uint256 x) internal pure returns (uint232) {
if (x >= 1 << 232) _revertOverflow();
return uint232(x);
}
/// @dev Casts `x` to a uint240. Reverts on overflow.
function toUint240(uint256 x) internal pure returns (uint240) {
if (x >= 1 << 240) _revertOverflow();
return uint240(x);
}
/// @dev Casts `x` to a uint248. Reverts on overflow.
function toUint248(uint256 x) internal pure returns (uint248) {
if (x >= 1 << 248) _revertOverflow();
return uint248(x);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* SIGNED INTEGER SAFE CASTING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Casts `x` to a int8. Reverts on overflow.
function toInt8(int256 x) internal pure returns (int8) {
unchecked {
if (((1 << 7) + uint256(x)) >> 8 == uint256(0)) return int8(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int16. Reverts on overflow.
function toInt16(int256 x) internal pure returns (int16) {
unchecked {
if (((1 << 15) + uint256(x)) >> 16 == uint256(0)) return int16(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int24. Reverts on overflow.
function toInt24(int256 x) internal pure returns (int24) {
unchecked {
if (((1 << 23) + uint256(x)) >> 24 == uint256(0)) return int24(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int32. Reverts on overflow.
function toInt32(int256 x) internal pure returns (int32) {
unchecked {
if (((1 << 31) + uint256(x)) >> 32 == uint256(0)) return int32(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int40. Reverts on overflow.
function toInt40(int256 x) internal pure returns (int40) {
unchecked {
if (((1 << 39) + uint256(x)) >> 40 == uint256(0)) return int40(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int48. Reverts on overflow.
function toInt48(int256 x) internal pure returns (int48) {
unchecked {
if (((1 << 47) + uint256(x)) >> 48 == uint256(0)) return int48(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int56. Reverts on overflow.
function toInt56(int256 x) internal pure returns (int56) {
unchecked {
if (((1 << 55) + uint256(x)) >> 56 == uint256(0)) return int56(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int64. Reverts on overflow.
function toInt64(int256 x) internal pure returns (int64) {
unchecked {
if (((1 << 63) + uint256(x)) >> 64 == uint256(0)) return int64(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int72. Reverts on overflow.
function toInt72(int256 x) internal pure returns (int72) {
unchecked {
if (((1 << 71) + uint256(x)) >> 72 == uint256(0)) return int72(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int80. Reverts on overflow.
function toInt80(int256 x) internal pure returns (int80) {
unchecked {
if (((1 << 79) + uint256(x)) >> 80 == uint256(0)) return int80(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int88. Reverts on overflow.
function toInt88(int256 x) internal pure returns (int88) {
unchecked {
if (((1 << 87) + uint256(x)) >> 88 == uint256(0)) return int88(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int96. Reverts on overflow.
function toInt96(int256 x) internal pure returns (int96) {
unchecked {
if (((1 << 95) + uint256(x)) >> 96 == uint256(0)) return int96(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int104. Reverts on overflow.
function toInt104(int256 x) internal pure returns (int104) {
unchecked {
if (((1 << 103) + uint256(x)) >> 104 == uint256(0)) return int104(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int112. Reverts on overflow.
function toInt112(int256 x) internal pure returns (int112) {
unchecked {
if (((1 << 111) + uint256(x)) >> 112 == uint256(0)) return int112(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int120. Reverts on overflow.
function toInt120(int256 x) internal pure returns (int120) {
unchecked {
if (((1 << 119) + uint256(x)) >> 120 == uint256(0)) return int120(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int128. Reverts on overflow.
function toInt128(int256 x) internal pure returns (int128) {
unchecked {
if (((1 << 127) + uint256(x)) >> 128 == uint256(0)) return int128(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int136. Reverts on overflow.
function toInt136(int256 x) internal pure returns (int136) {
unchecked {
if (((1 << 135) + uint256(x)) >> 136 == uint256(0)) return int136(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int144. Reverts on overflow.
function toInt144(int256 x) internal pure returns (int144) {
unchecked {
if (((1 << 143) + uint256(x)) >> 144 == uint256(0)) return int144(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int152. Reverts on overflow.
function toInt152(int256 x) internal pure returns (int152) {
unchecked {
if (((1 << 151) + uint256(x)) >> 152 == uint256(0)) return int152(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int160. Reverts on overflow.
function toInt160(int256 x) internal pure returns (int160) {
unchecked {
if (((1 << 159) + uint256(x)) >> 160 == uint256(0)) return int160(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int168. Reverts on overflow.
function toInt168(int256 x) internal pure returns (int168) {
unchecked {
if (((1 << 167) + uint256(x)) >> 168 == uint256(0)) return int168(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int176. Reverts on overflow.
function toInt176(int256 x) internal pure returns (int176) {
unchecked {
if (((1 << 175) + uint256(x)) >> 176 == uint256(0)) return int176(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int184. Reverts on overflow.
function toInt184(int256 x) internal pure returns (int184) {
unchecked {
if (((1 << 183) + uint256(x)) >> 184 == uint256(0)) return int184(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int192. Reverts on overflow.
function toInt192(int256 x) internal pure returns (int192) {
unchecked {
if (((1 << 191) + uint256(x)) >> 192 == uint256(0)) return int192(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int200. Reverts on overflow.
function toInt200(int256 x) internal pure returns (int200) {
unchecked {
if (((1 << 199) + uint256(x)) >> 200 == uint256(0)) return int200(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int208. Reverts on overflow.
function toInt208(int256 x) internal pure returns (int208) {
unchecked {
if (((1 << 207) + uint256(x)) >> 208 == uint256(0)) return int208(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int216. Reverts on overflow.
function toInt216(int256 x) internal pure returns (int216) {
unchecked {
if (((1 << 215) + uint256(x)) >> 216 == uint256(0)) return int216(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int224. Reverts on overflow.
function toInt224(int256 x) internal pure returns (int224) {
unchecked {
if (((1 << 223) + uint256(x)) >> 224 == uint256(0)) return int224(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int232. Reverts on overflow.
function toInt232(int256 x) internal pure returns (int232) {
unchecked {
if (((1 << 231) + uint256(x)) >> 232 == uint256(0)) return int232(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int240. Reverts on overflow.
function toInt240(int256 x) internal pure returns (int240) {
unchecked {
if (((1 << 239) + uint256(x)) >> 240 == uint256(0)) return int240(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int248. Reverts on overflow.
function toInt248(int256 x) internal pure returns (int248) {
unchecked {
if (((1 << 247) + uint256(x)) >> 248 == uint256(0)) return int248(x);
_revertOverflow();
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* OTHER SAFE CASTING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Casts `x` to a int8. Reverts on overflow.
function toInt8(uint256 x) internal pure returns (int8) {
if (x >= 1 << 7) _revertOverflow();
return int8(int256(x));
}
/// @dev Casts `x` to a int16. Reverts on overflow.
function toInt16(uint256 x) internal pure returns (int16) {
if (x >= 1 << 15) _revertOverflow();
return int16(int256(x));
}
/// @dev Casts `x` to a int24. Reverts on overflow.
function toInt24(uint256 x) internal pure returns (int24) {
if (x >= 1 << 23) _revertOverflow();
return int24(int256(x));
}
/// @dev Casts `x` to a int32. Reverts on overflow.
function toInt32(uint256 x) internal pure returns (int32) {
if (x >= 1 << 31) _revertOverflow();
return int32(int256(x));
}
/// @dev Casts `x` to a int40. Reverts on overflow.
function toInt40(uint256 x) internal pure returns (int40) {
if (x >= 1 << 39) _revertOverflow();
return int40(int256(x));
}
/// @dev Casts `x` to a int48. Reverts on overflow.
function toInt48(uint256 x) internal pure returns (int48) {
if (x >= 1 << 47) _revertOverflow();
return int48(int256(x));
}
/// @dev Casts `x` to a int56. Reverts on overflow.
function toInt56(uint256 x) internal pure returns (int56) {
if (x >= 1 << 55) _revertOverflow();
return int56(int256(x));
}
/// @dev Casts `x` to a int64. Reverts on overflow.
function toInt64(uint256 x) internal pure returns (int64) {
if (x >= 1 << 63) _revertOverflow();
return int64(int256(x));
}
/// @dev Casts `x` to a int72. Reverts on overflow.
function toInt72(uint256 x) internal pure returns (int72) {
if (x >= 1 << 71) _revertOverflow();
return int72(int256(x));
}
/// @dev Casts `x` to a int80. Reverts on overflow.
function toInt80(uint256 x) internal pure returns (int80) {
if (x >= 1 << 79) _revertOverflow();
return int80(int256(x));
}
/// @dev Casts `x` to a int88. Reverts on overflow.
function toInt88(uint256 x) internal pure returns (int88) {
if (x >= 1 << 87) _revertOverflow();
return int88(int256(x));
}
/// @dev Casts `x` to a int96. Reverts on overflow.
function toInt96(uint256 x) internal pure returns (int96) {
if (x >= 1 << 95) _revertOverflow();
return int96(int256(x));
}
/// @dev Casts `x` to a int104. Reverts on overflow.
function toInt104(uint256 x) internal pure returns (int104) {
if (x >= 1 << 103) _revertOverflow();
return int104(int256(x));
}
/// @dev Casts `x` to a int112. Reverts on overflow.
function toInt112(uint256 x) internal pure returns (int112) {
if (x >= 1 << 111) _revertOverflow();
return int112(int256(x));
}
/// @dev Casts `x` to a int120. Reverts on overflow.
function toInt120(uint256 x) internal pure returns (int120) {
if (x >= 1 << 119) _revertOverflow();
return int120(int256(x));
}
/// @dev Casts `x` to a int128. Reverts on overflow.
function toInt128(uint256 x) internal pure returns (int128) {
if (x >= 1 << 127) _revertOverflow();
return int128(int256(x));
}
/// @dev Casts `x` to a int136. Reverts on overflow.
function toInt136(uint256 x) internal pure returns (int136) {
if (x >= 1 << 135) _revertOverflow();
return int136(int256(x));
}
/// @dev Casts `x` to a int144. Reverts on overflow.
function toInt144(uint256 x) internal pure returns (int144) {
if (x >= 1 << 143) _revertOverflow();
return int144(int256(x));
}
/// @dev Casts `x` to a int152. Reverts on overflow.
function toInt152(uint256 x) internal pure returns (int152) {
if (x >= 1 << 151) _revertOverflow();
return int152(int256(x));
}
/// @dev Casts `x` to a int160. Reverts on overflow.
function toInt160(uint256 x) internal pure returns (int160) {
if (x >= 1 << 159) _revertOverflow();
return int160(int256(x));
}
/// @dev Casts `x` to a int168. Reverts on overflow.
function toInt168(uint256 x) internal pure returns (int168) {
if (x >= 1 << 167) _revertOverflow();
return int168(int256(x));
}
/// @dev Casts `x` to a int176. Reverts on overflow.
function toInt176(uint256 x) internal pure returns (int176) {
if (x >= 1 << 175) _revertOverflow();
return int176(int256(x));
}
/// @dev Casts `x` to a int184. Reverts on overflow.
function toInt184(uint256 x) internal pure returns (int184) {
if (x >= 1 << 183) _revertOverflow();
return int184(int256(x));
}
/// @dev Casts `x` to a int192. Reverts on overflow.
function toInt192(uint256 x) internal pure returns (int192) {
if (x >= 1 << 191) _revertOverflow();
return int192(int256(x));
}
/// @dev Casts `x` to a int200. Reverts on overflow.
function toInt200(uint256 x) internal pure returns (int200) {
if (x >= 1 << 199) _revertOverflow();
return int200(int256(x));
}
/// @dev Casts `x` to a int208. Reverts on overflow.
function toInt208(uint256 x) internal pure returns (int208) {
if (x >= 1 << 207) _revertOverflow();
return int208(int256(x));
}
/// @dev Casts `x` to a int216. Reverts on overflow.
function toInt216(uint256 x) internal pure returns (int216) {
if (x >= 1 << 215) _revertOverflow();
return int216(int256(x));
}
/// @dev Casts `x` to a int224. Reverts on overflow.
function toInt224(uint256 x) internal pure returns (int224) {
if (x >= 1 << 223) _revertOverflow();
return int224(int256(x));
}
/// @dev Casts `x` to a int232. Reverts on overflow.
function toInt232(uint256 x) internal pure returns (int232) {
if (x >= 1 << 231) _revertOverflow();
return int232(int256(x));
}
/// @dev Casts `x` to a int240. Reverts on overflow.
function toInt240(uint256 x) internal pure returns (int240) {
if (x >= 1 << 239) _revertOverflow();
return int240(int256(x));
}
/// @dev Casts `x` to a int248. Reverts on overflow.
function toInt248(uint256 x) internal pure returns (int248) {
if (x >= 1 << 247) _revertOverflow();
return int248(int256(x));
}
/// @dev Casts `x` to a int256. Reverts on overflow.
function toInt256(uint256 x) internal pure returns (int256) {
if (int256(x) >= 0) return int256(x);
_revertOverflow();
}
/// @dev Casts `x` to a uint256. Reverts on overflow.
function toUint256(int256 x) internal pure returns (uint256) {
if (x >= 0) return uint256(x);
_revertOverflow();
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PRIVATE HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
function _revertOverflow() private pure {
/// @solidity memory-safe-assembly
assembly {
// Store the function selector of `Overflow()`.
mstore(0x00, 0x35278d12)
// Revert with (offset, size).
revert(0x1c, 0x04)
}
}
}
lib/solady/src/utils/SafeTransferLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)
///
/// @dev Note:
/// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.
library SafeTransferLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ETH transfer has failed.
error ETHTransferFailed();
/// @dev The ERC20 `transferFrom` has failed.
error TransferFromFailed();
/// @dev The ERC20 `transfer` has failed.
error TransferFailed();
/// @dev The ERC20 `approve` has failed.
error ApproveFailed();
/// @dev The ERC20 `totalSupply` query has failed.
error TotalSupplyQueryFailed();
/// @dev The Permit2 operation has failed.
error Permit2Failed();
/// @dev The Permit2 amount must be less than `2**160 - 1`.
error Permit2AmountOverflow();
/// @dev The Permit2 approve operation has failed.
error Permit2ApproveFailed();
/// @dev The Permit2 lockdown operation has failed.
error Permit2LockdownFailed();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.
uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;
/// @dev Suggested gas stipend for contract receiving ETH to perform a few
/// storage reads and writes, but low enough to prevent griefing.
uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;
/// @dev The unique EIP-712 domain separator for the DAI token contract.
bytes32 internal constant DAI_DOMAIN_SEPARATOR =
0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;
/// @dev The address for the WETH9 contract on Ethereum mainnet.
address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
/// @dev The canonical Permit2 address.
/// [Github](https://github.com/Uniswap/permit2)
/// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
/// @dev The canonical address of the `SELFDESTRUCT` ETH mover.
/// See: https://gist.github.com/Vectorized/1cb8ad4cf393b1378e08f23f79bd99fa
/// [Etherscan](https://etherscan.io/address/0x00000000000073c48c8055bD43D1A53799176f0D)
address internal constant ETH_MOVER = 0x00000000000073c48c8055bD43D1A53799176f0D;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ETH OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.
//
// The regular variants:
// - Forwards all remaining gas to the target.
// - Reverts if the target reverts.
// - Reverts if the current contract has insufficient balance.
//
// The force variants:
// - Forwards with an optional gas stipend
// (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).
// - If the target reverts, or if the gas stipend is exhausted,
// creates a temporary contract to force send the ETH via `SELFDESTRUCT`.
// Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.
// - Reverts if the current contract has insufficient balance.
//
// The try variants:
// - Forwards with a mandatory gas stipend.
// - Instead of reverting, returns whether the transfer succeeded.
/// @dev Sends `amount` (in wei) ETH to `to`.
function safeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Sends all the ETH in the current contract to `to`.
function safeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// Transfer all the ETH and check if it succeeded or not.
if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
if lt(selfbalance(), amount) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.
function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
if lt(selfbalance(), amount) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// forgefmt: disable-next-item
if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)
}
}
/// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.
function trySafeTransferAllETH(address to, uint256 gasStipend)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)
}
}
/// @dev Force transfers ETH to `to`, without triggering the fallback (if any).
/// This method attempts to use a separate contract to send via `SELFDESTRUCT`,
/// and upon failure, deploys a minimal vault to accrue the ETH.
function safeMoveETH(address to, uint256 amount) internal returns (address vault) {
/// @solidity memory-safe-assembly
assembly {
to := shr(96, shl(96, to)) // Clean upper 96 bits.
for { let mover := ETH_MOVER } iszero(eq(to, address())) {} {
let selfBalanceBefore := selfbalance()
if or(lt(selfBalanceBefore, amount), eq(to, mover)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if extcodesize(mover) {
let balanceBefore := balance(to) // Check via delta, in case `SELFDESTRUCT` is bricked.
mstore(0x00, to)
pop(call(gas(), mover, amount, 0x00, 0x20, codesize(), 0x00))
// If `address(to).balance >= amount + balanceBefore`, skip vault workflow.
if iszero(lt(balance(to), add(amount, balanceBefore))) { break }
// Just in case `SELFDESTRUCT` is changed to not revert and do nothing.
if lt(selfBalanceBefore, selfbalance()) { invalid() }
}
let m := mload(0x40)
// If the mover is missing or bricked, deploy a minimal vault
// that withdraws all ETH to `to` when being called only by `to`.
// forgefmt: disable-next-item
mstore(add(m, 0x20), 0x33146025575b600160005260206000f35b3d3d3d3d47335af1601a5760003dfd)
mstore(m, or(to, shl(160, 0x6035600b3d3960353df3fe73)))
// Compute and store the bytecode hash.
mstore8(0x00, 0xff) // Write the prefix.
mstore(0x35, keccak256(m, 0x40))
mstore(0x01, shl(96, address())) // Deployer.
mstore(0x15, 0) // Salt.
vault := keccak256(0x00, 0x55)
pop(call(gas(), vault, amount, codesize(), 0x00, codesize(), 0x00))
// The vault returns a single word on success. Failure reverts with empty data.
if iszero(returndatasize()) {
if iszero(create2(0, m, 0x40, 0)) { revert(codesize(), codesize()) } // For gas estimation.
}
mstore(0x40, m) // Restore the free memory pointer.
break
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC20 OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for
/// the current contract to manage.
function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
///
/// The `from` account must have at least `amount` approved for the current contract to manage.
function trySafeTransferFrom(address token, address from, address to, uint256 amount)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
success := lt(or(iszero(extcodesize(token)), returndatasize()), success)
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends all of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have their entire balance approved for the current contract to manage.
function safeTransferAllFrom(address token, address from, address to)
internal
returns (uint256 amount)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
// Read the balance, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
)
) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.
amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransfer(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sends all of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransferAll(address token, address to) internal returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
mstore(0x20, address()) // Store the address of the current contract.
// Read the balance, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
)
) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
mstore(0x14, to) // Store the `to` argument.
amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// Reverts upon failure.
function safeApprove(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
/// then retries the approval again (some tokens, e.g. USDT, requires this).
/// Reverts upon failure.
function safeApproveWithRetry(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
// Perform the approval, retrying upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x34, 0) // Store 0 for the `amount`.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
mstore(0x34, amount) // Store back the original `amount`.
// Retry the approval, reverting upon failure.
success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
// Check the `extcodesize` again just in case the token selfdestructs lol.
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
}
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Returns the amount of ERC20 `token` owned by `account`.
/// Returns zero if the `token` does not exist.
function balanceOf(address token, address account) internal view returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, account) // Store the `account` argument.
mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
amount :=
mul( // The arguments of `mul` are evaluated from right to left.
mload(0x20),
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
)
)
}
}
/// @dev Performs a `token.balanceOf(account)` check.
/// `implemented` denotes whether the `token` does not implement `balanceOf`.
/// `amount` is zero if the `token` does not implement `balanceOf`.
function checkBalanceOf(address token, address account)
internal
view
returns (bool implemented, uint256 amount)
{
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, account) // Store the `account` argument.
mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
implemented :=
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
)
amount := mul(mload(0x20), implemented)
}
}
/// @dev Returns the total supply of the `token`.
/// Reverts if the token does not exist or does not implement `totalSupply()`.
function totalSupply(address token) internal view returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x18160ddd) // `totalSupply()`.
if iszero(
and(gt(returndatasize(), 0x1f), staticcall(gas(), token, 0x1c, 0x04, 0x00, 0x20))
) {
mstore(0x00, 0x54cd9435) // `TotalSupplyQueryFailed()`.
revert(0x1c, 0x04)
}
result := mload(0x00)
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// If the initial attempt fails, try to use Permit2 to transfer the token.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for the current contract to manage.
function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {
if (!trySafeTransferFrom(token, from, to, amount)) {
permit2TransferFrom(token, from, to, amount);
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.
/// Reverts upon failure.
function permit2TransferFrom(address token, address from, address to, uint256 amount)
internal
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(add(m, 0x74), shr(96, shl(96, token)))
mstore(add(m, 0x54), amount)
mstore(add(m, 0x34), to)
mstore(add(m, 0x20), shl(96, from))
// `transferFrom(address,address,uint160,address)`.
mstore(m, 0x36c78516000000000000000000000000)
let p := PERMIT2
let exists := eq(chainid(), 1)
if iszero(exists) { exists := iszero(iszero(extcodesize(p))) }
if iszero(
and(
call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00),
lt(iszero(extcodesize(token)), exists) // Token has code and Permit2 exists.
)
) {
mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.
revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04)
}
}
}
/// @dev Permit a user to spend a given amount of
/// another user's tokens via native EIP-2612 permit if possible, falling
/// back to Permit2 if native permit fails or is not implemented on the token.
function permit2(
address token,
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
for {} shl(96, xor(token, WETH9)) {} {
mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.
// Gas stipend to limit gas burn for tokens that don't refund gas when
// an non-existing function is called. 5K should be enough for a SLOAD.
staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)
)
) { break }
// After here, we can be sure that token is a contract.
let m := mload(0x40)
mstore(add(m, 0x34), spender)
mstore(add(m, 0x20), shl(96, owner))
mstore(add(m, 0x74), deadline)
if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {
mstore(0x14, owner)
mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.
mstore(
add(m, 0x94),
lt(iszero(amount), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
)
mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
// `nonces` is already at `add(m, 0x54)`.
// `amount != 0` is already stored at `add(m, 0x94)`.
mstore(add(m, 0xb4), and(0xff, v))
mstore(add(m, 0xd4), r)
mstore(add(m, 0xf4), s)
success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)
break
}
mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.
mstore(add(m, 0x54), amount)
mstore(add(m, 0x94), and(0xff, v))
mstore(add(m, 0xb4), r)
mstore(add(m, 0xd4), s)
success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)
break
}
}
if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);
}
/// @dev Simple permit on the Permit2 contract.
function simplePermit2(
address token,
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(m, 0x927da105) // `allowance(address,address,address)`.
{
let addressMask := shr(96, not(0))
mstore(add(m, 0x20), and(addressMask, owner))
mstore(add(m, 0x40), and(addressMask, token))
mstore(add(m, 0x60), and(addressMask, spender))
mstore(add(m, 0xc0), and(addressMask, spender))
}
let p := mul(PERMIT2, iszero(shr(160, amount)))
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.
staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)
)
) {
mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.
revert(add(0x18, shl(2, iszero(p))), 0x04)
}
mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).
// `owner` is already `add(m, 0x20)`.
// `token` is already at `add(m, 0x40)`.
mstore(add(m, 0x60), amount)
mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.
// `nonce` is already at `add(m, 0xa0)`.
// `spender` is already at `add(m, 0xc0)`.
mstore(add(m, 0xe0), deadline)
mstore(add(m, 0x100), 0x100) // `signature` offset.
mstore(add(m, 0x120), 0x41) // `signature` length.
mstore(add(m, 0x140), r)
mstore(add(m, 0x160), s)
mstore(add(m, 0x180), shl(248, v))
if iszero( // Revert if token does not have code, or if the call fails.
mul(extcodesize(token), call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00))) {
mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Approves `spender` to spend `amount` of `token` for `address(this)`.
function permit2Approve(address token, address spender, uint160 amount, uint48 expiration)
internal
{
/// @solidity memory-safe-assembly
assembly {
let addressMask := shr(96, not(0))
let m := mload(0x40)
mstore(m, 0x87517c45) // `approve(address,address,uint160,uint48)`.
mstore(add(m, 0x20), and(addressMask, token))
mstore(add(m, 0x40), and(addressMask, spender))
mstore(add(m, 0x60), and(addressMask, amount))
mstore(add(m, 0x80), and(0xffffffffffff, expiration))
if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
mstore(0x00, 0x324f14ae) // `Permit2ApproveFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Revokes an approval for `token` and `spender` for `address(this)`.
function permit2Lockdown(address token, address spender) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(m, 0xcc53287f) // `Permit2.lockdown`.
mstore(add(m, 0x20), 0x20) // Offset of the `approvals`.
mstore(add(m, 0x40), 1) // `approvals.length`.
mstore(add(m, 0x60), shr(96, shl(96, token)))
mstore(add(m, 0x80), shr(96, shl(96, spender)))
if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
mstore(0x00, 0x96b3de23) // `Permit2LockdownFailed()`.
revert(0x1c, 0x04)
}
}
}
}
src/access/TwoStepOwnable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// @title ITwoStepOwnable
/// @notice Two-step ownership interface. Host interfaces extend this so the mixin implements it once.
interface ITwoStepOwnable {
/// @notice Emitted when a two-step ownership transfer is started.
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/// @notice Emitted when ownership changes (accept or renounce).
event OwnerUpdated(address indexed newOwner);
/// @notice Caller is not the owner.
error NotOwner();
/// @notice Caller is not the pending owner.
error NotPendingOwner();
/// @notice The current owner.
function owner() external view returns (address);
/// @notice The pending owner of a two-step transfer.
function pendingOwner() external view returns (address);
/// @notice Starts a two-step ownership transfer. The new owner must call `acceptOwnership`.
function transferOwnership(address newOwner) external;
/// @notice Completes a two-step ownership transfer. Callable only by the pending owner.
function acceptOwnership() external;
/// @notice Renounces ownership, setting the owner to the zero address.
function renounceOwnership() external;
}
/// @title TwoStepOwnable
/// @notice Two-step ownership transfer with a separate renounce, mirroring OpenZeppelin's Ownable2Step.
/// @dev ERC-7201 namespaced storage so this composes with upgradeable and non-upgradeable hosts, and
/// alongside a TwoStepOperator role, with no storage-layout clashes. Seed the initial owner from the
/// host constructor or initializer via `_initializeOwner`.
abstract contract TwoStepOwnable is ITwoStepOwnable {
/// @custom:storage-location erc7201:lotus.storage.TwoStepOwnable
struct OwnableStorage {
address owner;
address pendingOwner;
}
// keccak256(abi.encode(uint256(keccak256("lotus.storage.TwoStepOwnable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant _STORAGE = 0xfaec8a094acaf62210bd0812262aaaff8760ca5d3f50907b79cda40ef2806d00;
function _ownableStorage() private pure returns (OwnableStorage storage $) {
assembly {
$.slot := _STORAGE
}
}
modifier onlyOwner() {
if (msg.sender != _ownableStorage().owner) revert NotOwner();
_;
}
/// @inheritdoc ITwoStepOwnable
function owner() public view virtual override returns (address) {
return _ownableStorage().owner;
}
/// @inheritdoc ITwoStepOwnable
function pendingOwner() public view virtual override returns (address) {
return _ownableStorage().pendingOwner;
}
/// @inheritdoc ITwoStepOwnable
function transferOwnership(address newOwner) public virtual override onlyOwner {
OwnableStorage storage $ = _ownableStorage();
$.pendingOwner = newOwner;
emit OwnershipTransferStarted($.owner, newOwner);
}
/// @inheritdoc ITwoStepOwnable
function acceptOwnership() public virtual override {
if (msg.sender != _ownableStorage().pendingOwner) revert NotPendingOwner();
_setOwner(msg.sender);
}
/// @inheritdoc ITwoStepOwnable
function renounceOwnership() public virtual override onlyOwner {
_setOwner(address(0));
}
/// @dev Seeds the owner. Call once from the host constructor or initializer.
function _initializeOwner(address initialOwner) internal {
_setOwner(initialOwner);
}
function _setOwner(address newOwner) internal {
OwnableStorage storage $ = _ownableStorage();
$.owner = newOwner;
delete $.pendingOwner;
emit OwnerUpdated(newOwner);
}
}
src/hooks/interfaces/ILotusHooks.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {Id} from "../../interfaces/ILotus.sol";
/// @title ILotusHooks
/// @notice Interface for Lotus market-scoped policy hooks on selected risk-sensitive operations.
/// @dev Hooks execute after Lotus state updates but before token transfers, allowing validation with rollback.
/// They are intentionally selective and market-scoped, not a promise of hook coverage for every Lotus action.
interface ILotusHooks {
/* HOOK PARAMETERS */
/// @notice Parameters for supply hooks.
struct SupplyParams {
/// @notice The market being supplied to.
Id id;
/// @notice The tranche being supplied to.
uint256 trancheIndex;
/// @notice The address initiating the supply.
address sender;
/// @notice The address receiving supply shares.
address onBehalf;
/// @notice The amount of assets supplied.
uint256 assets;
/// @notice The amount of shares minted.
uint256 shares;
}
/// @notice Parameters for borrow hooks.
struct BorrowParams {
/// @notice The market being borrowed from.
Id id;
/// @notice The tranche being borrowed from.
uint256 trancheIndex;
/// @notice The address initiating the borrow.
address sender;
/// @notice The address taking on the debt.
address onBehalf;
/// @notice The address receiving borrowed assets.
address receiver;
/// @notice The amount of assets borrowed.
uint256 assets;
/// @notice The amount of borrow shares issued.
uint256 shares;
}
/// @notice Parameters for supply collateral hooks.
struct SupplyCollateralParams {
/// @notice The market receiving collateral.
Id id;
/// @notice The tranche collateral is posted to.
uint256 trancheIndex;
/// @notice The address supplying collateral.
address sender;
/// @notice The address receiving collateral credit.
address onBehalf;
/// @notice The amount of collateral supplied.
uint256 assets;
}
/// @notice Parameters for withdraw hooks.
struct WithdrawParams {
/// @notice The market being withdrawn from.
Id id;
/// @notice The tranche being withdrawn from.
uint256 trancheIndex;
/// @notice The address initiating the withdrawal.
address sender;
/// @notice The address whose shares are being burned.
address onBehalf;
/// @notice The address receiving withdrawn assets.
address receiver;
/// @notice The amount of assets withdrawn.
uint256 assets;
/// @notice The amount of shares burned.
uint256 shares;
}
/// @notice Parameters for withdraw collateral hooks.
struct WithdrawCollateralParams {
/// @notice The market whose collateral is being withdrawn.
Id id;
/// @notice The tranche collateral is withdrawn from.
uint256 trancheIndex;
/// @notice The address initiating the withdrawal.
address sender;
/// @notice The address whose collateral is being withdrawn.
address onBehalf;
/// @notice The address receiving withdrawn collateral.
address receiver;
/// @notice The amount of collateral withdrawn.
uint256 assets;
}
/* HOOKS */
/// @notice Called after supply state changes but before token transfer.
/// @dev Reverts to prevent the supply. Called after balance updates.
/// @param params The supply hook context.
/// @return selector This function's selector to signal successful execution.
function afterSupply(SupplyParams calldata params) external view returns (bytes4 selector);
/// @notice Called after borrow state changes but before token transfer.
/// @dev Reverts to prevent the borrow. Called after balance updates and health checks.
/// @param params The borrow hook context.
/// @return selector This function's selector to signal successful execution.
function afterBorrow(BorrowParams calldata params) external view returns (bytes4 selector);
/// @notice Called after supply collateral state changes but before token transfer.
/// @dev Reverts to prevent the collateral supply. Called after collateral balance updates.
/// @param params The supply-collateral hook context.
/// @return selector This function's selector to signal successful execution.
function afterSupplyCollateral(SupplyCollateralParams calldata params) external view returns (bytes4 selector);
/// @notice Called after withdraw state changes but before token transfer.
/// @dev Reverts to prevent the withdrawal. Called after balance updates.
/// @param params The withdraw hook context.
/// @return selector This function's selector to signal successful execution.
function afterWithdraw(WithdrawParams calldata params) external view returns (bytes4 selector);
/// @notice Called after withdraw collateral state changes but before token transfer.
/// @dev Reverts to prevent the collateral withdrawal. Called after balance updates.
/// @param params The withdraw-collateral hook context.
/// @return selector This function's selector to signal successful execution.
function afterWithdrawCollateral(WithdrawCollateralParams calldata params) external view returns (bytes4 selector);
}
src/hooks/libraries/Hooks.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.28;
import {ILotusHooks} from "../interfaces/ILotusHooks.sol";
/// @title Hooks
/// @notice Library for managing hook permissions and calls.
/// @dev Implements a permission system to optimize gas by only calling implemented hooks.
library Hooks {
/* HOOK PERMISSION FLAGS */
uint256 internal constant AFTER_SUPPLY_FLAG = 1 << 0;
uint256 internal constant AFTER_BORROW_FLAG = 1 << 1;
uint256 internal constant AFTER_SUPPLY_COLLATERAL_FLAG = 1 << 2;
uint256 internal constant AFTER_WITHDRAW_FLAG = 1 << 3;
uint256 internal constant AFTER_WITHDRAW_COLLATERAL_FLAG = 1 << 4;
/* ERRORS */
/// @notice Hook call failed without returning revert data to bubble.
/// @param hook The hook contract that was called.
/// @param expectedSelector The selector that was expected from the hook.
error HookCallFailed(address hook, bytes4 expectedSelector);
/// @notice Hook returned a selector other than the invoked hook's selector.
/// @param hook The hook contract that was called.
/// @param expected The selector expected for the invoked hook.
/// @param received The selector returned by the hook.
error InvalidHookResponse(address hook, bytes4 expected, bytes4 received);
/// @notice Configured hook address has no bytecode.
/// @param hook The invalid hook address.
error InvalidHook(address hook);
/// @notice Hook-disable request includes nonzero permissions.
error InvalidHookConfig();
/* STRUCTS */
/// @notice Configuration for a hook.
struct HookConfig {
/// @notice The hook contract address.
address hook;
/// @notice The permissions bitmap indicating which hooks are implemented.
uint256 permissions;
}
/* PERMISSION HELPERS */
/// @dev Validates hook address and creates configuration.
/// @param hook The hook contract address (zero address to disable hooks).
/// @param permissions Binary mask selecting enabled hook callbacks.
/// @return config Normalized hook configuration.
function validateHookConfig(address hook, uint256 permissions) internal view returns (HookConfig memory config) {
if (hook == address(0)) {
if (permissions != 0) revert InvalidHookConfig();
return HookConfig({hook: address(0), permissions: 0});
}
if (hook.code.length == 0) revert InvalidHook(hook);
return HookConfig({hook: hook, permissions: permissions});
}
/// @dev Checks whether a permissions bitmap contains a hook flag.
/// @param permissions The permissions bitmap to inspect.
/// @param flag Binary mask selecting which permission bit to check.
/// @return Whether `flag` is set in `permissions`.
function hasPermission(uint256 permissions, uint256 flag) internal pure returns (bool) {
return (permissions & flag) != 0;
}
/* HOOK CALL HELPERS */
/// @dev Calls afterSupply hook if enabled.
function afterSupply(HookConfig storage config, ILotusHooks.SupplyParams memory params) internal view {
if (hasPermission(config.permissions, AFTER_SUPPLY_FLAG)) {
_callHook(config.hook, abi.encodeCall(ILotusHooks.afterSupply, (params)), ILotusHooks.afterSupply.selector);
}
}
/// @dev Calls afterBorrow hook if enabled.
function afterBorrow(HookConfig storage config, ILotusHooks.BorrowParams memory params) internal view {
if (hasPermission(config.permissions, AFTER_BORROW_FLAG)) {
_callHook(config.hook, abi.encodeCall(ILotusHooks.afterBorrow, (params)), ILotusHooks.afterBorrow.selector);
}
}
/// @dev Calls afterSupplyCollateral hook if enabled.
function afterSupplyCollateral(HookConfig storage config, ILotusHooks.SupplyCollateralParams memory params)
internal
view
{
if (hasPermission(config.permissions, AFTER_SUPPLY_COLLATERAL_FLAG)) {
_callHook(
config.hook,
abi.encodeCall(ILotusHooks.afterSupplyCollateral, (params)),
ILotusHooks.afterSupplyCollateral.selector
);
}
}
/// @dev Calls afterWithdraw hook if enabled.
function afterWithdraw(HookConfig storage config, ILotusHooks.WithdrawParams memory params) internal view {
if (hasPermission(config.permissions, AFTER_WITHDRAW_FLAG)) {
_callHook(
config.hook, abi.encodeCall(ILotusHooks.afterWithdraw, (params)), ILotusHooks.afterWithdraw.selector
);
}
}
/// @dev Calls afterWithdrawCollateral hook if enabled.
function afterWithdrawCollateral(HookConfig storage config, ILotusHooks.WithdrawCollateralParams memory params)
internal
view
{
if (hasPermission(config.permissions, AFTER_WITHDRAW_COLLATERAL_FLAG)) {
_callHook(
config.hook,
abi.encodeCall(ILotusHooks.afterWithdrawCollateral, (params)),
ILotusHooks.afterWithdrawCollateral.selector
);
}
}
/* INTERNAL HELPERS */
/// @dev Calls a hook and validates that it returned the expected selector.
function _callHook(address hook, bytes memory data, bytes4 expectedSelector) private view {
(bool success, bytes memory result) = hook.staticcall(data);
if (!success) {
// Preserve hook revert data when the hook returns one.
if (result.length > 0) {
assembly ("memory-safe") {
revert(add(result, 0x20), mload(result))
}
}
revert HookCallFailed(hook, expectedSelector);
}
bytes4 returnedSelector = abi.decode(result, (bytes4));
if (returnedSelector != expectedSelector) {
revert InvalidHookResponse(hook, expectedSelector, returnedSelector);
}
}
}
src/interfaces/ILiquidationModule.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {Id, Position, Tranche} from "./ILotus.sol";
/// @notice Trusted Lotus-owned quote context for a single-tranche liquidation.
struct LiquidationQuoteContext {
/// @notice The market being liquidated.
Id id;
/// @notice The tranche index being liquidated.
uint256 trancheIndex;
/// @notice Current tranche accounting state.
Tranche tranche;
/// @notice Current collateral price in oracle scale.
uint256 collateralPrice;
/// @notice Borrower being liquidated.
address borrower;
/// @notice The tranche liquidation loan-to-value threshold, in wad.
uint256 lltv;
/// @notice Borrower's current position state for the tranche.
Position position;
}
/// @title ILiquidationModule
/// @notice Interface for liquidation modules expected by Lotus protocol.
interface ILiquidationModule {
/// @notice Initializes the liquidation module for a Lotus market.
/// @param id The market being initialized in the liquidation module.
/// @param liquidationConfig ABI-encoded params expected by the liquidation module implementation.
function initializeMarket(Id id, bytes calldata liquidationConfig) external;
/// @notice Calculates liquidation settlement amounts (seize- or repay-based).
/// @param context The Lotus-owned liquidation quote context.
/// @param lmData Opaque liquidation data interpreted by the module implementation.
/// @return seizedAssets The amount of collateral to be seized.
/// @return repaidShares The shares of debt to be repaid.
/// @return repaidAssets The amount of debt to be repaid.
function calculateLiquidation(LiquidationQuoteContext calldata context, bytes calldata lmData)
external
view
returns (uint256 seizedAssets, uint256 repaidShares, uint256 repaidAssets);
/// @notice Executes the token transfers for a liquidation.
/// Should only be called after internal state has been updated.
/// @param id The market being liquidated.
/// @param trancheIndex The tranche being liquidated.
/// @param borrower The borrower being liquidated.
/// @param liquidator The address performing the liquidation.
/// @param loanToken The loan token address.
/// @param collateralToken The collateral token address.
/// @param seizedAssets The amount of collateral to transfer to the liquidator.
/// @param repaidAssets The amount of debt to transfer from the liquidator.
/// @param callbackData Optional callback data for the liquidator.
function executeLiquidation(
Id id,
uint256 trancheIndex,
address borrower,
address liquidator,
address loanToken,
address collateralToken,
uint256 seizedAssets,
uint256 repaidAssets,
bytes calldata callbackData
) external;
}
src/interfaces/ILotus.sol
// SPDX-License-Identifier: MIT
// Adapted in part from Morpho Blue, Copyright (c) 2023-2026 Morpho Association, MIT License.
pragma solidity ^0.8.28;
import {IRiskEngine} from "./IRiskEngine.sol";
import {ITwoStepOwnable} from "../access/TwoStepOwnable.sol";
type Id is bytes32;
/// @notice Core market parameters shared across all tranches.
struct MarketParams {
/// @notice Loan token shared across all tranches.
address loanToken;
/// @notice Risk engine for the market, shared across all tranches.
address riskEngine;
/// @notice Liquidation module for the market, shared across all tranches.
address liquidationModule;
/// @notice keccak256 hash of abi-encoded TrancheConfig array.
bytes32 trancheConfigsHash;
}
/// @notice Per-tranche configuration stored separately from core params.
struct TrancheConfig {
/// @notice Collateral token accepted by this tranche.
address collateralToken;
/// @notice Oracle used to price this tranche's collateral token.
address oracle;
/// @notice Liquidation loan-to-value threshold for this tranche, in wad.
uint128 lltv;
}
/// @notice Per-tranche user position state.
/// @dev Warning: The `supplyShares` for the protocol `feeRecipient` is accurate as of the last interest accrual.
struct Position {
/// @notice Supply shares for this tranche.
uint256 supplyShares;
/// @notice Borrow shares for this tranche.
uint128 borrowShares;
/// @notice Collateral amount for this tranche.
uint128 collateral;
/// @notice Size-weighted timestamp of this position's outstanding borrow.
uint64 borrowTs;
}
/// @notice Aggregate accounting state for one market tranche.
/// @dev Warning: The `supplyAssets` and `borrowAssets` are accurate as of the last interest accrual.
/// @dev Warning: The `supplyShares` does not include supply shares to be issued to the `feeRecipient` during the next
/// interest accrual.
/// @dev `supplyShares` is `uint256`: bad debt reduces `supplyAssets` without reducing `supplyShares`, so a wiped
/// tranche's collapsed share price can mint far more than `uint128` shares. Asset fields stay `uint128` because they
/// only ever hold real token amounts. Layout (3 slots): `supplyAssets | fee | lastUpdate`, `supplyShares`,
/// `borrowAssets | borrowShares`, so supply, borrow and accrual each write at most two slots per tranche.
struct Tranche {
/// @notice Total amount of assets supplied at this tranche.
uint128 supplyAssets;
/// @notice Protocol fee taken from interest accrued at this tranche.
uint64 fee;
/// @notice Last timestamp when interest was accrued for this tranche.
uint64 lastUpdate;
/// @notice Total supply shares for this tranche.
uint256 supplyShares;
/// @notice Total borrow assets for only the current tranche.
uint128 borrowAssets;
/// @notice Total borrow shares for only the current tranche.
uint128 borrowShares;
}
/// @notice EIP-712 authorization payload.
struct Authorization {
/// @notice Account granting or revoking authorization.
address authorizer;
/// @notice Account receiving or losing authorization.
address authorized;
/// @notice Whether authorization is granted or revoked.
bool isAuthorized;
/// @notice Authorizer nonce consumed by this payload.
uint256 nonce;
/// @notice Timestamp after which the signature is invalid.
uint256 deadline;
}
/// @notice ECDSA signature fields for EIP-712 authorization payloads.
struct Signature {
/// @notice ECDSA recovery id.
uint8 v;
/// @notice ECDSA r value.
bytes32 r;
/// @notice ECDSA s value.
bytes32 s;
}
/// @title ILotus
/// @notice Interface for the Lotus core lending protocol.
interface ILotus is ITwoStepOwnable {
/// @notice Emitted when the protocol is globally paused.
event GlobalPaused();
/// @notice Emitted when the protocol is globally unpaused.
/// @param unpausedAt The timestamp at which the global pause was released.
event GlobalUnpaused(uint64 unpausedAt);
/// @notice Emitted when a single market is paused.
/// @param id The market id.
event MarketPaused(Id indexed id);
/// @notice Emitted when a single market is unpaused.
/// @param id The market id.
event MarketUnpaused(Id indexed id);
/// @notice Emitted when a token's flash loan fee is updated.
/// @param token The token whose flash loan fee was updated.
/// @param newFee The new flash loan fee in WAD.
event FlashLoanFeeUpdated(address indexed token, uint64 newFee);
/// @notice Emitted when an LLTV is enabled.
/// @param lltv The enabled liquidation LTV ratio.
event LltvEnabled(uint256 indexed lltv);
/// @notice Emitted after aggregate accounting state changes for a tranche.
/// @param id The market id.
/// @param trancheIndex The tranche index.
/// @param supplyAssets Total supplied assets after the change.
/// @param supplyShares Total supply shares after the change.
/// @param borrowAssets Total borrowed assets after the change.
/// @param borrowShares Total borrow shares after the change.
event TrancheStateUpdated(
Id indexed id,
uint256 indexed trancheIndex,
uint256 supplyAssets,
uint256 supplyShares,
uint256 borrowAssets,
uint256 borrowShares
);
/// @notice Emitted when interest is added to a tranche's aggregate borrow balance.
/// @param id The market id.
/// @param trancheIndex The tranche index.
/// @param borrowInterest The amount added to aggregate borrow assets.
event BorrowInterestAccrued(Id indexed id, uint256 indexed trancheIndex, uint256 borrowInterest);
/// @notice Emitted when interest is distributed to a tranche's suppliers.
/// @param id The market id.
/// @param trancheIndex The tranche index.
/// @param supplyInterest The amount added to aggregate supply assets.
/// @param feeShares The supply shares minted to the protocol fee recipient.
event SupplyInterestDistributed(
Id indexed id, uint256 indexed trancheIndex, uint256 supplyInterest, uint256 feeShares
);
/// @notice Emitted when bad debt is allocated to a tranche's suppliers.
/// @param id The market id.
/// @param originTrancheIndex The tranche where the defaulted borrow position originated.
/// @param absorbingTrancheIndex The tranche whose aggregate supply assets absorb the loss.
/// @param assetsReduced The amount removed from the absorbing tranche's supply assets.
event BadDebtAllocated(
Id indexed id, uint256 indexed originTrancheIndex, uint256 indexed absorbingTrancheIndex, uint256 assetsReduced
);
/// @notice Emitted when a bad-debt event arms the borrow cooldown on the tranches junior to its origin.
/// @param id The market id.
/// @param originTrancheIndex The tranche where the bad debt originated.
/// @param cooldownUntil Latest resulting expiry among the affected junior tranches, or the event's own expiry
/// if there are no junior tranches. Each tranche accumulates its own remaining window, capped at
/// `MIN_BORROW_DURATION` from now.
event BorrowCooldownArmed(Id indexed id, uint256 indexed originTrancheIndex, uint64 cooldownUntil);
/// @notice Emitted when the owner clears a tranche's borrow cooldown.
/// @param id The market id.
/// @param trancheIndex The tranche whose cooldown was cleared.
event BorrowCooldownCleared(Id indexed id, uint256 indexed trancheIndex);
/// @notice Emitted when the owner sets a borrower's exemption from the repay cooldown.
/// @param account The borrower.
/// @param exempt Whether `account` is exempt.
event BorrowCooldownExemptSet(address indexed account, bool exempt);
/// @return domainSeparator The EIP-712 domain separator for Lotus.
function DOMAIN_SEPARATOR() external view returns (bytes32 domainSeparator);
/// @notice Minimum size-weighted age a borrow position needs to be repaid while its tranche's cooldown is armed.
function MIN_BORROW_DURATION() external view returns (uint256);
/// @notice Bad debt, as a WAD fraction of cascade supply, at which the borrow cooldown arms for the full duration.
function FULL_COOLDOWN_BAD_DEBT_RATIO() external view returns (uint256);
/* OWNER FUNCTIONS */
/// @notice The Lotus fee recipient for all markets, tranches, and flash loans.
/// @dev The `feeRecipient` receives tranche fees during interest accrual via supply shares.
/// @return recipient The protocol fee recipient.
function feeRecipient() external view returns (address recipient);
/// @notice Global relative buffer below each tranche's LLTV that caps new borrows and collateral withdrawals.
/// @dev `borrow` and `withdrawCollateral` require the position to stay within `lltv * (WAD - borrowLtvBuffer) / WAD`.
/// Liquidation eligibility and every other health computation keep using the plain LLTV, so a fresh position
/// cannot become liquidatable through interest alone until its debt grows past the buffer.
/// @return buffer The buffer in WAD, in [`MIN_BORROW_LTV_BUFFER`, `MAX_BORROW_LTV_BUFFER`].
function borrowLtvBuffer() external view returns (uint64 buffer);
/// @notice The Lotus flash loan fee for `token`, in WAD.
/// @param token The token to quote the configured flash loan fee for.
/// @return fee The flash loan fee rate applied to `token`.
function flashLoanFee(address token) external view returns (uint64 fee);
/// @notice Sets the protocol interest fee for a specific tranche in a market.
/// @param marketParams The market parameters.
/// @param trancheIndex The index of the tranche to set the fee for.
/// @param newFee The new fee to set.
/// @param riskEngineData The risk engine data to pass during interest accrual.
function setFee(
MarketParams memory marketParams,
uint256 trancheIndex,
uint64 newFee,
bytes calldata riskEngineData
) external;
/// @notice Sets the Lotus fee recipient.
/// @param newFeeRecipient The new Lotus fee recipient.
function setFeeRecipient(address newFeeRecipient) external;
/// @notice Sets the Lotus flash loan fee for `token`.
/// @param token The token to configure the flash loan fee for.
/// @param newFee The new flash loan fee, in WAD.
function setFlashLoanFee(address token, uint64 newFee) external;
/// @notice Sets the global borrow LTV buffer.
/// @dev Reverts if `newBuffer` equals the current buffer or is outside
/// [`MIN_BORROW_LTV_BUFFER`, `MAX_BORROW_LTV_BUFFER`].
/// @param newBuffer The new relative buffer below each tranche's LLTV, in WAD.
function setBorrowLtvBuffer(uint64 newBuffer) external;
/// @notice Enables `riskEngine` for Lotus markets.
/// @param riskEngine The risk engine to enable.
function enableRiskEngine(address riskEngine) external;
/// @notice Enables `lltv` for Lotus markets.
/// @param lltv The LLTV to enable.
function enableLltv(uint128 lltv) external;
/// @notice Enables `liquidationModule` for Lotus markets.
/// @param liquidationModule The liquidation module to enable.
function enableLiquidationModule(address liquidationModule) external;
/// @notice Enables a module manager who can enable risk engines and liquidation modules.
/// @param manager The module manager address.
function enableModuleManager(address manager) external;
/// @notice Disables a module manager.
/// @param manager The module manager address.
function disableModuleManager(address manager) external;
/// @notice Sets or clears the market hook configuration.
/// @param marketParams The market parameters (used to derive market id).
/// @param hook The hook contract address (zero address to disable hooks).
/// @param permissions The permissions bitmap indicating which hooks are implemented.
function setMarketHook(MarketParams memory marketParams, address hook, uint256 permissions) external;
/* PAUSE */
/// @notice Pauses or unpauses state-changing operations. Owner only.
/// @dev When `global` is true, applies to every market across the protocol and `marketParams`
/// is ignored. When `global` is false, applies to the single market identified by
/// `marketParams`; forbidden while globally paused. Unpausing (in either scope) records the
/// moment so the lazy per-market sync skips interest accrual over the pause window.
/// Interest from the last pre-pause interaction up to the pause is not captured by the lazy
/// sync. Operators who need that interest realized must call `accrueInterest` before pausing;
/// it cannot be recovered during a pause, because accrual reverts while paused, or after
/// unpause, because the sync skips directly to the unpause timestamp. This preserves
/// emergency-pause availability when accrual itself depends on a broken oracle or risk engine
/// and could revert.
/// @param marketParams The market parameters (ignored when `global` is true).
/// @param global Whether to set the global-pause flag (true) or the per-market flag (false).
/// @param paused The new pause state.
function setPaused(MarketParams memory marketParams, bool global, bool paused) external;
/// @notice Clears a tranche's borrow cooldown once no young borrow in it needs gating. Clear-only: never arms.
/// @param id The market id.
/// @param trancheIndex The tranche to clear.
function clearBorrowCooldown(Id id, uint256 trancheIndex) external;
/// @notice Exempts `account`'s positions from the repay cooldown, whoever calls repay on its behalf.
/// @param account The borrower (repay's `onBehalf`).
/// @param exempt Whether `account` is exempt.
function setBorrowCooldownExempt(address account, bool exempt) external;
/* MARKET CREATION */
/// @notice Creates a new Lotus market.
/// @dev Lotus settlement assumes exact token receipt on inbound transfers.
/// @dev Do not configure fee-on-transfer or other transfer-shortfall loan or collateral tokens.
/// @dev `marketParams.trancheConfigsHash` is recomputed from `tranches`, returned, and used as input into the
/// market id calculation; any caller-supplied value is ignored.
/// @param marketParams The core market parameters (loan token, risk engine, liquidation module).
/// @param tranches The per-tranche configuration array.
/// @param riskEngineParams The parameters for the risk engine.
/// @param liquidationParams The parameters for the liquidation module.
/// @return id The id of the created market (derived from the recomputed `marketParams`).
/// @return trancheConfigsHash The tranche config hash recomputed from `tranches`.
function createMarket(
MarketParams memory marketParams,
TrancheConfig[] memory tranches,
bytes calldata riskEngineParams,
bytes calldata liquidationParams
) external returns (Id id, bytes32 trancheConfigsHash);
/* LENDER FUNCTIONS */
/// @notice Supplies assets to a specific tranche in the market.
/// @param marketParams The market parameters.
/// @param trancheIndex The index of the tranche to supply to.
/// @param assets The amount of assets to supply (use 0 if supplying by shares).
/// @param shares The amount of shares to supply (use 0 if supplying by assets).
/// @param onBehalf The address to supply on behalf of.
/// @param data Arbitrary data to pass to the callback (if any).
/// @param riskEngineData The risk engine data to pass during interest accrual.
/// @return suppliedAssets The actual amount of assets supplied.
/// @return suppliedShares The actual amount of shares supplied.
function supply(
MarketParams memory marketParams,
uint256 trancheIndex,
uint256 assets,
uint256 shares,
address onBehalf,
bytes calldata data,
bytes calldata riskEngineData
) external returns (uint256 suppliedAssets, uint256 suppliedShares);
/// @notice Withdraws assets from a specific tranche in the market.
/// @param marketParams The market parameters.
/// @param trancheIndex The index of the tranche to withdraw from.
/// @param assets The amount of assets to withdraw (use 0 if withdrawing by shares).
/// @param shares The amount of shares to withdraw (use 0 if withdrawing by assets).
/// @param onBehalf The address to withdraw on behalf of.
/// @param receiver The address to send the withdrawn assets to.
/// @param riskEngineData The risk engine data to pass during interest accrual.
/// @return withdrawnAssets The actual amount of assets withdrawn.
/// @return withdrawnShares The actual amount of shares withdrawn.
function withdraw(
MarketParams memory marketParams,
uint256 trancheIndex,
uint256 assets,
uint256 shares,
address onBehalf,
address receiver,
bytes calldata riskEngineData
) external returns (uint256 withdrawnAssets, uint256 withdrawnShares);
/* BORROWER FUNCTIONS */
/// @notice Borrows assets from a specific tranche in the market.
/// @param marketParams The market parameters.
/// @param trancheIndex The index of the tranche to borrow from.
/// @param assets The amount of assets to borrow (use 0 if borrowing by shares).
/// @param shares The amount of shares to borrow (use 0 if borrowing by assets). A borrow by shares pays out the
/// shares' value rounded down and mints only the shares that amount costs, which can be fewer than requested.
/// @param onBehalf The address to borrow on behalf of.
/// @param receiver The address to send the borrowed assets to.
/// @param riskEngineData The risk engine data to pass during interest accrual.
/// @return borrowedAssets The actual amount of assets borrowed.
/// @return borrowedShares The actual amount of shares borrowed.
function borrow(
MarketParams memory marketParams,
uint256 trancheIndex,
uint256 assets,
uint256 shares,
address onBehalf,
address receiver,
bytes calldata riskEngineData
) external returns (uint256 borrowedAssets, uint256 borrowedShares);
/// @notice Repays borrowed assets for a specific tranche in the market with callback support.
/// @param marketParams The market parameters.
/// @param trancheIndex The index of the tranche to repay to.
/// @param assets The amount of assets to repay (use 0 if repaying by shares).
/// @param shares The amount of shares to repay (use 0 if repaying by assets). A partial repay by shares burns at
/// least the shares its charged assets are worth, capped at the position, which can be more than requested.
/// @param onBehalf The address to repay on behalf of.
/// @param data Arbitrary data to pass to the callback (if any).
/// @param riskEngineData The risk engine data to pass during interest accrual.
/// @return repaidAssets The actual amount of assets repaid.
/// @return repaidShares The actual amount of shares repaid.
function repay(
MarketParams memory marketParams,
uint256 trancheIndex,
uint256 assets,
uint256 shares,
address onBehalf,
bytes calldata data,
bytes calldata riskEngineData
) external returns (uint256 repaidAssets, uint256 repaidShares);
/// @notice Supplies collateral to a specific tranche in the market with callback support.
/// @param marketParams The market parameters.
/// @param trancheIndex The index of the tranche to supply collateral to.
/// @param assets The amount of collateral assets to supply.
/// @param onBehalf The address to supply collateral on behalf of.
/// @param data Arbitrary data to pass to the callback (if any).
function supplyCollateral(
MarketParams memory marketParams,
uint256 trancheIndex,
uint256 assets,
address onBehalf,
bytes calldata data
) external;
/// @notice Withdraws collateral from a specific tranche in the market.
/// @param marketParams The market parameters.
/// @param trancheIndex The index of the tranche to withdraw collateral from.
/// @param assets The amount of collateral assets to withdraw.
/// @param onBehalf The address to withdraw collateral on behalf of.
/// @param receiver The address to send the withdrawn collateral to.
/// @param riskEngineData The risk engine data to pass during interest accrual.
function withdrawCollateral(
MarketParams memory marketParams,
uint256 trancheIndex,
uint256 assets,
address onBehalf,
address receiver,
bytes calldata riskEngineData
) external;
/* LIQUIDATION */
/// @notice Liquidates a borrower's position.
/// @dev The returned `repaidAssets` is computed with rounding up to favor protocol safety.
/// @param marketParams The market parameters.
/// @param trancheIndex The tranche index of the position to liquidate.
/// @param borrower The address of the borrower to liquidate.
/// @param riskEngineData risk engine-specific data.
/// @param callbackData Optional data forwarded to the liquidator callback.
/// @param lmData Opaque liquidation-module data interpreted by the selected module.
/// @return seizedAssets The collateral assets seized.
/// @return repaidAssets The loan assets repaid by the liquidator.
function liquidate(
MarketParams memory marketParams,
uint256 trancheIndex,
address borrower,
bytes calldata riskEngineData,
bytes calldata callbackData,
bytes calldata lmData
) external returns (uint256 seizedAssets, uint256 repaidAssets);
/* INTEREST MANAGEMENT */
/// @notice Accrues interest for all tranches in a market.
/// @param marketParams The market parameters.
/// @param riskEngineData The risk engine data to pass during interest accrual.
function accrueInterest(MarketParams memory marketParams, bytes calldata riskEngineData) external;
/* FLASH LOANS */
/// @notice Returns the fee owed for borrowing `assets` of `token`.
/// @param token The token to quote.
/// @param assets The amount to flash loan.
/// @return fee The flash loan fee owed on top of `assets`.
function flashFee(address token, uint256 assets) external view returns (uint256 fee);
/// @notice Executes a flash loan.
/// @param token The address of the token to flash loan.
/// @param assets The amount of assets to flash loan.
/// @param data Arbitrary data to pass to the callback.
function flashLoan(address token, uint256 assets, bytes calldata data) external;
/* AUTHORIZATION */
/// @notice Returns true if `authorized` can modify `authorizer`'s position on all markets/tranches.
/// @param authorizer The account delegating permissions.
/// @param authorized The account receiving delegated permissions.
/// @return isAuthorized_ Whether `authorized` is currently approved.
function isAuthorized(address authorizer, address authorized) external view returns (bool isAuthorized_);
/// @notice The `authorizer`'s current nonce.
/// @dev To prevent replay attacks with EIP-712 signatures.
/// @param authorizer The account whose nonce is queried.
/// @return currentNonce The current authorization nonce.
function nonce(address authorizer) external view returns (uint256 currentNonce);
/// @notice Sets `authorized` authorization to act on behalf of `msg.sender`.
/// @param authorized The authorized address.
/// @param newIsAuthorized The new authorization status.
function setAuthorization(address authorized, bool newIsAuthorized) external;
/// @notice Sets authorization via signature.
/// @param authorization The authorization struct.
/// @param signature The signature struct.
function setAuthorizationWithSig(Authorization memory authorization, Signature calldata signature) external;
/* VIEW FUNCTIONS */
/// @notice Returns true if `riskEngine` is enabled for Lotus markets.
/// @param riskEngine The risk engine to check.
/// @return isEnabled Whether `riskEngine` is enabled.
function isRiskEngineEnabled(address riskEngine) external view returns (bool isEnabled);
/// @notice Returns true if `lltv` is enabled for Lotus markets.
/// @param lltv The LLTV to check.
/// @return isEnabled Whether `lltv` is enabled.
function isLltvEnabled(uint256 lltv) external view returns (bool isEnabled);
/// @notice Returns true if `liquidationModule` is enabled for Lotus markets.
/// @param liquidationModule The liquidation module to check.
/// @return isEnabled Whether `liquidationModule` is enabled.
function isLiquidationModuleEnabled(address liquidationModule) external view returns (bool isEnabled);
/// @notice Returns true if `manager` is a module manager.
/// @param manager The address to check.
/// @return Whether `manager` is a module manager.
function isModuleManager(address manager) external view returns (bool);
/// @notice Returns the last interest accrual time for a market.
/// @param id The market id.
/// @param trancheIndex The tranche index.
/// @return timestamp The unix timestamp of last accrual for the tranche.
function lastUpdate(Id id, uint256 trancheIndex) external view returns (uint64 timestamp);
/// @notice Returns when a tranche's borrow cooldown lapses; while armed, only positions at least
/// `MIN_BORROW_DURATION` old may repay.
/// @param id The market id.
/// @param trancheIndex The tranche index.
/// @return The cooldown expiry timestamp, or zero if never armed.
function borrowCooldownUntil(Id id, uint256 trancheIndex) external view returns (uint64);
/// @notice Returns whether `account`'s positions skip the repay cooldown.
/// @param account The borrower.
function isBorrowCooldownExempt(address account) external view returns (bool);
/// @notice Returns the market parameters for a given market id.
/// @param id The market id.
/// @return The MarketParams struct for the market.
function getMarketParams(Id id) external view returns (MarketParams memory);
/// @notice Returns the tranche config for a given market id and tranche index.
/// @param id The market id.
/// @param trancheIndex The tranche index.
/// @return The TrancheConfig struct for the tranche.
function getTrancheConfig(Id id, uint256 trancheIndex) external view returns (TrancheConfig memory);
/// @notice Returns all tranche configs for a given market id.
/// @param id The market id.
/// @return An array of TrancheConfig structs for the market.
function getTrancheConfigs(Id id) external view returns (TrancheConfig[] memory);
/// @notice Returns the tranches for a given market id.
/// @param id The market id.
/// @return An array of Tranche structs for the market.
function getMarketTranches(Id id) external view returns (Tranche[] memory);
/// @notice Returns a single tranche for a given market id and tranche index.
/// @param id The market id.
/// @param trancheIndex The tranche index.
/// @return The Tranche struct for the tranche.
function getMarketTranche(Id id, uint256 trancheIndex) external view returns (Tranche memory);
/// @notice Returns the number of tranches for a given market id.
/// @param id The market id.
/// @return The number of tranches in the market.
function getNumMarketTranches(Id id) external view returns (uint256);
/// @notice Returns the effective pause state for a market, as the interest-accrual gate sees it.
/// @dev Lets off-chain valuation mirror accrual: when `paused`, no interest accrues over the
/// pause window; when `unpausedAt > syncedAt`, the next accrual restarts each tranche from
/// `unpausedAt` rather than its stale pre-pause `lastUpdate`.
/// @param id The market id.
/// @return paused Whether the protocol or this market is currently paused.
/// @return unpausedAt The most recent unpause timestamp relevant to this market (global or per-market).
/// @return syncedAt The unpause timestamp already synchronized into this market's tranche `lastUpdate` values.
function getMarketPauseState(Id id) external view returns (bool paused, uint64 unpausedAt, uint64 syncedAt);
/// @notice Returns the risk engine for a given market id.
/// @param id The market id.
/// @return The IRiskEngine contract for the market.
function getMarketRiskEngine(Id id) external view returns (IRiskEngine);
/// @notice Returns a user's position in a specific market tranche.
/// @param id The market id.
/// @param user The address of the user.
/// @param trancheIndex The tranche index.
/// @return The Position struct for the user in the tranche.
function getPosition(Id id, address user, uint256 trancheIndex) external view returns (Position memory);
/// @notice Returns the current borrowed assets and max borrowable assets for a borrower in a market tranche.
/// @dev Accurate as of the last interest accrual.
/// @dev Use `accrueInterest` first (or a lens helper) when post-accrual values are required.
/// @param marketParams The market parameters.
/// @param trancheIndex The tranche index.
/// @param borrower The borrower account.
/// @return borrowed The current borrowed assets in the tranche.
/// @return maxBorrow The current max borrowable assets in the tranche.
function getMaxBorrowAndBorrowed(MarketParams memory marketParams, uint256 trancheIndex, address borrower)
external
view
returns (uint256 borrowed, uint256 maxBorrow);
/// @notice Computes junior supply for a given market and tranche.
/// @dev Accurate as of the last interest accrual.
/// @param id The market whose junior supply is computed.
/// @param trancheIndex The tranche whose junior supply is computed.
/// @return The junior supply amount.
function getJrSupply(Id id, uint256 trancheIndex) external view returns (uint256);
/// @notice Returns risk engine-effective free supply available for withdraw or borrow.
/// @dev Bounded by Lotus's current waterfall-backed physical ceiling and then refined by the market risk engine.
/// @param id The market whose free supply is returned.
/// @param trancheIndex The tranche whose free supply is returned.
/// @return The free supply amount.
function getFreeSupply(Id id, uint256 trancheIndex) external view returns (uint256);
/// @notice Returns risk engine-effective free supply available for withdraw or borrow.
/// @dev Bounded by Lotus's current waterfall-backed physical ceiling and then refined by the market risk engine.
/// @param id The market whose free supply is returned.
/// @param trancheIndex The tranche whose free supply is returned.
/// @param riskEngineData Custom data to be passed to the risk engine implementation.
/// @return The free supply amount.
function getFreeSupply(Id id, uint256 trancheIndex, bytes calldata riskEngineData) external view returns (uint256);
/// @notice Computes junior net supply for all tranches in a market.
/// @dev Accurate as of the last interest accrual.
/// @param id The market id.
/// @return An array of junior net supply amounts for each tranche.
function getJrNetSupply(Id id) external view returns (uint256[] memory);
/// @notice Returns the market hook configuration (if any) for a given market id.
/// @param id The market id.
/// @return hook The hook contract address (zero address if disabled).
/// @return permissions The hook permissions bitmap.
function getMarketHookConfig(Id id) external view returns (address hook, uint256 permissions);
}
src/interfaces/ILotusCallbacks.sol
// SPDX-License-Identifier: MIT
// Adapted in part from Morpho Blue, Copyright (c) 2023-2026 Morpho Association, MIT License.
pragma solidity ^0.8.28;
/// @title ILotusSupplyCallback
/// @notice Callback interface for Lotus flows that require caller participation before Lotus pulls funds.
/// @dev Lotus callbacks are selective execution hooks for supply/repay/collateral-supply flows and flash-loan
/// round trips. They are not a promise that every Lotus entrypoint exposes a callback surface.
interface ILotusSupplyCallback {
/// @notice Callback called when a supply occurs.
/// @dev The callback is called only if data is not empty.
/// @param assets The amount of assets to be supplied.
/// @param data Arbitrary data passed to the `supply` function.
function onLotusSupply(uint256 assets, bytes calldata data) external;
}
/// @title ILotusRepayCallback
/// @notice Callback interface for Lotus repay flows that require caller participation before Lotus pulls funds.
interface ILotusRepayCallback {
/// @notice Callback called when a repayment occurs.
/// @dev The callback is called only if data is not empty.
/// @param assets The amount of repaid assets.
/// @param data Arbitrary data passed to the `repay` function.
function onLotusRepay(uint256 assets, bytes calldata data) external;
}
/// @title ILotusLiquidateCallback
/// @notice Callback interface for liquidation settlement owned by the liquidation-module boundary.
/// @dev Lotus core does not expose a generic liquidation callback surface on ordinary entrypoints; liquidation
/// callbacks are part of module settlement after Lotus has already updated protocol state.
interface ILotusLiquidateCallback {
/// @notice Callback called when a liquidation occurs.
/// @dev The callback is called only if data is not empty.
/// @param repaidAssets The amount of repaid assets.
/// @param data Arbitrary data passed to the `liquidate` function.
function onLotusLiquidate(uint256 repaidAssets, bytes calldata data) external;
}
/// @title ILotusFlashLoanCallback
/// @notice Callback interface for Lotus flash-loan round trips.
interface ILotusFlashLoanCallback {
/// @notice Callback called when a flash loan occurs.
/// @dev The callback is always called, even if data is empty.
/// @param token The token that was flash loaned.
/// @param assets The amount of assets that was flash loaned.
/// @param fee The additional amount of tokens owed on top of `assets`.
/// @param data Arbitrary data passed to the `flashLoan` function.
/// @return selector This function's selector to signal successful execution.
function onLotusFlashLoan(address token, uint256 assets, uint256 fee, bytes calldata data)
external
returns (bytes4 selector);
}
/// @title ILotusSupplyCollateralCallback
/// @notice Callback interface for Lotus collateral-supply flows that require caller participation.
interface ILotusSupplyCollateralCallback {
/// @notice Callback called when a supply of collateral occurs.
/// @dev The callback is called only if data is not empty.
/// @param assets The amount of supplied collateral.
/// @param data Arbitrary data passed to the `supplyCollateral` function.
function onLotusSupplyCollateral(uint256 assets, bytes calldata data) external;
}
src/interfaces/IOracle.sol
// SPDX-License-Identifier: MIT
// Adapted in part from Morpho Blue, Copyright (c) 2023-2026 Morpho Association, MIT License.
pragma solidity ^0.8.28;
/// @title IOracle
/// @notice Interface that oracles used by Lotus must implement.
/// @dev It is the user's responsibility to select markets with safe oracles.
interface IOracle {
/// @notice Returns the price of 1 asset of collateral token quoted in 1 asset of loan token, scaled by 1e36.
/// @dev It corresponds to the price of 10**(collateral token decimals) assets of collateral token quoted in
/// 10**(loan token decimals) assets of loan token with `36 + loan token decimals - collateral token decimals`
/// decimals of precision.
/// @return oraclePrice The collateral price in loan-token terms, scaled by 1e36.
function price() external view returns (uint256 oraclePrice);
}
src/interfaces/IRiskEngine.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {Id, Tranche} from "./ILotus.sol";
/// @notice Per-tranche accrual delta returned by cascade accrual.
struct AccrualDelta {
/// @notice Interest added to `borrowAssets`.
uint256 borrowInterest;
/// @notice Interest added to `supplyAssets`.
uint256 supplyInterest;
}
/// @notice Per-tranche bad debt reductions returned by the risk engine.
struct BadDebtDeltas {
/// @notice Full-length array of supply asset reductions.
uint256[] supplyReductions;
}
/// @title IRiskEngine
/// @notice The Risk Engine interface expected by Lotus protocol.
interface IRiskEngine {
/// @notice Initializes the risk engine for a Lotus market.
/// @param id The market id.
/// @param riskEngineParams ABI-encoded params expected by the risk engine implementation.
function initialize(Id id, bytes calldata riskEngineParams) external;
/// @notice Accrues interest across all tranches with cascading distribution.
/// @dev May update internal risk engine state (e.g. adaptive rates).
/// @param id The market id.
/// @param tranches The current tranche state array.
/// @param riskEngineData Custom data to be passed to the risk engine implementation.
/// @return deltas The per-tranche accrual deltas.
/// @return freeSupply The risk-engine-effective withdraw/borrow liquidity across accrued tranches,
/// bounded by Lotus's trusted physical `freeSupplyCap`.
function accrueInterest(Id id, Tranche[] calldata tranches, bytes calldata riskEngineData)
external
returns (AccrualDelta[] memory deltas, uint256 freeSupply);
/// @notice Returns the effective free supply at a tranche without accruing interest.
/// @param id The market id.
/// @param tranches The current tranche state array.
/// @param trancheIndex The tranche index to query.
/// @param riskEngineData Custom data to be passed to the risk engine implementation.
/// @return freeSupply The risk-engine-effective withdraw/borrow liquidity at the tranche,
/// bounded by Lotus's trusted physical `freeSupplyCap`.
function getFreeSupply(Id id, Tranche[] calldata tranches, uint256 trancheIndex, bytes calldata riskEngineData)
external
view
returns (uint256 freeSupply);
/// @notice Distributes bad debt losses across tranches from originIndex upward.
/// @param id The market id.
/// @param tranches The current tranche state array.
/// @param originTrancheIndex The tranche index where bad debt originated.
/// @param badDebtAssets The amount of bad debt to distribute.
/// @return deltas The per-tranche supply reductions after bad debt distribution.
function distributeBadDebt(Id id, Tranche[] calldata tranches, uint256 originTrancheIndex, uint256 badDebtAssets)
external
pure
returns (BadDebtDeltas memory deltas);
/// @notice View-only preview of accrueInterest for off-chain estimation.
/// @param id The market id.
/// @param tranches The current tranche state array.
/// @param riskEngineData Custom data to be passed to the risk engine implementation.
/// @return deltas The preview per-tranche accrual deltas.
/// @return freeSupply The risk-engine-effective withdraw/borrow liquidity across accrued tranches,
/// bounded by Lotus's trusted physical `freeSupplyCap`.
function previewAccrueInterest(Id id, Tranche[] calldata tranches, bytes calldata riskEngineData)
external
view
returns (AccrualDelta[] memory deltas, uint256 freeSupply);
/// @notice Validates that `riskEngineData` is well-formed for this engine before it is used or persisted.
/// @dev Called on an integrating adapter's position write path so that a caller cannot associate arbitrary or
/// oversized `riskEngineData` with a position (that data is later SLOADed and forwarded to the engine on every
/// valuation read). Engines that ignore `riskEngineData` MUST reject any non-empty payload; engines with
/// call-time config SHOULD validate its structure and bound its size. Reverts if the data is not acceptable.
/// @param riskEngineData The custom data a caller wants associated with a position.
function validateRiskEngineData(bytes calldata riskEngineData) external view;
}
src/libraries/ConstantsLib.sol
// SPDX-License-Identifier: MIT
// Adapted in part from Morpho Blue, Copyright (c) 2023-2026 Morpho Association, MIT License.
pragma solidity ^0.8.28;
/// @dev The WAD constant (1e18) for fixed-point arithmetic.
uint256 constant WAD = 1e18;
/// @dev The oracle price scale.
uint256 constant ORACLE_PRICE_SCALE = 1e36;
/// @dev The maximum protocol interest fee for a tranche (25% in WAD).
uint64 constant MAX_FEE = 0.25e18;
/// @dev Minimum raw asset units that a partial repay must settle (full position closes are exempt).
/// @dev Rejects one-unit dust repays. On its own the floor does not stop `borrowShares` inflation, since a borrow of
/// @dev any size can be paired with a repay settling exactly the floor; Lotus prevents that by having borrows mint and
/// @dev partial repays burn shares in line with the assets they move.
uint256 constant MIN_PARTIAL_REPAY_ASSETS = 2;
/// @dev The maximum flash loan fee for a token (25% in WAD).
uint64 constant MAX_FLASH_LOAN_FEE = 0.25e18;
/// @dev Maximum allowed borrow rate per second in WAD (~500% APY continuous).
/// Computed as ln(6) / 365 days ~= 5.6816320054e-8, scaled by 1e18.
uint256 constant MAX_BORROW_RATE_PER_SECOND = 56_816_320_054;
/// @dev Maximum allowed slope (rate change per utilization unit), per second in WAD.
/// Aligns with the maximum rate ceiling to prevent extreme steepness.
uint256 constant MAX_SLOPE_PER_SECOND = MAX_BORROW_RATE_PER_SECOND;
/// @dev Minimum liquidation incentive (1.0x) and maximum (1.15x) in WAD.
uint256 constant MIN_LIQUIDATION_INCENTIVE = 1e18;
uint256 constant MAX_LIQUIDATION_INCENTIVE = 1.15e18;
/// @dev The minimum borrow LTV buffer (0.5% in WAD). Covers about one day of interest at `MAX_BORROW_RATE_PER_SECOND`,
/// @dev i.e. `MIN_COOLDOWN_DURATION`.
uint64 constant MIN_BORROW_LTV_BUFFER = 0.005e18;
/// @dev The maximum borrow LTV buffer (25% in WAD). The buffer is relative: a tranche's borrow limit is
/// @dev `lltv * (WAD - borrowLtvBuffer) / WAD`.
uint64 constant MAX_BORROW_LTV_BUFFER = 0.25e18;
/// @dev Maximum configurable health liquidation discount in WAD (25%),
/// equivalent to a ~1.33x maximum liquidation effect.
/// Must remain strictly below 100% to keep discount factor positive.
uint256 constant MAX_HEALTH_LIQUIDATION_DISCOUNT = 0.25e18;
/// @dev Inclusive bounds on the borrow-cooldown `MIN_BORROW_DURATION` immutable. A zero duration would disable the
/// @dev cooldown; an excessive one would lock honest borrowers out of `repay` and, at extreme values, overflow the
/// @dev cooldown arming arithmetic.
uint256 constant MIN_COOLDOWN_DURATION = 1 days;
uint256 constant MAX_COOLDOWN_DURATION = 7 days;
/// @dev The EIP-712 typeHash for EIP712Domain.
bytes32 constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(uint256 chainId,address verifyingContract)");
/// @dev The EIP-712 typeHash for Authorization.
bytes32 constant AUTHORIZATION_TYPEHASH =
keccak256("Authorization(address authorizer,address authorized,bool isAuthorized,uint256 nonce,uint256 deadline)");
src/libraries/InterestMathLib.sol
// SPDX-License-Identifier: MIT
// Adapted in part from Morpho Blue, Copyright (c) 2023-2026 Morpho Association, MIT License.
pragma solidity ^0.8.28;
import {FixedPointMathLib} from "solady/src/utils/FixedPointMathLib.sol";
import {WAD} from "./ConstantsLib.sol";
/// @title InterestMathLib
/// @notice Library for interest rate calculations and mathematical operations.
/// @dev Contains protocol-specific interest rate math functions.
library InterestMathLib {
using FixedPointMathLib for uint256;
/// @dev Returns the sum of the first three non-zero terms of a Taylor expansion of `e^(n*x) - 1`.
/// @dev Used as a gas-efficient approximation of continuous compounding in wad space.
/// @dev Approximation:
/// @dev e^(n*x) - 1 ~= (n*x) + (n*x)^2/2 + (n*x)^3/6
/// @dev Where:
/// @dev `x` is rate per second (wad), `n` is elapsed seconds.
/// @param x The per-second rate in wad.
/// @param n The elapsed time in seconds.
/// @return The compounded interest factor in wad.
function wTaylorCompounded(uint256 x, uint256 n) internal pure returns (uint256) {
uint256 firstTerm = x * n;
uint256 secondTerm = firstTerm.mulDiv(firstTerm, 2 * WAD);
uint256 thirdTerm = secondTerm.mulDiv(firstTerm, 3 * WAD);
return firstTerm + secondTerm + thirdTerm;
}
}
src/libraries/LotusErrorsLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {Id} from "../interfaces/ILotus.sol";
/// @title LotusErrorsLib
/// @notice Library for Lotus errors.
library LotusErrorsLib {
/* GENERAL ERRORS */
/// @notice Zero address provided for a required argument.
error ZeroAddress();
/// @notice Non-zero value is required but zero is provided.
error ZeroValue();
/// @notice Mutually dependent inputs are inconsistent.
error InconsistentInput();
/// @notice Caller is not the owner.
error NotOwner();
/// @notice Caller is neither the owner nor a module manager.
error NotOwnerOrModuleManager();
/* ASSET AMOUNT ERRORS */
/// @notice Withdrawal resolves to zero assets.
error InvalidZeroAssetWithdrawal();
/// @notice Borrow resolves to zero assets.
error InvalidZeroAssetBorrow();
/// @notice Supply resolves to zero shares.
error InvalidZeroShareSupply();
/// @notice Repay resolves to zero shares.
error InvalidZeroShareRepay();
/// @notice Partial repay settles fewer than the minimum required assets.
error InsufficientRepayAssets(uint256 assets);
/* OWNER ERRORS */
/// @notice Owner is already set to the requested address.
/// @param owner The owner that is already set.
error OwnerAlreadySet(address owner);
/// @notice Caller is not the pending owner.
error NotPendingOwner();
/// @notice Fee is already set to the requested value.
/// @param id The market whose fee is already set.
/// @param trancheIndex The tranche whose fee is already set.
/// @param fee The fee that is already set.
error FeeAlreadySet(Id id, uint256 trancheIndex, uint64 fee);
/// @notice Fee exceeds protocol bounds.
/// @param fee The invalid fee value.
error InvalidFee(uint64 fee);
/// @notice Fee recipient is already set to the requested address.
/// @param feeRecipient The fee recipient that is already set.
error FeeRecipientAlreadySet(address feeRecipient);
/// @notice Fee recipient is the zero address or the Lotus contract itself.
/// @param feeRecipient The invalid fee recipient.
error InvalidFeeRecipient(address feeRecipient);
/// @notice Token flash-loan fee is already set to the requested value.
/// @param token The token whose flash loan fee is already set.
/// @param fee The flash loan fee that is already set.
error FlashLoanFeeAlreadySet(address token, uint64 fee);
/// @notice Borrow LTV buffer is outside [`MIN_BORROW_LTV_BUFFER`, `MAX_BORROW_LTV_BUFFER`].
/// @param buffer The rejected buffer, in WAD.
error InvalidBorrowLtvBuffer(uint256 buffer);
/// @notice Borrow LTV buffer is already set to the requested value.
/// @param buffer The current buffer, in WAD.
error BorrowLtvBufferAlreadySet(uint256 buffer);
/// @notice Risk engine is already enabled.
/// @param riskEngine The risk engine that is already enabled.
error RiskEngineAlreadyEnabled(address riskEngine);
/// @notice LLTV is outside valid bounds.
/// @param lltv The invalid LLTV value.
error InvalidLltv(uint256 lltv);
/// @notice LLTV is already enabled.
/// @param lltv The LLTV that is already enabled.
error LltvAlreadyEnabled(uint256 lltv);
/* MARKET LIFECYCLE ERRORS */
/// @notice Market already exists.
/// @param id The market id that already exists.
error MarketAlreadyExists(Id id);
/// @notice Market has not been created.
/// @param id The market id that does not exist.
error MarketNotCreated(Id id);
/// @notice Market references a risk engine that is not enabled.
/// @param riskEngine The risk engine that is not enabled.
error RiskEngineNotEnabled(address riskEngine);
/// @notice Market references an LLTV that is not enabled.
/// @param lltv The LLTV that is not enabled.
error LltvNotEnabled(uint256 lltv);
/// @notice Tranche index is out of bounds.
/// @param trancheIndex The tranche index that is out of bounds.
error InvalidTrancheIndex(uint256 trancheIndex);
/* LIQUIDITY ERRORS */
/// @notice Available liquidity is insufficient for an operation.
/// @param assets The amount of assets that is not available.
error InsufficientLiquidity(uint256 assets);
/// @notice Operation makes the position unhealthy.
/// @param assets The operation amount that caused the unhealthy state.
error UnhealthyAfter(uint256 assets);
/// @notice Liquidation is attempted on a non-underwater borrower.
/// @param borrower The borrower that is not underwater.
error NotUnderwater(address borrower);
/// @notice `repaidShares` exceeds the borrower's debt shares.
/// @param repaidShares The amount of shares attempting to be repaid.
/// @param borrowerShares The borrower's actual borrow shares.
error ExcessiveRepay(uint256 repaidShares, uint256 borrowerShares);
/// @notice Flash loan callback returned an unexpected selector.
/// @param expected The selector expected from the callback.
/// @param received The selector actually returned by the callback.
error InvalidFlashLoanCallbackResponse(bytes4 expected, bytes4 received);
/// @notice `seizedAssets` exceeds the borrower's collateral.
/// @param seizedAssets The amount of assets attempting to be seized.
/// @param borrowerCollateral The borrower's actual collateral.
error ExcessiveSeizure(uint256 seizedAssets, uint256 borrowerCollateral);
/* AUTHORIZATION ERRORS */
/// @notice Caller is not authorized for the operation.
error Unauthorized();
/// @notice Authorization is already set to the requested value.
error AuthorizationAlreadySet();
/// @notice Signature deadline has passed.
error SignatureExpired();
/// @notice Signature nonce is invalid.
error InvalidNonce();
/// @notice Signature recovery or signer validation failed.
error InvalidSignature();
/* LIQUIDATION MODULE ERRORS */
/// @notice Caller is not Lotus.
error NotLotus();
/// @notice Liquidation module is already enabled.
/// @param module The liquidation module that is already enabled.
error LiquidationModuleAlreadyEnabled(address module);
/// @notice Liquidation module is not enabled.
/// @param module The liquidation module that is not enabled.
error LiquidationModuleNotEnabled(address module);
/// @notice Module manager is already enabled.
/// @param manager The module manager that is already enabled.
error ModuleManagerAlreadyEnabled(address manager);
/// @notice Module manager is not enabled.
/// @param manager The module manager that is not enabled.
error ModuleManagerNotEnabled(address manager);
/// @notice Oracle collateral price is zero.
error InvalidCollateralPrice();
/// @notice Repay attempted on a position younger than `MIN_BORROW_DURATION` while its tranche's cooldown is armed.
/// @param cooldownUntil Timestamp at which the tranche's borrow cooldown lapses.
error BorrowTooYoung(uint64 cooldownUntil);
/// @notice Constructor borrow-cooldown config is out of bounds: `minBorrowDuration` must lie in
/// [`MIN_COOLDOWN_DURATION`, `MAX_COOLDOWN_DURATION`] and `fullCooldownBadDebtRatio` in (0, `WAD`].
error InvalidBorrowCooldownConfig();
/* DELTA VALIDATION ERRORS */
/// @notice Risk engine delta array length does not match Lotus expectations.
error DeltaLengthMismatch();
/// @notice Risk engine reports borrow interest above Lotus's maximum allowed envelope.
error BorrowInterestTooHigh();
/// @notice Risk engine reports non-zero borrow interest when no interest can accrue.
error UnexpectedBorrowInterest();
/// @notice Risk engine reports free supply above Lotus's waterfall-backed liquidity cap.
error FreeSupplyExceedsPhysical();
/// @notice Risk engine over-distributes cascading interest to suppliers.
error InterestDirectionViolation();
/// @notice Full accrual leaves unexpected interest undistributed.
error UnexpectedCarryForward();
/// @notice Bad debt reductions flow below the origin tranche.
error BadDebtDirectionViolation();
/// @notice Bad debt reduction exceeds a tranche's supply assets.
error ExcessiveBadDebtReduction();
/// @notice Bad debt reductions do not exactly match realized bad debt.
error BadDebtTotalMismatch();
/// @notice Lotus is reentered during the guarded risk engine external call window.
error RiskEngineCallReentrancy();
/* PAUSE ERRORS */
/// @notice Operation attempted while the protocol is globally paused.
error ProtocolPaused();
/// @notice Operation attempted on a paused market.
/// @param id The paused market id.
error MarketIsPaused(Id id);
/// @notice Protocol is already paused.
error AlreadyPaused();
/// @notice Protocol is not paused.
error NotPaused();
}
src/libraries/LotusEventsLib.sol
// SPDX-License-Identifier: MIT
// Adapted in part from Morpho Blue, Copyright (c) 2023-2026 Morpho Association, MIT License.
pragma solidity ^0.8.28;
import {Id, MarketParams} from "../interfaces/ILotus.sol";
/// @title LotusEventsLib
/// @notice Library for Lotus events.
library LotusEventsLib {
/// @notice Emitted when the contract owner is updated.
/// @param newOwner The new owner address.
event OwnerUpdated(address indexed newOwner);
/// @notice Emitted when a two-step ownership transfer is started.
/// @param previousOwner The current owner.
/// @param newOwner The pending owner that must accept.
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/// @notice Emitted when the protocol interest fee for a tranche is updated.
/// @param id The market id.
/// @param trancheIndex The tranche index.
/// @param newFee The new fee value.
event FeeUpdated(Id indexed id, uint256 indexed trancheIndex, uint64 newFee);
/// @notice Emitted when the fee recipient is updated.
/// @param newFeeRecipient The new fee recipient address.
event FeeRecipientUpdated(address indexed newFeeRecipient);
/// @notice Emitted when the global borrow LTV buffer is updated.
/// @param newBorrowLtvBuffer The new relative buffer below each tranche's LLTV, in WAD.
event BorrowLtvBufferUpdated(uint256 newBorrowLtvBuffer);
/// @notice Emitted when a risk engine is enabled.
/// @param riskEngine The risk engine contract address.
event RiskEngineEnabled(address indexed riskEngine);
/// @notice Emitted when a liquidation module is enabled.
/// @param module The liquidation module address.
event LiquidationModuleEnabled(address indexed module);
/// @notice Emitted when a new market is created.
/// @param id The market id.
/// @param marketParams The market parameters.
event MarketCreated(Id indexed id, MarketParams marketParams);
/// @notice Emitted when a market tranche configuration is set at creation time.
/// @param id The market id.
/// @param trancheIndex The configured tranche index.
/// @param collateralToken The tranche collateral token.
/// @param oracle The tranche oracle.
/// @param lltv The tranche LLTV.
event MarketTrancheConfigured(
Id indexed id, uint256 indexed trancheIndex, address indexed collateralToken, address oracle, uint128 lltv
);
/// @notice Emitted when assets are supplied to the protocol.
/// @param id The market id.
/// @param sender The address supplying the assets.
/// @param onBehalf The recipient of the supply shares.
/// @param trancheIndex The tranche index being supplied to.
/// @param assets The amount of assets supplied.
/// @param shares The amount of supply shares issued.
event Supplied(
Id indexed id,
address indexed sender,
address indexed onBehalf,
uint256 trancheIndex,
uint256 assets,
uint256 shares
);
/// @notice Emitted when assets are withdrawn from the protocol.
/// @param id The market id.
/// @param sender The caller initiating the withdrawal.
/// @param onBehalf The account whose supply shares are burned.
/// @param receiver The address receiving the withdrawn assets.
/// @param trancheIndex The tranche index withdrawn from.
/// @param assets The amount of assets withdrawn.
/// @param shares The amount of supply shares burned.
event Withdrawn(
Id indexed id,
address indexed sender,
address indexed onBehalf,
address receiver,
uint256 trancheIndex,
uint256 assets,
uint256 shares
);
/// @notice Emitted when assets are borrowed from the protocol.
/// @param id The market id.
/// @param sender The address initiating the borrow.
/// @param onBehalf The address taking on the debt.
/// @param receiver The address receiving the borrowed assets.
/// @param trancheIndex The tranche index borrowed from.
/// @param assets The amount of assets borrowed.
/// @param shares The amount of borrow shares issued.
event Borrowed(
Id indexed id,
address indexed sender,
address indexed onBehalf,
address receiver,
uint256 trancheIndex,
uint256 assets,
uint256 shares
);
/// @notice Emitted when a borrower repays borrowed assets.
/// @param id The market id.
/// @param sender The caller initiating the repay.
/// @param onBehalf The account whose debt is repaid.
/// @param trancheIndex The tranche index being repaid.
/// @param assets The amount of assets repaid.
/// @param shares The amount of borrow shares burned.
event Repaid(
Id indexed id,
address indexed sender,
address indexed onBehalf,
uint256 trancheIndex,
uint256 assets,
uint256 shares
);
/// @notice Emitted when collateral is supplied by a borrower.
/// @param id The market id.
/// @param sender The address supplying the collateral.
/// @param onBehalf The recipient of the collateral position.
/// @param trancheIndex The tranche index collateral is associated with.
/// @param assets The amount of collateral assets supplied.
event CollateralSupplied(
Id indexed id, address indexed sender, address indexed onBehalf, uint256 trancheIndex, uint256 assets
);
/// @notice Emitted when collateral is withdrawn by a borrower.
/// @param id The market id.
/// @param sender The caller initiating the withdrawal.
/// @param onBehalf The account whose collateral is withdrawn.
/// @param receiver The address receiving the withdrawn collateral.
/// @param trancheIndex The tranche index withdrawn from.
/// @param assets The amount of collateral assets withdrawn.
event CollateralWithdrawn(
Id indexed id,
address indexed sender,
address indexed onBehalf,
address receiver,
uint256 trancheIndex,
uint256 assets
);
/// @notice Emitted when a borrower's position is liquidated.
/// @param id The market id.
/// @param trancheIndex The tranche index being liquidated.
/// @param liquidator The address executing the liquidation.
/// @param borrower The borrower being liquidated.
/// @param repaidAssets The amount of debt repaid.
/// @param repaidShares The amount of borrow shares burned.
/// @param seizedAssets The amount of collateral seized.
/// @param badDebtAssets The assets marked as bad debt.
/// @param badDebtShares The borrow shares marked as bad debt.
event Liquidated(
Id indexed id,
uint256 indexed trancheIndex,
address indexed liquidator,
address borrower,
uint256 repaidAssets,
uint256 repaidShares,
uint256 seizedAssets,
uint256 badDebtAssets,
uint256 badDebtShares
);
/// @notice Emitted when interest is manually accrued for a market.
/// @param id The market id.
event InterestAccrued(Id indexed id);
/// @notice Emitted when an authorization is set.
/// @param caller The address that initiated the authorization change.
/// @param authorizer The address that authorized another address.
/// @param authorized The address that was authorized.
/// @param newIsAuthorized The new authorization status.
event AuthorizationUpdated(
address indexed caller, address indexed authorizer, address indexed authorized, bool newIsAuthorized
);
/// @notice Emitted when a nonce is incremented to prevent signature replay.
/// @param caller The address that initiated the increment.
/// @param authorizer The address whose nonce was incremented.
/// @param usedNonce The nonce value that was used.
event NonceIncremented(address indexed caller, address indexed authorizer, uint256 usedNonce);
/// @notice Emitted when a flash loan is executed.
/// @param caller The address that initiated the flash loan.
/// @param token The address of the token that was flash loaned.
/// @param assets The amount of assets that was flash loaned.
/// @param fee The additional amount of tokens charged to the borrower.
event FlashLoanExecuted(address indexed caller, address indexed token, uint256 assets, uint256 fee);
/// @notice Emitted when a market hook is configured.
/// @param id The market id.
/// @param hook The hook contract address (zero address disables hooks).
/// @param permissions The hook permissions bitmap.
event MarketHookUpdated(Id indexed id, address indexed hook, uint256 permissions);
/// @notice Emitted when a module manager is enabled.
/// @param manager The module manager address.
event ModuleManagerEnabled(address indexed manager);
/// @notice Emitted when a module manager is disabled.
/// @param manager The module manager address.
event ModuleManagerDisabled(address indexed manager);
}
src/libraries/LotusExternalLib.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Adapted in part from Morpho Blue. Modified by Lotus DeFi Labs, Inc. through November 2026.
pragma solidity ^0.8.28;
import {ILotus, Id, MarketParams, Tranche, Authorization, Signature} from "../interfaces/ILotus.sol";
import {LotusErrorsLib} from "./LotusErrorsLib.sol";
import {LotusEventsLib} from "./LotusEventsLib.sol";
import {WAD, MAX_FLASH_LOAN_FEE, AUTHORIZATION_TYPEHASH} from "./ConstantsLib.sol";
import {MarketParamsLib} from "./MarketParamsLib.sol";
/// @title LotusExternalLib
/// @notice External-library home for Lotus pause logic, owner setters and aggregate-accounting event emitters.
/// @dev Keeping this logic in separately deployed bytecode preserves Lotus's EIP-170 headroom.
/// Calls execute via DELEGATECALL, so state updates and logs apply to the Lotus contract. Combining
/// both concerns in one library avoids paying a second cold external-account access when a
/// state-changing market operation performs its pause check and later emits visibility events.
library LotusExternalLib {
/// @notice Aggregated pause state for Lotus. `globalPaused` and `globalUnpausedAt` pack into
/// a single slot; the three mappings each take their own slot.
struct State {
/// @notice Whether the entire protocol is currently paused.
bool globalPaused;
/// @notice Timestamp of the last global unpause, or zero before the first global unpause.
uint64 globalUnpausedAt;
/// @notice Per-market pause status.
mapping(Id id => bool) marketPaused;
/// @notice Timestamp of the last per-market unpause.
mapping(Id id => uint64) marketUnpausedAt;
/// @notice Last unpause timestamp already synchronized into tranche `lastUpdate` values.
mapping(Id id => uint64) marketPauseSyncedAt;
}
/// @notice Applies a global or per-market pause/unpause transition.
/// @dev Validates the market exists when `global` is false. Reverts on no-op transitions.
/// @param state Lotus's pause storage struct.
/// @param marketTranches Lotus's `mapping(Id id => Tranche[]) marketTranches` (used to check that
/// the per-market target exists).
/// @param marketParams Ignored when `global` is true; otherwise the per-market target.
/// @param global Whether the transition applies to the protocol-wide flag (true) or the
/// per-market flag (false).
/// @param paused The desired pause state.
function setPaused(
State storage state,
mapping(Id id => Tranche[]) storage marketTranches,
MarketParams memory marketParams,
bool global,
bool paused
) external {
if (global) {
if (paused == state.globalPaused) {
if (paused) revert LotusErrorsLib.AlreadyPaused();
revert LotusErrorsLib.NotPaused();
}
state.globalPaused = paused;
if (paused) {
emit ILotus.GlobalPaused();
} else {
uint64 nowTs = uint64(block.timestamp);
state.globalUnpausedAt = nowTs;
emit ILotus.GlobalUnpaused(nowTs);
}
return;
}
Id id = MarketParamsLib.id(marketParams);
if (marketTranches[id].length == 0) revert LotusErrorsLib.MarketNotCreated(id);
if (state.globalPaused) revert LotusErrorsLib.ProtocolPaused();
if (paused == state.marketPaused[id]) {
if (paused) revert LotusErrorsLib.AlreadyPaused();
revert LotusErrorsLib.NotPaused();
}
state.marketPaused[id] = paused;
if (paused) {
emit ILotus.MarketPaused(id);
} else {
state.marketUnpausedAt[id] = uint64(block.timestamp);
emit ILotus.MarketUnpaused(id);
}
}
/// @notice Sets the flash loan fee for `token`. Owner check is done by Lotus.
function setFlashLoanFee(mapping(address token => uint64) storage flashLoanFee, address token, uint64 newFee)
external
{
if (token == address(0)) revert LotusErrorsLib.ZeroAddress();
if (newFee == flashLoanFee[token]) revert LotusErrorsLib.FlashLoanFeeAlreadySet(token, newFee);
if (newFee > MAX_FLASH_LOAN_FEE) revert LotusErrorsLib.InvalidFee(newFee);
flashLoanFee[token] = newFee;
emit ILotus.FlashLoanFeeUpdated(token, newFee);
}
/// @notice Body of `Lotus.setAuthorizationWithSig`; `msg.sender` is preserved under DELEGATECALL.
function setAuthorizationWithSig(
mapping(address authorizer => mapping(address authorized => bool)) storage isAuthorized,
mapping(address authorizer => uint256) storage nonce,
bytes32 domainSeparator,
Authorization memory authorization,
Signature calldata signature
) external {
if (block.timestamp > authorization.deadline) revert LotusErrorsLib.SignatureExpired();
if (authorization.nonce != nonce[authorization.authorizer]++) revert LotusErrorsLib.InvalidNonce();
bytes32 hashStruct = keccak256(abi.encode(AUTHORIZATION_TYPEHASH, authorization));
bytes32 digest = keccak256(bytes.concat("\x19\x01", domainSeparator, hashStruct));
address signatory = ecrecover(digest, signature.v, signature.r, signature.s);
if (signatory == address(0) || authorization.authorizer != signatory) revert LotusErrorsLib.InvalidSignature();
emit LotusEventsLib.NonceIncremented(msg.sender, authorization.authorizer, authorization.nonce);
isAuthorized[authorization.authorizer][authorization.authorized] = authorization.isAuthorized;
emit LotusEventsLib.AuthorizationUpdated(
msg.sender, authorization.authorizer, authorization.authorized, authorization.isAuthorized
);
}
/// @notice Enables `lltv` for market creation. Owner check is done by Lotus.
function enableLltv(mapping(uint256 lltv => bool) storage isLltvEnabled, uint128 lltv) external {
if (isLltvEnabled[lltv]) revert LotusErrorsLib.LltvAlreadyEnabled(lltv);
if (lltv == 0 || lltv > WAD) revert LotusErrorsLib.InvalidLltv(lltv);
isLltvEnabled[lltv] = true;
emit ILotus.LltvEnabled(lltv);
}
/// @notice Full pause gate: reverts if the protocol or this market is paused, then lazily
/// fast-forwards each tranche's `lastUpdate` if a pause window has closed since the last sync.
/// @dev Called from every per-market state-changing entry point on Lotus. The lib lives in
/// its own deployed contract and is invoked via DELEGATECALL.
/// @dev Each tranche's `lastUpdate` is advanced to the unpause timestamp, not to `block.timestamp`.
/// This skips interest over the pause window only, so the active period between the unpause and
/// this first post-unpause interaction is still charged on the next accrual. (Interest owed
/// between the last pre-pause interaction and the pause itself is not captured; settle it by
/// accruing before pausing.) The guard leaves `lastUpdate` untouched if it is already at or past
/// `unpausedAt`, so it can never move backwards.
/// @param state Lotus's pause storage struct.
/// @param tranches The market tranches to synchronize after an unpause window.
/// @param id The market whose pause state is enforced and synchronized.
function enforceNotPaused(State storage state, Tranche[] storage tranches, Id id) external {
if (state.globalPaused) revert LotusErrorsLib.ProtocolPaused();
if (state.marketPaused[id]) revert LotusErrorsLib.MarketIsPaused(id);
uint64 unpausedAt = state.globalUnpausedAt;
uint64 mUnpausedAt = state.marketUnpausedAt[id];
if (mUnpausedAt > unpausedAt) unpausedAt = mUnpausedAt;
if (unpausedAt == 0 || state.marketPauseSyncedAt[id] >= unpausedAt) return;
uint256 numTranches = tranches.length;
unchecked {
for (uint256 i = 0; i < numTranches; ++i) {
if (tranches[i].lastUpdate < unpausedAt) tranches[i].lastUpdate = unpausedAt;
}
}
state.marketPauseSyncedAt[id] = unpausedAt;
}
/// @notice Returns the effective pause state for a market, as the accrual gate sees it.
/// @dev Lets off-chain valuation mirror `enforceNotPaused`'s effect on interest: when `paused`
/// is true no interest accrues; when `unpausedAt > syncedAt` the next accrual will restart each
/// tranche from `unpausedAt` rather than from its stale pre-pause `lastUpdate`.
/// @param state Lotus's pause storage struct.
/// @param id The market to query.
/// @return paused Whether the protocol or this market is currently paused.
/// @return unpausedAt The most recent unpause timestamp relevant to this market (global or per-market).
/// @return syncedAt The unpause timestamp already synchronized into this market's tranche `lastUpdate` values.
function pauseState(State storage state, Id id)
external
view
returns (bool paused, uint64 unpausedAt, uint64 syncedAt)
{
paused = state.globalPaused || state.marketPaused[id];
unpausedAt = state.globalUnpausedAt;
uint64 mUnpausedAt = state.marketUnpausedAt[id];
if (mUnpausedAt > unpausedAt) unpausedAt = mUnpausedAt;
syncedAt = state.marketPauseSyncedAt[id];
}
/// @notice Arms the repay cooldown on tranches junior to `trancheIndex`, whose borrows can move the loss split.
/// @dev Window = minBorrowDuration * badDebt / (fullArmRatio * cascade supply), capped at minBorrowDuration.
/// Each event adds to the remaining cooldown, capped at minBorrowDuration from now; excess is discarded.
/// @param borrowCooldownUntil Lotus's per-market, per-tranche cooldown expiries.
/// @param marketTranches Lotus's tranche storage, read before the bad debt is distributed.
/// @param id The market id.
/// @param trancheIndex The tranche where the bad debt originated.
/// @param badDebtAssets The realized bad debt.
/// @param minBorrowDuration Full cooldown window, Lotus's `MIN_BORROW_DURATION`.
/// @param fullArmRatio Bad debt as a WAD fraction of cascade supply that arms the full window.
function armBorrowCooldown(
mapping(Id => mapping(uint256 => uint64)) storage borrowCooldownUntil,
mapping(Id => Tranche[]) storage marketTranches,
Id id,
uint256 trancheIndex,
uint256 badDebtAssets,
uint256 minBorrowDuration,
uint256 fullArmRatio
) external {
Tranche[] storage tranches = marketTranches[id];
mapping(uint256 => uint64) storage cooldownUntil = borrowCooldownUntil[id];
uint256 numTranches = tranches.length;
uint256 cascadeSupply;
for (uint256 i = trancheIndex; i < numTranches; ++i) {
cascadeSupply += tranches[i].supplyAssets;
}
uint256 fullArmBadDebt = cascadeSupply * fullArmRatio / WAD;
uint256 window =
badDebtAssets >= fullArmBadDebt ? minBorrowDuration : minBorrowDuration * badDebtAssets / fullArmBadDebt;
if (window == 0) return;
uint64 until = uint64(block.timestamp + window);
uint256 cap = block.timestamp + minBorrowDuration;
for (uint256 i = trancheIndex + 1; i < numTranches; ++i) {
uint256 base = cooldownUntil[i] > block.timestamp ? cooldownUntil[i] : block.timestamp;
uint256 extended = base + window;
if (extended > cap) extended = cap;
cooldownUntil[i] = uint64(extended);
if (extended > until) until = uint64(extended);
}
emit ILotus.BorrowCooldownArmed(id, trancheIndex, until);
}
/// @notice Emits the current aggregate accounting state for a tranche.
function emitTrancheState(Id id, uint256 trancheIndex, Tranche storage tranche) external {
_emitTrancheState(id, trancheIndex, tranche);
}
/// @notice Emits non-zero interest deltas and the resulting aggregate tranche state.
function emitAccrual(
Id id,
uint256 trancheIndex,
Tranche storage tranche,
uint256 borrowInterest,
uint256 supplyInterest,
uint256 feeShares
) external {
if (borrowInterest != 0) {
emit ILotus.BorrowInterestAccrued(id, trancheIndex, borrowInterest);
}
if (supplyInterest != 0) {
emit ILotus.SupplyInterestDistributed(id, trancheIndex, supplyInterest, feeShares);
}
_emitTrancheState(id, trancheIndex, tranche);
}
/// @notice Emits a bad-debt allocation and, except for the origin tranche, the absorbing
/// tranche's resulting aggregate state.
/// @dev The origin tranche's snapshot is intentionally suppressed here because the liquidation
/// path emits its single final `TrancheStateUpdated` after `Liquidated`. That later snapshot
/// includes both the borrow-side bad-debt write and any supply loss absorbed by the origin.
/// Non-origin absorbing tranches have no later flow event, so their snapshots are emitted here.
function emitBadDebtAllocation(
Id id,
uint256 originTrancheIndex,
uint256 absorbingTrancheIndex,
uint256 assetsReduced,
Tranche storage absorbingTranche
) external {
emit ILotus.BadDebtAllocated(id, originTrancheIndex, absorbingTrancheIndex, assetsReduced);
if (absorbingTrancheIndex != originTrancheIndex) {
_emitTrancheState(id, absorbingTrancheIndex, absorbingTranche);
}
}
function _emitTrancheState(Id id, uint256 trancheIndex, Tranche storage tranche) private {
emit ILotus.TrancheStateUpdated(
id, trancheIndex, tranche.supplyAssets, tranche.supplyShares, tranche.borrowAssets, tranche.borrowShares
);
}
}
src/libraries/MarketParamsLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {Id, MarketParams, TrancheConfig} from "../interfaces/ILotus.sol";
/// @title MarketParamsLib
/// @notice Helpers for deriving and transforming Lotus market parameter structs.
library MarketParamsLib {
/// @dev Computes the unique id for a given `MarketParams` struct.
function id(MarketParams memory marketParams) internal pure returns (Id marketParamsId) {
marketParamsId = Id.wrap(
keccak256(
abi.encode(
marketParams.loanToken,
marketParams.riskEngine,
marketParams.liquidationModule,
marketParams.trancheConfigsHash
)
)
);
}
/// @dev Computes `trancheConfigsHash` from a tranche configuration array.
function computeTrancheConfigsHash(TrancheConfig[] memory tranches) internal pure returns (bytes32) {
// forge-lint: disable-next-item(asm-keccak256)
return keccak256(abi.encode(tranches));
}
}
src/libraries/SharesMathLib.sol
// SPDX-License-Identifier: MIT
// Adapted in part from Morpho Blue, Copyright (c) 2023-2026 Morpho Association, MIT License.
pragma solidity ^0.8.28;
import {FixedPointMathLib} from "solady/src/utils/FixedPointMathLib.sol";
/// @title SharesMathLib
/// @notice Shares management library.
/// @dev This implementation mitigates share price manipulations, using OpenZeppelin's method of virtual shares:
/// https://docs.openzeppelin.com/contracts/4.x/erc4626#inflation-attack.
library SharesMathLib {
using FixedPointMathLib for uint256;
/// @dev The number of virtual shares has been chosen low enough to prevent overflows, and high enough to ensure
/// high precision computations.
/// @dev Virtual shares can never be redeemed for the assets they are entitled to, but it is assumed the share price
/// stays low enough not to inflate these assets to a significant value.
/// @dev Warning: The assets to which virtual borrow shares are entitled behave like unrealizable bad debt.
uint256 internal constant VIRTUAL_SHARES = 1e6;
/// @dev A number of virtual assets of 1 enforces a conversion rate between shares and assets when a market is
/// empty.
uint256 internal constant VIRTUAL_ASSETS = 1;
/// @dev Calculates the value of `assets` quoted in shares, rounding down.
function toSharesDown(uint256 assets, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
return assets.mulDiv(totalShares + VIRTUAL_SHARES, totalAssets + VIRTUAL_ASSETS);
}
/// @dev Calculates the value of `shares` quoted in assets, rounding down.
function toAssetsDown(uint256 shares, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
return shares.mulDiv(totalAssets + VIRTUAL_ASSETS, totalShares + VIRTUAL_SHARES);
}
/// @dev Calculates the value of `assets` quoted in shares, rounding up.
function toSharesUp(uint256 assets, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
return assets.mulDivUp(totalShares + VIRTUAL_SHARES, totalAssets + VIRTUAL_ASSETS);
}
/// @dev Calculates the value of `shares` quoted in assets, rounding up.
function toAssetsUp(uint256 shares, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
return shares.mulDivUp(totalAssets + VIRTUAL_ASSETS, totalShares + VIRTUAL_SHARES);
}
}
src/libraries/UtilsLib.sol
// SPDX-License-Identifier: MIT
// Adapted in part from Morpho Blue, Copyright (c) 2023-2026 Morpho Association, MIT License.
pragma solidity ^0.8.28;
/// @title UtilsLib
/// @notice Minimal library with utility functions not available in Solady.
/// @dev Only contains functions that are unique to our protocol needs.
library UtilsLib {
/// @dev Returns true if there is exactly one zero among `x` and `y`.
function exactlyOneZero(uint256 x, uint256 y) internal pure returns (bool z) {
assembly {
z := xor(iszero(x), iszero(y))
}
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"solady/=lib/solady/",
"bundler3/=lib/bundler3/",
"ds-test/=lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"forge-std/=lib/forge-std/src/",
"halmos-cheatcodes/=lib/bundler3/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"morpho-blue/=lib/bundler3/lib/morpho-blue/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"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.