Проверенный контрактЧастичноеUNLICENSED
LotusSwapAdapter
Адрес0xeae80f3064fb85ffdebefc7e3f3f44039ef25fdb
- Баланс
0 ETH
- Транзакций
1
- Компилятор
solc 0.8.28
- Тот же код
Только этот контракт
Подробности
- Компилятор
- solc 0.8.28+commit.7893614a
- Язык
- solidity
- Оптимизация
- Да, 200 прогонов
- Версия EVM
- cancun
- Через IR
- да
- Лицензия
- UNLICENSED
- Совпадение
- Частичноекод создания: да, код в сети: да
- Проверен на Sourcify
- Создан в блоке
- 26 436 561
- Транзакция создания
- 0x185a2026d5…5bd5fc680d
11 файлов
- src/bundler3/LotusSwapAdapter.solглавный3,23 КБ
- lib/solady/src/utils/SafeTransferLib.sol32,86 КБ
- src/access/TwoStepOwnable.sol3,72 КБ
- src/bundler3/AdapterBase.sol3,03 КБ
- src/bundler3/interfaces/IAdapterBase.sol2,47 КБ
- src/bundler3/interfaces/ILotusSwapAdapter.sol2,8 КБ
- src/bundler3/interfaces/ILotusSwapRouterRegistry.sol797 Б
- src/interfaces/IBundler3.sol1,62 КБ
- src/interfaces/ILotus.sol27,59 КБ
- src/interfaces/IRiskEngine.sol4,36 КБ
- src/libraries/LotusErrorsLib.sol8,13 КБ
src/bundler3/LotusSwapAdapter.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;
import {SafeTransferLib} from "solady/src/utils/SafeTransferLib.sol";
import {AdapterBase} from "./AdapterBase.sol";
import {LotusErrorsLib} from "../libraries/LotusErrorsLib.sol";
import {ILotusSwapAdapter} from "./interfaces/ILotusSwapAdapter.sol";
import {ILotusSwapRouterRegistry} from "./interfaces/ILotusSwapRouterRegistry.sol";
/// @title LotusSwapAdapter
/// @notice Bundler3 adapter executing aggregator swaps against registry-whitelisted routers.
/// @dev Deliberately separate from LotusBundlerAdapter: this contract performs low-level calls with
/// API-provided calldata and must therefore never hold standing user approvals. Funds only transit it
/// within a bundle.
contract LotusSwapAdapter is AdapterBase, ILotusSwapAdapter {
using SafeTransferLib for address;
/* IMMUTABLES */
/// @inheritdoc ILotusSwapAdapter
ILotusSwapRouterRegistry public immutable ROUTER_REGISTRY;
/* CONSTRUCTOR */
/// @param bundler3 The Bundler3 contract allowed to call adapter entry points.
/// @param routerRegistry The registry validating swap router targets.
constructor(address bundler3, address routerRegistry) AdapterBase(bundler3) {
if (routerRegistry == address(0)) revert LotusErrorsLib.ZeroAddress();
ROUTER_REGISTRY = ILotusSwapRouterRegistry(routerRegistry);
}
/* SWAP ACTIONS */
/// @inheritdoc ILotusSwapAdapter
function sell(
address router,
bytes calldata swapCalldata,
address srcToken,
address destToken,
uint256 maxSrcAmount,
uint256 minDestAmount,
address receiver
) external onlyBundler3 {
if (receiver == address(0)) revert LotusErrorsLib.ZeroAddress();
if (srcToken == destToken) revert SameToken();
if (maxSrcAmount == 0) revert ZeroAmount();
if (minDestAmount == 0) revert ZeroMinDestAmount();
if (!ROUTER_REGISTRY.isWhitelistedRouter(router)) revert RouterNotWhitelisted();
uint256 srcBefore = srcToken.balanceOf(address(this));
uint256 destBefore = destToken.balanceOf(address(this));
// The router approval is capped to maxSrcAmount so it can never consume more than quoted, even when
// the adapter holds a larger in-flight balance.
srcToken.safeApproveWithRetry(router, maxSrcAmount == type(uint256).max ? srcBefore : maxSrcAmount);
(bool ok, bytes memory ret) = router.call(swapCalldata);
if (!ok) {
assembly {
revert(add(ret, 0x20), mload(ret))
}
}
srcToken.safeApprove(router, 0);
// Slippage is enforced on measured balance deltas; router return values are never trusted.
uint256 srcAmount = srcBefore - srcToken.balanceOf(address(this));
if (srcAmount > maxSrcAmount) revert MaxSrcAmountExceeded();
uint256 destAmount = destToken.balanceOf(address(this)) - destBefore;
if (destAmount < minDestAmount) revert InsufficientDestAmount();
if (receiver != address(this)) destToken.safeTransfer(receiver, destAmount);
emit Sold(router, srcToken, destToken, srcAmount, destAmount, receiver);
}
}
lib/solady/src/utils/SafeTransferLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)
///
/// @dev Note:
/// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.
library SafeTransferLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ETH transfer has failed.
error ETHTransferFailed();
/// @dev The ERC20 `transferFrom` has failed.
error TransferFromFailed();
/// @dev The ERC20 `transfer` has failed.
error TransferFailed();
/// @dev The ERC20 `approve` has failed.
error ApproveFailed();
/// @dev The ERC20 `totalSupply` query has failed.
error TotalSupplyQueryFailed();
/// @dev The Permit2 operation has failed.
error Permit2Failed();
/// @dev The Permit2 amount must be less than `2**160 - 1`.
error Permit2AmountOverflow();
/// @dev The Permit2 approve operation has failed.
error Permit2ApproveFailed();
/// @dev The Permit2 lockdown operation has failed.
error Permit2LockdownFailed();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.
uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;
/// @dev Suggested gas stipend for contract receiving ETH to perform a few
/// storage reads and writes, but low enough to prevent griefing.
uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;
/// @dev The unique EIP-712 domain separator for the DAI token contract.
bytes32 internal constant DAI_DOMAIN_SEPARATOR =
0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;
/// @dev The address for the WETH9 contract on Ethereum mainnet.
address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
/// @dev The canonical Permit2 address.
/// [Github](https://github.com/Uniswap/permit2)
/// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
/// @dev The canonical address of the `SELFDESTRUCT` ETH mover.
/// See: https://gist.github.com/Vectorized/1cb8ad4cf393b1378e08f23f79bd99fa
/// [Etherscan](https://etherscan.io/address/0x00000000000073c48c8055bD43D1A53799176f0D)
address internal constant ETH_MOVER = 0x00000000000073c48c8055bD43D1A53799176f0D;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ETH OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.
//
// The regular variants:
// - Forwards all remaining gas to the target.
// - Reverts if the target reverts.
// - Reverts if the current contract has insufficient balance.
//
// The force variants:
// - Forwards with an optional gas stipend
// (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).
// - If the target reverts, or if the gas stipend is exhausted,
// creates a temporary contract to force send the ETH via `SELFDESTRUCT`.
// Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.
// - Reverts if the current contract has insufficient balance.
//
// The try variants:
// - Forwards with a mandatory gas stipend.
// - Instead of reverting, returns whether the transfer succeeded.
/// @dev Sends `amount` (in wei) ETH to `to`.
function safeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Sends all the ETH in the current contract to `to`.
function safeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// Transfer all the ETH and check if it succeeded or not.
if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
if lt(selfbalance(), amount) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.
function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
if lt(selfbalance(), amount) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// forgefmt: disable-next-item
if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)
}
}
/// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.
function trySafeTransferAllETH(address to, uint256 gasStipend)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)
}
}
/// @dev Force transfers ETH to `to`, without triggering the fallback (if any).
/// This method attempts to use a separate contract to send via `SELFDESTRUCT`,
/// and upon failure, deploys a minimal vault to accrue the ETH.
function safeMoveETH(address to, uint256 amount) internal returns (address vault) {
/// @solidity memory-safe-assembly
assembly {
to := shr(96, shl(96, to)) // Clean upper 96 bits.
for { let mover := ETH_MOVER } iszero(eq(to, address())) {} {
let selfBalanceBefore := selfbalance()
if or(lt(selfBalanceBefore, amount), eq(to, mover)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if extcodesize(mover) {
let balanceBefore := balance(to) // Check via delta, in case `SELFDESTRUCT` is bricked.
mstore(0x00, to)
pop(call(gas(), mover, amount, 0x00, 0x20, codesize(), 0x00))
// If `address(to).balance >= amount + balanceBefore`, skip vault workflow.
if iszero(lt(balance(to), add(amount, balanceBefore))) { break }
// Just in case `SELFDESTRUCT` is changed to not revert and do nothing.
if lt(selfBalanceBefore, selfbalance()) { invalid() }
}
let m := mload(0x40)
// If the mover is missing or bricked, deploy a minimal vault
// that withdraws all ETH to `to` when being called only by `to`.
// forgefmt: disable-next-item
mstore(add(m, 0x20), 0x33146025575b600160005260206000f35b3d3d3d3d47335af1601a5760003dfd)
mstore(m, or(to, shl(160, 0x6035600b3d3960353df3fe73)))
// Compute and store the bytecode hash.
mstore8(0x00, 0xff) // Write the prefix.
mstore(0x35, keccak256(m, 0x40))
mstore(0x01, shl(96, address())) // Deployer.
mstore(0x15, 0) // Salt.
vault := keccak256(0x00, 0x55)
pop(call(gas(), vault, amount, codesize(), 0x00, codesize(), 0x00))
// The vault returns a single word on success. Failure reverts with empty data.
if iszero(returndatasize()) {
if iszero(create2(0, m, 0x40, 0)) { revert(codesize(), codesize()) } // For gas estimation.
}
mstore(0x40, m) // Restore the free memory pointer.
break
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC20 OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for
/// the current contract to manage.
function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
///
/// The `from` account must have at least `amount` approved for the current contract to manage.
function trySafeTransferFrom(address token, address from, address to, uint256 amount)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
success := lt(or(iszero(extcodesize(token)), returndatasize()), success)
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends all of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have their entire balance approved for the current contract to manage.
function safeTransferAllFrom(address token, address from, address to)
internal
returns (uint256 amount)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
// Read the balance, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
)
) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.
amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransfer(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sends all of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransferAll(address token, address to) internal returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
mstore(0x20, address()) // Store the address of the current contract.
// Read the balance, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
)
) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
mstore(0x14, to) // Store the `to` argument.
amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// Reverts upon failure.
function safeApprove(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
/// then retries the approval again (some tokens, e.g. USDT, requires this).
/// Reverts upon failure.
function safeApproveWithRetry(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
// Perform the approval, retrying upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x34, 0) // Store 0 for the `amount`.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
mstore(0x34, amount) // Store back the original `amount`.
// Retry the approval, reverting upon failure.
success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
// Check the `extcodesize` again just in case the token selfdestructs lol.
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
}
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Returns the amount of ERC20 `token` owned by `account`.
/// Returns zero if the `token` does not exist.
function balanceOf(address token, address account) internal view returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, account) // Store the `account` argument.
mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
amount :=
mul( // The arguments of `mul` are evaluated from right to left.
mload(0x20),
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
)
)
}
}
/// @dev Performs a `token.balanceOf(account)` check.
/// `implemented` denotes whether the `token` does not implement `balanceOf`.
/// `amount` is zero if the `token` does not implement `balanceOf`.
function checkBalanceOf(address token, address account)
internal
view
returns (bool implemented, uint256 amount)
{
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, account) // Store the `account` argument.
mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
implemented :=
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
)
amount := mul(mload(0x20), implemented)
}
}
/// @dev Returns the total supply of the `token`.
/// Reverts if the token does not exist or does not implement `totalSupply()`.
function totalSupply(address token) internal view returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x18160ddd) // `totalSupply()`.
if iszero(
and(gt(returndatasize(), 0x1f), staticcall(gas(), token, 0x1c, 0x04, 0x00, 0x20))
) {
mstore(0x00, 0x54cd9435) // `TotalSupplyQueryFailed()`.
revert(0x1c, 0x04)
}
result := mload(0x00)
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// If the initial attempt fails, try to use Permit2 to transfer the token.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for the current contract to manage.
function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {
if (!trySafeTransferFrom(token, from, to, amount)) {
permit2TransferFrom(token, from, to, amount);
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.
/// Reverts upon failure.
function permit2TransferFrom(address token, address from, address to, uint256 amount)
internal
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(add(m, 0x74), shr(96, shl(96, token)))
mstore(add(m, 0x54), amount)
mstore(add(m, 0x34), to)
mstore(add(m, 0x20), shl(96, from))
// `transferFrom(address,address,uint160,address)`.
mstore(m, 0x36c78516000000000000000000000000)
let p := PERMIT2
let exists := eq(chainid(), 1)
if iszero(exists) { exists := iszero(iszero(extcodesize(p))) }
if iszero(
and(
call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00),
lt(iszero(extcodesize(token)), exists) // Token has code and Permit2 exists.
)
) {
mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.
revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04)
}
}
}
/// @dev Permit a user to spend a given amount of
/// another user's tokens via native EIP-2612 permit if possible, falling
/// back to Permit2 if native permit fails or is not implemented on the token.
function permit2(
address token,
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
for {} shl(96, xor(token, WETH9)) {} {
mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.
// Gas stipend to limit gas burn for tokens that don't refund gas when
// an non-existing function is called. 5K should be enough for a SLOAD.
staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)
)
) { break }
// After here, we can be sure that token is a contract.
let m := mload(0x40)
mstore(add(m, 0x34), spender)
mstore(add(m, 0x20), shl(96, owner))
mstore(add(m, 0x74), deadline)
if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {
mstore(0x14, owner)
mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.
mstore(
add(m, 0x94),
lt(iszero(amount), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
)
mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
// `nonces` is already at `add(m, 0x54)`.
// `amount != 0` is already stored at `add(m, 0x94)`.
mstore(add(m, 0xb4), and(0xff, v))
mstore(add(m, 0xd4), r)
mstore(add(m, 0xf4), s)
success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)
break
}
mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.
mstore(add(m, 0x54), amount)
mstore(add(m, 0x94), and(0xff, v))
mstore(add(m, 0xb4), r)
mstore(add(m, 0xd4), s)
success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)
break
}
}
if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);
}
/// @dev Simple permit on the Permit2 contract.
function simplePermit2(
address token,
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(m, 0x927da105) // `allowance(address,address,address)`.
{
let addressMask := shr(96, not(0))
mstore(add(m, 0x20), and(addressMask, owner))
mstore(add(m, 0x40), and(addressMask, token))
mstore(add(m, 0x60), and(addressMask, spender))
mstore(add(m, 0xc0), and(addressMask, spender))
}
let p := mul(PERMIT2, iszero(shr(160, amount)))
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.
staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)
)
) {
mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.
revert(add(0x18, shl(2, iszero(p))), 0x04)
}
mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).
// `owner` is already `add(m, 0x20)`.
// `token` is already at `add(m, 0x40)`.
mstore(add(m, 0x60), amount)
mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.
// `nonce` is already at `add(m, 0xa0)`.
// `spender` is already at `add(m, 0xc0)`.
mstore(add(m, 0xe0), deadline)
mstore(add(m, 0x100), 0x100) // `signature` offset.
mstore(add(m, 0x120), 0x41) // `signature` length.
mstore(add(m, 0x140), r)
mstore(add(m, 0x160), s)
mstore(add(m, 0x180), shl(248, v))
if iszero( // Revert if token does not have code, or if the call fails.
mul(extcodesize(token), call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00))) {
mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Approves `spender` to spend `amount` of `token` for `address(this)`.
function permit2Approve(address token, address spender, uint160 amount, uint48 expiration)
internal
{
/// @solidity memory-safe-assembly
assembly {
let addressMask := shr(96, not(0))
let m := mload(0x40)
mstore(m, 0x87517c45) // `approve(address,address,uint160,uint48)`.
mstore(add(m, 0x20), and(addressMask, token))
mstore(add(m, 0x40), and(addressMask, spender))
mstore(add(m, 0x60), and(addressMask, amount))
mstore(add(m, 0x80), and(0xffffffffffff, expiration))
if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
mstore(0x00, 0x324f14ae) // `Permit2ApproveFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Revokes an approval for `token` and `spender` for `address(this)`.
function permit2Lockdown(address token, address spender) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(m, 0xcc53287f) // `Permit2.lockdown`.
mstore(add(m, 0x20), 0x20) // Offset of the `approvals`.
mstore(add(m, 0x40), 1) // `approvals.length`.
mstore(add(m, 0x60), shr(96, shl(96, token)))
mstore(add(m, 0x80), shr(96, shl(96, spender)))
if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
mstore(0x00, 0x96b3de23) // `Permit2LockdownFailed()`.
revert(0x1c, 0x04)
}
}
}
}
src/access/TwoStepOwnable.sol
// SPDX-License-Identifier: UNLICENSED
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/bundler3/AdapterBase.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;
import {IBundler3} from "../interfaces/IBundler3.sol";
import {LotusErrorsLib} from "../libraries/LotusErrorsLib.sol";
import {SafeTransferLib} from "solady/src/utils/SafeTransferLib.sol";
import {IAdapterBase} from "./interfaces/IAdapterBase.sol";
/// @title AdapterBase
/// @notice Base authorization and helper layer for Bundler3 adapters.
/// @dev Minimal base providing Bundler3 gating and helpers for adapters.
abstract contract AdapterBase is IAdapterBase {
/// @inheritdoc IAdapterBase
address public immutable BUNDLER3;
/// @param bundler3 The Bundler3 contract allowed to call adapter entry points.
constructor(address bundler3) {
if (bundler3 == address(0)) revert LotusErrorsLib.ZeroAddress();
BUNDLER3 = bundler3;
}
/// @notice Native tokens are received by the adapter and should be used afterwards.
/// @dev Allows wrapped native contracts and bundle calls to transfer native tokens to the adapter.
receive() external payable virtual {}
/// @dev Restricts calls to Bundler3.
modifier onlyBundler3() {
if (msg.sender != BUNDLER3) revert UnauthorizedSender();
_;
}
/// @inheritdoc IAdapterBase
function tagIntegrator(bytes32 integratorId) external onlyBundler3 {
if (integratorId == bytes32(0)) revert ZeroIntegratorId();
emit IntegratorTagged(integratorId, _initiator());
}
/// @inheritdoc IAdapterBase
function nativeTransfer(address receiver, uint256 amount) external onlyBundler3 {
if (receiver == address(0)) revert LotusErrorsLib.ZeroAddress();
if (receiver == address(this)) revert AdapterAddress();
if (amount == type(uint256).max) {
amount = address(this).balance;
} else if (amount == 0) {
revert ZeroAmount();
}
if (amount > 0) SafeTransferLib.safeTransferETH(receiver, amount);
}
/// @inheritdoc IAdapterBase
function erc20Transfer(address token, address receiver, uint256 amount) external onlyBundler3 {
if (receiver == address(0)) revert LotusErrorsLib.ZeroAddress();
if (receiver == address(this)) revert AdapterAddress();
if (amount == type(uint256).max) {
amount = SafeTransferLib.balanceOf(token, address(this));
} else if (amount == 0) {
revert ZeroAmount();
}
if (amount > 0) SafeTransferLib.safeTransfer(token, receiver, amount);
}
/// @dev Returns the bundle initiator.
function _initiator() internal view returns (address) {
return IBundler3(BUNDLER3).initiator();
}
/// @dev Calls bundler3.reenter with an already encoded Call array.
function _reenterBundler3(bytes calldata data) internal {
(bool ok, bytes memory ret) = BUNDLER3.call(bytes.concat(IBundler3.reenter.selector, data));
if (!ok) {
assembly {
revert(add(ret, 0x20), mload(ret))
}
}
}
}
src/bundler3/interfaces/IAdapterBase.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;
/// @title IAdapterBase
/// @notice Shared interface for Bundler3-gated adapter bases.
interface IAdapterBase {
/// @notice Caller is neither the configured Bundler3 nor Lotus during a callback.
error UnauthorizedSender();
/// @notice Action would make the adapter itself receive assets or own a position.
error AdapterAddress();
/// @notice Asset amount resolves to zero.
error ZeroAmount();
/// @notice Integrator id is the reserved zero value.
error ZeroIntegratorId();
/// @notice Emitted when a bundle self-reports the integrator that originated it.
/// @dev The tag is not authenticated. Consumers should require a matching successful Lotus flow from the same
/// trusted adapter, attribute only flows that follow at least one tag instance in the transaction, and treat
/// multiple distinct ids from one adapter in a transaction as ambiguous and unattributable.
/// @param integratorId Partner-provided integrator identifier.
/// @param initiator The original Bundler3 multicall caller.
event IntegratorTagged(bytes32 indexed integratorId, address indexed initiator);
/// @return The Bundler3 contract allowed to call adapter entry points.
function BUNDLER3() external view returns (address);
/// @notice Self-reports an integrator for the current bundle.
/// @dev Partners should include this call once near the start of the outer bundle. This event provides flow
/// attribution only; it does not create persistent or exclusive ownership of a user's fungible Lotus position.
/// @param integratorId Partner-provided non-zero identifier.
function tagIntegrator(bytes32 integratorId) external;
/// @notice Transfers native tokens from the adapter.
/// @param receiver The recipient.
/// @param amount The amount to transfer. Pass `type(uint256).max` to transfer the adapter's full native balance
/// (this allows zero-value sweeps).
function nativeTransfer(address receiver, uint256 amount) external;
/// @notice Transfers ERC20 tokens from the adapter.
/// @param token The token to transfer.
/// @param receiver The recipient.
/// @param amount The amount to transfer. Pass `type(uint256).max` to transfer the adapter's full token balance
/// (this allows zero-value sweeps).
function erc20Transfer(address token, address receiver, uint256 amount) external;
}
src/bundler3/interfaces/ILotusSwapAdapter.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;
import {ILotusSwapRouterRegistry} from "./ILotusSwapRouterRegistry.sol";
/// @title ILotusSwapAdapter
/// @notice Interface for the Bundler3 swap adapter.
interface ILotusSwapAdapter {
/// @notice Swap target is not whitelisted in the router registry.
error RouterNotWhitelisted();
/// @notice Source and destination token are identical.
error SameToken();
/// @notice Slippage floor is the reserved zero value.
error ZeroMinDestAmount();
/// @notice Received destination amount is below the slippage floor.
error InsufficientDestAmount();
/// @notice Consumed source amount exceeds the slippage ceiling.
error MaxSrcAmountExceeded();
/// @notice Emitted after a successful swap.
/// @param router The whitelisted router that executed the swap.
/// @param srcToken The token sold.
/// @param destToken The token bought.
/// @param srcAmount The source amount consumed from the adapter's balance.
/// @param destAmount The destination amount received and forwarded.
/// @param receiver The recipient of the destination tokens.
event Sold(
address indexed router,
address indexed srcToken,
address indexed destToken,
uint256 srcAmount,
uint256 destAmount,
address receiver
);
/// @return The registry validating swap router targets.
function ROUTER_REGISTRY() external view returns (ILotusSwapRouterRegistry);
/// @notice Sells `srcToken` held by this adapter for `destToken` through a whitelisted router.
/// @dev Exact-in only; the sell amount is baked into `swapCalldata` by the off-chain quoter. The received
/// amount is measured as the adapter's `destToken` balance delta and forwarded to `receiver`. Leftover
/// `srcToken` stays on the adapter and should be swept with a subsequent `erc20Transfer` bundle call.
/// @param router The swap router to call; must be whitelisted in `ROUTER_REGISTRY`.
/// @param swapCalldata The opaque router calldata obtained from the aggregator API.
/// @param srcToken The token to sell.
/// @param destToken The token to buy.
/// @param maxSrcAmount The maximum source amount the router may consume; must be non-zero. The router
/// approval is capped to this value (`type(uint256).max` caps to the adapter's current balance).
/// @param minDestAmount The minimum acceptable received amount; must be non-zero.
/// @param receiver The recipient of the received `destToken`.
function sell(
address router,
bytes calldata swapCalldata,
address srcToken,
address destToken,
uint256 maxSrcAmount,
uint256 minDestAmount,
address receiver
) external;
}
src/bundler3/interfaces/ILotusSwapRouterRegistry.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;
/// @title ILotusSwapRouterRegistry
/// @notice Interface for the owner-managed swap router whitelist.
interface ILotusSwapRouterRegistry {
/// @notice Emitted when a router's whitelist status changes.
/// @param router The router address.
/// @param whitelisted The new whitelist status.
event RouterSet(address indexed router, bool whitelisted);
/// @notice Returns whether `router` is an allowed swap target.
function isWhitelistedRouter(address router) external view returns (bool);
/// @notice Sets the whitelist status of a router.
/// @param router The router address.
/// @param whitelisted The new whitelist status.
function setRouter(address router, bool whitelisted) external;
}
src/interfaces/IBundler3.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;
/// @notice Single planned call in a Bundler3 bundle.
struct Call {
/// @notice Call target.
address to;
/// @notice Calldata for `to`.
bytes data;
/// @notice Native value sent with the call.
uint256 value;
/// @notice Whether to continue the bundle when this call reverts.
bool skipRevert;
/// @notice Expected reenter bundle hash when this call triggers a callback.
bytes32 callbackHash;
}
/// @title IBundler3
/// @notice Interface for the Bundler3 multicall contract.
/// @dev `multicall` executes the planned bundle. `reenter` resumes execution from protocol callbacks and is expected
/// to use the callback bundle committed via `callbackHash`.
interface IBundler3 {
/// @notice Executes a sequence of calls atomically.
/// @param bundle The ordered array of calls to execute.
function multicall(Call[] calldata bundle) external payable;
/// @notice Resumes bundle execution from within a protocol callback.
/// @param bundle The callback bundle whose hash must match the committed callbackHash.
function reenter(Call[] calldata bundle) external;
/// @notice Returns the hash of the currently expected reenter bundle.
/// @return The callback bundle hash, or zero if no callback is pending.
function reenterHash() external view returns (bytes32);
/// @notice Returns the address that initiated the current multicall.
/// @return The original multicall caller, or address(0) if no bundle is executing.
function initiator() external view returns (address);
}
src/interfaces/ILotus.sol
// SPDX-License-Identifier: UNLICENSED
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 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.
struct Tranche {
/// @notice Total amount of assets supplied at this tranche.
uint128 supplyAssets;
/// @notice Total supply shares for this tranche.
uint128 supplyShares;
/// @notice Total borrow assets for only the current tranche.
uint128 borrowAssets;
/// @notice Total borrow shares for only the current tranche.
uint128 borrowShares;
/// @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 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 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
);
/// @return domainSeparator The EIP-712 domain separator for Lotus.
function DOMAIN_SEPARATOR() external view returns (bytes32 domainSeparator);
/* 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 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 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;
/* 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).
/// @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).
/// @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 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 all tranche positions for a user in a given market.
/// @param id The market id.
/// @param user The address of the user.
/// @return An array of Position structs indexed by tranche.
function getPositions(Id id, address user) 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/IRiskEngine.sol
// SPDX-License-Identifier: UNLICENSED
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
view
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/LotusErrorsLib.sol
// SPDX-License-Identifier: UNLICENSED
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 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();
/* 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();
}
Настройки компилятораПоказать
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"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/src/",
"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/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"prb-math/=lib/prb-math/src/"
]
}Исходный код и метаданные: Sourcify.
Исходный код принадлежит авторам контракта.