Verified contractExactGPL-2.0-or-later
HealthDiscountLiquidationModuleFactory
Address0xf6104cc419c3626dceb95dddec6cfc5657f1eb57
- Balance
0 ETH
- Transactions
4
- Compiler
solc 0.8.28
- Same code
1 more contract
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,733
- Creation transaction
- 0x952100fcaa…fe9f96abd9
34 files
- src/liquidations/factories/HealthDiscountLiquidationModuleFactory.solmain2.02 KB
- lib/openzeppelin-contracts-upgradeable/contracts/access/Ownable2StepUpgradeable.sol3.01 KB
- lib/openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol4.03 KB
- lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol8.91 KB
- lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol6.59 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol1.19 KB
- lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol880 B
- lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Proxy.sol1.72 KB
- lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol6.72 KB
- lib/openzeppelin-contracts/contracts/proxy/Proxy.sol2.67 KB
- lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol472 B
- lib/openzeppelin-contracts/contracts/utils/Address.sol6.26 KB
- lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol3.93 KB
- lib/solady/src/utils/FixedPointMathLib.sol55.69 KB
- lib/solady/src/utils/SafeTransferLib.sol32.86 KB
- src/access/TwoStepOperator.sol3.96 KB
- src/access/TwoStepOwnable.sol3.72 KB
- src/factories/ModuleFactory.sol1.6 KB
- src/factories/interfaces/IModuleFactory.sol1.41 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/BaseUpgradeableModule.sol3 KB
- src/libraries/ConstantsLib.sol3.02 KB
- src/libraries/LotusErrorsLib.sol9.01 KB
- src/libraries/SharesMathLib.sol2.42 KB
- src/libraries/UtilsLib.sol576 B
- src/liquidations/HealthDiscountLiquidationModule.sol8.49 KB
- src/liquidations/interfaces/IHealthDiscountLiquidationModule.sol2.96 KB
- src/liquidations/interfaces/IHealthDiscountLiquidationModuleFactory.sol1.33 KB
- src/liquidations/libraries/BaseLiquidationModule.sol3.46 KB
- src/liquidations/libraries/LiquidationErrorsLib.sol749 B
src/liquidations/factories/HealthDiscountLiquidationModuleFactory.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.28;
import {ERC1967Proxy} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol";
import {ILotus} from "../../interfaces/ILotus.sol";
import {ModuleFactory} from "../../factories/ModuleFactory.sol";
import {LotusErrorsLib} from "../../libraries/LotusErrorsLib.sol";
import {HealthDiscountLiquidationModule} from "../HealthDiscountLiquidationModule.sol";
import {IHealthDiscountLiquidationModuleFactory} from "../interfaces/IHealthDiscountLiquidationModuleFactory.sol";
/// @title HealthDiscountLiquidationModuleFactory
/// @notice Factory for deploying and enabling health-discount liquidation modules.
/// @dev Must be registered as a module manager on Lotus via `enableModuleManager`.
contract HealthDiscountLiquidationModuleFactory is ModuleFactory, IHealthDiscountLiquidationModuleFactory {
/// @inheritdoc IHealthDiscountLiquidationModuleFactory
ILotus public immutable LOTUS;
/// @inheritdoc IHealthDiscountLiquidationModuleFactory
address public immutable IMPLEMENTATION;
/// @param _lotus The Lotus protocol address.
/// @param _implementation The pre-deployed module implementation address.
/// @param _owner The factory owner.
constructor(ILotus _lotus, address _implementation, address _owner) ModuleFactory(_owner) {
if (address(_lotus) == address(0) || _implementation == address(0)) revert LotusErrorsLib.ZeroAddress();
LOTUS = _lotus;
IMPLEMENTATION = _implementation;
}
/// @inheritdoc IHealthDiscountLiquidationModuleFactory
function deploy(address owner, address operator) external onlyAllowedCaller returns (address module) {
ERC1967Proxy proxy = new ERC1967Proxy(
IMPLEMENTATION, abi.encodeCall(HealthDiscountLiquidationModule.initializeModule, (owner, operator))
);
module = address(proxy);
LOTUS.enableLiquidationModule(module);
emit HealthDiscountLiquidationModuleDeployed(module, operator);
}
}
lib/openzeppelin-contracts-upgradeable/contracts/access/Ownable2StepUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {OwnableUpgradeable} from "./OwnableUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2StepUpgradeable is Initializable, OwnableUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Ownable2Step
struct Ownable2StepStorage {
address _pendingOwner;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable2Step")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant Ownable2StepStorageLocation = 0x237e158222e3e6968b72b9db0d8043aacf074ad9f650f0d1606b4d82ee432c00;
function _getOwnable2StepStorage() private pure returns (Ownable2StepStorage storage $) {
assembly {
$.slot := Ownable2StepStorageLocation
}
}
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
function __Ownable2Step_init() internal onlyInitializing {
}
function __Ownable2Step_init_unchained() internal onlyInitializing {
}
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
Ownable2StepStorage storage $ = _getOwnable2StepStorage();
return $._pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
Ownable2StepStorage storage $ = _getOwnable2StepStorage();
$._pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
Ownable2StepStorage storage $ = _getOwnable2StepStorage();
delete $._pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
lib/openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Ownable
struct OwnableStorage {
address _owner;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;
function _getOwnableStorage() private pure returns (OwnableStorage storage $) {
assembly {
$.slot := OwnableStorageLocation
}
}
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
function __Ownable_init(address initialOwner) internal onlyInitializing {
__Ownable_init_unchained(initialOwner);
}
function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
OwnableStorage storage $ = _getOwnableStorage();
return $._owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
OwnableStorage storage $ = _getOwnableStorage();
address oldOwner = $._owner;
$._owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.20;
import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable __self = address(this);
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
* and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev The call is from an unauthorized context.
*/
error UUPSUnauthorizedCallContext();
/**
* @dev The storage `slot` is unsupported as a UUID.
*/
error UUPSUnsupportedProxiableUUID(bytes32 slot);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
_checkProxy();
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
_checkNotDelegated();
_;
}
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/**
* @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual notDelegated returns (bytes32) {
return ERC1967Utils.IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data);
}
/**
* @dev Reverts if the execution is not performed via delegatecall or the execution
* context is not of a proxy with an ERC1967-compliant implementation pointing to self.
* See {_onlyProxy}.
*/
function _checkProxy() internal view virtual {
if (
address(this) == __self || // Must be called through delegatecall
ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
) {
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Reverts if the execution is performed via delegatecall.
* See {notDelegated}.
*/
function _checkNotDelegated() internal view virtual {
if (address(this) != __self) {
// Must not be called through delegatecall
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
*
* As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
* is expected to be the implementation slot in ERC1967.
*
* Emits an {IERC1967-Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
revert UUPSUnsupportedProxiableUUID(slot);
}
ERC1967Utils.upgradeToAndCall(newImplementation, data);
} catch {
// The implementation is not UUPS
revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.20;
/**
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Proxy.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Proxy.sol)
pragma solidity ^0.8.20;
import {Proxy} from "../Proxy.sol";
import {ERC1967Utils} from "./ERC1967Utils.sol";
/**
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*/
contract ERC1967Proxy is Proxy {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `implementation`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `implementation`. This will typically be an
* encoded function call, and allows initializing the storage of the proxy like a Solidity constructor.
*
* Requirements:
*
* - If `data` is empty, `msg.value` must be zero.
*/
constructor(address implementation, bytes memory _data) payable {
ERC1967Utils.upgradeToAndCall(implementation, _data);
}
/**
* @dev Returns the current implementation address.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
*/
function _implementation() internal view virtual override returns (address) {
return ERC1967Utils.getImplementation();
}
}
lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.20;
import {IBeacon} from "../beacon/IBeacon.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*/
library ERC1967Utils {
// We re-declare ERC-1967 events here because they can't be used directly from IERC1967.
// This will be fixed in Solidity 0.8.21. At that point we should remove these events.
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @dev Returns the current implementation address.
*/
function getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-AdminChanged} event.
*/
function changeAdmin(address newAdmin) internal {
emit AdminChanged(getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev Change the beacon and trigger a setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-BeaconUpgraded} event.
*
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
* efficiency.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}
lib/openzeppelin-contracts/contracts/proxy/Proxy.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/Proxy.sol)
pragma solidity ^0.8.20;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev This is a virtual function that should be overridden so it returns the address to which the fallback
* function and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback() external payable virtual {
_fallback();
}
}
lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.20;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {UpgradeableBeacon} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
lib/openzeppelin-contracts/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}
lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```solidity
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
/**
* @dev Returns an `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
}
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/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/TwoStepOperator.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// @title ITwoStepOperator
/// @notice Two-step operator interface. Host interfaces extend this so the mixin implements it once.
interface ITwoStepOperator {
/// @notice Emitted when a two-step operator transfer is started.
event OperatorTransferStarted(address indexed previousOperator, address indexed newOperator);
/// @notice Emitted when the operator changes (accept or renounce).
event OperatorUpdated(address indexed newOperator);
/// @notice Caller is not the operator.
error NotOperator();
/// @notice Caller is not the pending operator.
error NotPendingOperator();
/// @notice The current operator.
function operator() external view returns (address);
/// @notice The pending operator of a two-step transfer.
function pendingOperator() external view returns (address);
/// @notice Starts a two-step operator transfer. The new operator must call `acceptOperator`.
function transferOperator(address newOperator) external;
/// @notice Completes a two-step operator transfer. Callable only by the pending operator.
function acceptOperator() external;
/// @notice Renounces the operator role, setting the operator to the zero address.
function renounceOperator() external;
}
/// @title TwoStepOperator
/// @notice Two-step operator transfer with a separate renounce. Identical in logic to TwoStepOwnable,
/// differing only in role name, functions, events, and errors.
/// @dev ERC-7201 namespaced storage so this composes with upgradeable and non-upgradeable hosts, and
/// alongside a TwoStepOwnable role, with no storage-layout clashes. Seed the initial operator from
/// the host constructor or initializer via `_initializeOperator`.
abstract contract TwoStepOperator is ITwoStepOperator {
/// @custom:storage-location erc7201:lotus.storage.TwoStepOperator
struct OperatorStorage {
address operator;
address pendingOperator;
}
// keccak256(abi.encode(uint256(keccak256("lotus.storage.TwoStepOperator")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant _STORAGE = 0x55bdcf4f670652d32e43f833e0dff175c969fd90c3ac269d94fdc53ad5636200;
function _operatorStorage() private pure returns (OperatorStorage storage $) {
assembly {
$.slot := _STORAGE
}
}
modifier onlyOperator() {
if (msg.sender != _operatorStorage().operator) revert NotOperator();
_;
}
/// @inheritdoc ITwoStepOperator
function operator() public view virtual override returns (address) {
return _operatorStorage().operator;
}
/// @inheritdoc ITwoStepOperator
function pendingOperator() public view virtual override returns (address) {
return _operatorStorage().pendingOperator;
}
/// @inheritdoc ITwoStepOperator
function transferOperator(address newOperator) public virtual override onlyOperator {
OperatorStorage storage $ = _operatorStorage();
$.pendingOperator = newOperator;
emit OperatorTransferStarted($.operator, newOperator);
}
/// @inheritdoc ITwoStepOperator
function acceptOperator() public virtual override {
if (msg.sender != _operatorStorage().pendingOperator) revert NotPendingOperator();
_setOperator(msg.sender);
}
/// @inheritdoc ITwoStepOperator
function renounceOperator() public virtual override onlyOperator {
_setOperator(address(0));
}
/// @dev Seeds the operator. Call once from the host constructor or initializer.
function _initializeOperator(address initialOperator) internal {
_setOperator(initialOperator);
}
function _setOperator(address newOperator) internal {
OperatorStorage storage $ = _operatorStorage();
$.operator = newOperator;
delete $.pendingOperator;
emit OperatorUpdated(newOperator);
}
}
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/factories/ModuleFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {TwoStepOwnable} from "../access/TwoStepOwnable.sol";
import {IModuleFactory} from "./interfaces/IModuleFactory.sol";
/// @title ModuleFactory
/// @notice Ownable deployment gate shared by Lotus module factories.
/// @dev The factory owner controls who may call `deploy()`. The owner may always deploy, and additional callers may be
/// whitelisted. Ownership can be renounced to make the current configuration permanent. Revoking a factory's
/// Lotus module-manager role later only blocks future `enableRiskEngine` / `enableLiquidationModule` calls on
/// Lotus; it does not disable the factory contract itself or affect modules it already deployed.
abstract contract ModuleFactory is TwoStepOwnable, IModuleFactory {
/* STORAGE */
/// @inheritdoc IModuleFactory
mapping(address caller => bool) public isWhitelistedCaller;
/* CONSTRUCTOR */
/// @param _owner The owner that controls caller whitelisting.
constructor(address _owner) {
if (_owner == address(0)) revert InvalidOwner(_owner);
_initializeOwner(_owner);
}
/* MODIFIERS */
modifier onlyAllowedCaller() {
if (msg.sender != owner() && !isWhitelistedCaller[msg.sender]) {
revert NotAllowedCaller();
}
_;
}
/* OWNER FUNCTIONS */
/// @inheritdoc IModuleFactory
function setWhitelistedCaller(address caller, bool allowed) external onlyOwner {
isWhitelistedCaller[caller] = allowed;
emit CallerWhitelisted(caller, allowed);
}
}
src/factories/interfaces/IModuleFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {ITwoStepOwnable} from "../../access/TwoStepOwnable.sol";
/// @title IModuleFactory
/// @notice Shared interface for Lotus module factories with deploy-caller whitelisting.
/// @dev The owner may always deploy, and additional callers may be whitelisted. Ownership can be renounced to make
/// the current configuration permanent.
interface IModuleFactory is ITwoStepOwnable {
/// @notice Caller is not allowed to deploy a module.
error NotAllowedCaller();
/// @notice Initial factory owner is the zero address.
/// @param owner The invalid owner address.
error InvalidOwner(address owner);
/// @notice Emitted when a caller's whitelist status changes.
/// @param caller The caller whose deploy permission changed.
/// @param allowed Whether `caller` is allowed to deploy.
event CallerWhitelisted(address indexed caller, bool allowed);
/// @notice Returns whether `caller` may deploy.
/// @param caller The address to query.
/// @return Whether `caller` is whitelisted.
function isWhitelistedCaller(address caller) external view returns (bool);
/// @notice Adds or removes a caller from the deploy whitelist.
/// @param caller The address to update.
/// @param allowed Whether the caller is allowed.
function setWhitelistedCaller(address caller, bool allowed) external;
}
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/BaseUpgradeableModule.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {Ownable2StepUpgradeable} from "@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {ILotus} from "../interfaces/ILotus.sol";
import {LotusErrorsLib} from "./LotusErrorsLib.sol";
/// @title BaseUpgradeableModule
/// @notice Upgradeable Lotus module base with Lotus binding and UUPS authorization.
/// @dev Provides Lotus binding, UUPS upgrade safety, renounce-disabled ownership, and Lotus-only gating.
abstract contract BaseUpgradeableModule is Initializable, Ownable2StepUpgradeable, UUPSUpgradeable {
/* ERRORS */
/// @notice Ownership renouncement is attempted.
error RenounceDisabled();
/// @notice Proposed implementation is not bound to the same Lotus core contract.
/// @param implementation The invalid implementation address.
error InvalidLotusImplementation(address implementation);
/* STORAGE */
/// @notice The Lotus core contract bound to this module.
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
ILotus public immutable LOTUS;
/* CONSTRUCTOR */
/// @param _lotus The Lotus core contract.
/// @custom:oz-upgrades-unsafe-allow constructor
constructor(ILotus _lotus) {
if (address(_lotus) == address(0)) revert LotusErrorsLib.ZeroAddress();
LOTUS = _lotus;
}
/* INITIALIZER */
/// @dev Initializes shared ownership and UUPS state for Lotus modules.
/// @param _owner The initial module owner.
function __BaseUpgradeableModule_init(address _owner) internal onlyInitializing {
__Ownable_init(_owner);
__UUPSUpgradeable_init();
}
/* UPGRADEABLE */
function _authorizeUpgrade(address newImplementation) internal view override onlyOwner {
(bool success, bytes memory returndata) = newImplementation.staticcall(abi.encodeWithSignature("LOTUS()"));
if (!success || returndata.length < 32 || abi.decode(returndata, (address)) != address(LOTUS)) {
revert InvalidLotusImplementation(newImplementation);
}
}
/// @notice Always reverts; module ownership cannot be renounced.
/// @dev Renouncing ownership is disabled to avoid permanently bricking upgrade capability.
function renounceOwnership() public view override onlyOwner {
revert RenounceDisabled();
}
/* MODIFIERS */
modifier onlyLotus() {
_onlyLotus();
_;
}
/* INTERNAL FUNCTIONS */
/// @dev Reverts when `msg.sender` is not the Lotus core contract.
function _onlyLotus() internal view {
if (msg.sender != address(LOTUS)) revert LotusErrorsLib.NotLotus();
}
/* STORAGE GAP */
/// @dev Reserved storage for future base-contract upgrades.
uint256[50] private __gap;
}
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/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/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))
}
}
}
src/liquidations/HealthDiscountLiquidationModule.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.28;
import {FixedPointMathLib} from "solady/src/utils/FixedPointMathLib.sol";
import {ILiquidationModule, LiquidationQuoteContext} from "../interfaces/ILiquidationModule.sol";
import {IOracle} from "../interfaces/IOracle.sol";
import {IHealthDiscountLiquidationModule} from "./interfaces/IHealthDiscountLiquidationModule.sol";
import {TwoStepOperator} from "../access/TwoStepOperator.sol";
import {BaseLiquidationModule, BaseLiquidationParams} from "./libraries/BaseLiquidationModule.sol";
import {Id, ILotus, Position, Tranche, TrancheConfig} from "../interfaces/ILotus.sol";
import {SharesMathLib} from "../libraries/SharesMathLib.sol";
import {LiquidationErrorsLib} from "./libraries/LiquidationErrorsLib.sol";
import {LotusErrorsLib} from "../libraries/LotusErrorsLib.sol";
import {MAX_HEALTH_LIQUIDATION_DISCOUNT, ORACLE_PRICE_SCALE, WAD} from "../libraries/ConstantsLib.sol";
/// @title HealthDiscountLiquidationModule
/// @notice Liquidation module that quotes collateral discounts from account health.
/// @dev Stores per-tranche max discount caps and settles liquidations immediately.
contract HealthDiscountLiquidationModule is BaseLiquidationModule, TwoStepOperator, IHealthDiscountLiquidationModule {
using SharesMathLib for uint256;
using FixedPointMathLib for uint256;
/* STORAGE */
/// @inheritdoc IHealthDiscountLiquidationModule
mapping(Id id => mapping(uint256 trancheIndex => uint256)) public override maxLiquidationDiscount;
/* CONSTRUCTOR */
/// @param _lotus The Lotus core contract.
/// @custom:oz-upgrades-unsafe-allow constructor
constructor(ILotus _lotus) BaseLiquidationModule(_lotus) {
_disableInitializers();
}
/* INITIALIZER */
/// @inheritdoc IHealthDiscountLiquidationModule
function initializeModule(address _owner, address _operator) external initializer {
__BaseLiquidationModule_init(_owner);
if (_operator == address(0)) revert LiquidationErrorsLib.NotLiquidationOperator();
_initializeOperator(_operator);
}
/* LOTUS INTERFACE */
/// @inheritdoc ILiquidationModule
function initializeMarket(Id id, bytes calldata liquidationParams)
external
override(BaseLiquidationModule, ILiquidationModule)
onlyLotus
{
uint256[] memory maxDiscounts = _getDecodedLiquidationParams(liquidationParams);
_setLiquidationParams(id, maxDiscounts);
}
/// @inheritdoc ILiquidationModule
function calculateLiquidation(LiquidationQuoteContext calldata context, bytes calldata lmData)
external
view
override(BaseLiquidationModule, ILiquidationModule)
returns (uint256, uint256, uint256)
{
BaseLiquidationParams memory params = abi.decode(lmData, (BaseLiquidationParams));
_validateLiquidationInputs(params.seizedAssets, params.repaidShares);
return _calculateLiquidation(context, params.seizedAssets, params.repaidShares);
}
/// @dev Computes liquidation outputs from exactly one input mode:
/// @dev `seizedAssets` mode or `repaidShares` mode.
/// @dev Rounding intentionally favors protocol solvency (`mulDivUp`, `toSharesUp`).
function _calculateLiquidation(LiquidationQuoteContext calldata context, uint256 seizedAssets, uint256 repaidShares)
internal
view
override
returns (uint256 finalSeizedAssets, uint256 finalRepaidShares, uint256 finalRepaidAssets)
{
uint256
discountFactor =
_getDiscountFactor(
context.id,
context.trancheIndex,
context.tranche,
context.position,
context.collateralPrice,
context.lltv
);
if (seizedAssets > 0) {
uint256 seizedAssetsQuoted = seizedAssets.mulDivUp(context.collateralPrice, ORACLE_PRICE_SCALE);
finalSeizedAssets = seizedAssets;
finalRepaidAssets = seizedAssetsQuoted.mulDivUp(discountFactor, WAD);
finalRepaidShares = finalRepaidAssets.toSharesUp(context.tranche.borrowAssets, context.tranche.borrowShares);
} else {
finalRepaidShares = repaidShares;
finalRepaidAssets = repaidShares.toAssetsUp(context.tranche.borrowAssets, context.tranche.borrowShares);
finalSeizedAssets =
finalRepaidAssets.mulDiv(WAD, discountFactor).mulDiv(ORACLE_PRICE_SCALE, context.collateralPrice);
}
}
/* OPERATOR FUNCTIONS */
/// @inheritdoc IHealthDiscountLiquidationModule
function setLiquidationParams(Id id, uint256[] memory maxDiscounts) external onlyOperator {
_setLiquidationParams(id, maxDiscounts);
}
/* VIEW FUNCTIONS */
/// @inheritdoc IHealthDiscountLiquidationModule
function getDiscountFactor(Id id, uint256 trancheIndex, address borrower)
external
view
returns (uint256 discountFactor)
{
Tranche memory tranche = LOTUS.getMarketTranche(id, trancheIndex);
Position memory position = LOTUS.getPosition(id, borrower, trancheIndex);
TrancheConfig memory config = LOTUS.getTrancheConfig(id, trancheIndex);
uint256 collateralPrice = IOracle(config.oracle).price();
if (collateralPrice == 0) revert LotusErrorsLib.InvalidCollateralPrice();
discountFactor = _getDiscountFactor(id, trancheIndex, tranche, position, collateralPrice, config.lltv);
}
/// @inheritdoc IHealthDiscountLiquidationModule
function getEncodedLiquidationParams(uint256[] memory maxDiscounts) external pure returns (bytes memory) {
return abi.encode(maxDiscounts);
}
/// @inheritdoc IHealthDiscountLiquidationModule
function getDecodedLiquidationParams(bytes memory liquidationParams)
external
pure
returns (uint256[] memory maxDiscounts)
{
return _getDecodedLiquidationParams(liquidationParams);
}
/* INTERNAL FUNCTIONS */
/// @dev Internal decoder for liquidation config.
function _getDecodedLiquidationParams(bytes memory liquidationParams)
internal
pure
returns (uint256[] memory maxDiscounts)
{
return abi.decode(liquidationParams, (uint256[]));
}
/// @dev Computes discount factor from position health and max discount cap.
function _getDiscountFactor(
Id id,
uint256 trancheIndex,
Tranche memory tranche,
Position memory position,
uint256 collateralPrice,
uint256 lltv
) internal view returns (uint256 discountFactor) {
uint256 borrowed = uint256(position.borrowShares).toAssetsUp(tranche.borrowAssets, tranche.borrowShares);
if (borrowed == 0) return WAD;
uint256 maxBorrow = uint256(position.collateral).mulDiv(collateralPrice, ORACLE_PRICE_SCALE).mulWad(lltv);
uint256 healthScore = maxBorrow >= borrowed ? WAD : maxBorrow.mulDiv(WAD, borrowed);
uint256 minDiscountFactor = WAD - maxLiquidationDiscount[id][trancheIndex];
return healthScore > minDiscountFactor ? healthScore : minDiscountFactor;
}
/// @dev Validates and stores per-tranche max liquidation discounts.
function _setLiquidationParams(Id id, uint256[] memory maxDiscounts) internal {
uint256 numTranches = LOTUS.getNumMarketTranches(id);
if (maxDiscounts.length != numTranches) revert LiquidationErrorsLib.LiquidationParamsLengthMismatch();
for (uint256 i = 0; i < numTranches;) {
uint256 discount = maxDiscounts[i];
if (discount > MAX_HEALTH_LIQUIDATION_DISCOUNT) {
revert LiquidationErrorsLib.InvalidMaxLiquidationDiscount();
}
// The discount must not exceed 1e18 - lltv. Above that bound a liquidation at the health threshold
// seizes collateral worth strictly more than the debt it repays, letting a borrower drain supply via
// profitable self-liquidation and socialize the residual bad debt onto suppliers.
uint256 lltv = LOTUS.getTrancheConfig(id, i).lltv;
if (discount > WAD - lltv) {
revert LiquidationErrorsLib.InvalidMaxLiquidationDiscount();
}
maxLiquidationDiscount[id][i] = discount;
emit MaxLiquidationDiscountUpdated(id, i, discount);
unchecked {
++i;
}
}
}
}
src/liquidations/interfaces/IHealthDiscountLiquidationModule.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {ILiquidationModule} from "../../interfaces/ILiquidationModule.sol";
import {Id} from "../../interfaces/ILotus.sol";
import {ITwoStepOperator} from "../../access/TwoStepOperator.sol";
/// @title IHealthDiscountLiquidationModule
/// @notice Interface for the health-discount liquidation module with per-tranche max discounts.
interface IHealthDiscountLiquidationModule is ILiquidationModule, ITwoStepOperator {
/// @notice Initializes the proxy with owner and operator.
/// @param owner The owner address for upgrades.
/// @param operator The operator address for parameter management.
function initializeModule(address owner, address operator) external;
/// @notice Emitted when per-tranche max liquidation discount is updated.
/// @param id The market whose max liquidation discount changed.
/// @param trancheIndex The tranche whose max liquidation discount changed.
/// @param maxLiquidationDiscount The max liquidation discount for the tranche in WAD.
event MaxLiquidationDiscountUpdated(Id indexed id, uint256 indexed trancheIndex, uint256 maxLiquidationDiscount);
/// @notice Sets per-tranche max liquidation discounts for a market.
/// @dev Only callable by the operator.
/// @param id The market whose max liquidation discounts are updated.
/// @param maxDiscounts Per-tranche max liquidation discounts in WAD.
function setLiquidationParams(Id id, uint256[] memory maxDiscounts) external;
/// @param id The market whose max liquidation discount is returned.
/// @param trancheIndex The tranche whose max liquidation discount is returned.
/// @return discount The max liquidation discount in WAD.
function maxLiquidationDiscount(Id id, uint256 trancheIndex) external view returns (uint256 discount);
/// @notice Returns current discount factor for a borrower (WAD where 1e18 is no discount).
/// @param id The market whose discount factor is evaluated.
/// @param trancheIndex The tranche whose discount factor is evaluated.
/// @param borrower The borrower address.
/// @return discountFactor The current discount factor in WAD.
function getDiscountFactor(Id id, uint256 trancheIndex, address borrower)
external
view
returns (uint256 discountFactor);
/// @notice Encodes module initialization params.
/// @param maxDiscounts Per-tranche max liquidation discounts in WAD.
/// @return The encoded params.
function getEncodedLiquidationParams(uint256[] memory maxDiscounts) external pure returns (bytes memory);
/// @notice Decodes module initialization params.
/// @param liquidationParams Encoded module params.
/// @return maxDiscounts Per-tranche max liquidation discounts in WAD.
function getDecodedLiquidationParams(bytes memory liquidationParams)
external
pure
returns (uint256[] memory maxDiscounts);
}
src/liquidations/interfaces/IHealthDiscountLiquidationModuleFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {IModuleFactory} from "../../factories/interfaces/IModuleFactory.sol";
import {ILotus} from "../../interfaces/ILotus.sol";
/// @title IHealthDiscountLiquidationModuleFactory
/// @notice Factory interface for deploying HealthDiscountLiquidationModule proxies and whitelisting them on Lotus.
interface IHealthDiscountLiquidationModuleFactory is IModuleFactory {
/// @return The Lotus protocol contract.
function LOTUS() external view returns (ILotus);
/// @return The pre-deployed implementation address used by new proxies.
function IMPLEMENTATION() external view returns (address);
/// @notice Emitted when a new HealthDiscountLiquidationModule proxy is deployed.
/// @param module The deployed module address.
/// @param operator The operator of the deployed module.
event HealthDiscountLiquidationModuleDeployed(address indexed module, address indexed operator);
/// @notice Deploys a new HealthDiscountLiquidationModule proxy and enables it on Lotus.
/// @param owner The owner address for upgrades.
/// @param operator The operator address for the new module instance.
/// @return module The address of the deployed proxy.
function deploy(address owner, address operator) external returns (address module);
}
src/liquidations/libraries/BaseLiquidationModule.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.28;
import {SafeTransferLib} from "solady/src/utils/SafeTransferLib.sol";
import {ILiquidationModule, LiquidationQuoteContext} from "../../interfaces/ILiquidationModule.sol";
import {Id, ILotus} from "../../interfaces/ILotus.sol";
import {ILotusLiquidateCallback} from "../../interfaces/ILotusCallbacks.sol";
import {BaseUpgradeableModule} from "../../libraries/BaseUpgradeableModule.sol";
import {LotusErrorsLib} from "../../libraries/LotusErrorsLib.sol";
import {UtilsLib} from "../../libraries/UtilsLib.sol";
/// @notice Shared liquidation request shape used by the bundled base liquidation modules.
struct BaseLiquidationParams {
/// @notice The collateral assets requested for seizure.
uint256 seizedAssets;
/// @notice The debt shares requested for repayment.
uint256 repaidShares;
}
/// @title BaseLiquidationModule
/// @notice Shared base implementation for Lotus liquidation modules.
/// @dev Abstract base for liquidation modules.
abstract contract BaseLiquidationModule is ILiquidationModule, BaseUpgradeableModule {
/* CONSTRUCTOR */
/// @param _lotus The Lotus core contract.
/// @custom:oz-upgrades-unsafe-allow constructor
constructor(ILotus _lotus) BaseUpgradeableModule(_lotus) {}
/* INITIALIZER */
/// @dev Initializes shared liquidation module state.
/// @param _owner The initial module owner.
function __BaseLiquidationModule_init(address _owner) internal onlyInitializing {
__BaseUpgradeableModule_init(_owner);
}
/* LOTUS INTERFACE */
/// @inheritdoc ILiquidationModule
function initializeMarket(Id id, bytes calldata liquidationConfig) external virtual;
/// @inheritdoc ILiquidationModule
function calculateLiquidation(LiquidationQuoteContext calldata context, bytes calldata lmData)
external
view
virtual
returns (uint256, uint256, uint256);
/// @inheritdoc ILiquidationModule
function executeLiquidation(
Id, // id
uint256, // trancheIndex
address, // borrower
address liquidator,
address loanToken,
address collateralToken,
uint256 seizedAssets,
uint256 repaidAssets,
bytes calldata callbackData
) external onlyLotus {
SafeTransferLib.safeTransferFrom(collateralToken, address(LOTUS), liquidator, seizedAssets);
if (callbackData.length > 0) {
ILotusLiquidateCallback(liquidator).onLotusLiquidate(repaidAssets, callbackData);
}
SafeTransferLib.safeTransferFrom(loanToken, liquidator, address(LOTUS), repaidAssets);
}
/// @dev Computes liquidation amounts while enforcing module-specific incentive and close-factor rules.
function _calculateLiquidation(LiquidationQuoteContext calldata context, uint256 seizedAssets, uint256 repaidShares)
internal
view
virtual
returns (uint256 finalSeizedAssets, uint256 finalRepaidShares, uint256 finalRepaidAssets);
/// @dev Validates liquidation-specific inputs.
/// @dev Exactly one of seizedAssets or repaidShares must be non-zero (XOR validation).
function _validateLiquidationInputs(uint256 seizedAssets, uint256 repaidShares) internal pure {
if (!UtilsLib.exactlyOneZero(seizedAssets, repaidShares)) {
revert LotusErrorsLib.InconsistentInput();
}
}
uint256[50] private __gap;
}
src/liquidations/libraries/LiquidationErrorsLib.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.28;
/// @title LiquidationErrorsLib
/// @notice Library containing all custom errors for the LiquidationModule contract.
library LiquidationErrorsLib {
/// @notice Caller is not the liquidation operator.
error NotLiquidationOperator();
/// @notice Caller is not the pending operator.
error NotPendingOperator();
/// @notice Liquidation incentive is outside allowed bounds.
error InvalidLiquidationIncentive();
/// @notice Maximum liquidation discount is outside allowed bounds.
error InvalidMaxLiquidationDiscount();
/// @notice Liquidation params array length does not match the tranche count.
error LiquidationParamsLengthMismatch();
}
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.