Verified contractExactBUSL-1.1
V3ProviderLib
Address0x10333b8978074a77dfdcb7345c976fc0ac1fb7e5
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.34
- Same code
Only this contract
Details
- Compiler
- solc 0.8.34+commit.80d5c536
- Language
- solidity
- Optimization
- Yes, 20 runs
- EVM version
- osaka
- Via IR
- yes
- License
- BUSL-1.1
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,282,612
- Creation transaction
- 0xd63d1569bc…7c8a5195b9
src/provider/libraries/V3ProviderLib.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.34;
import { IOracle } from "moolah/interfaces/IOracle.sol";
import { IMoolah, MarketParams, Id } from "moolah/interfaces/IMoolah.sol";
import { MarketParamsLib } from "moolah/libraries/MarketParamsLib.sol";
import { IV3DexAdapter } from "../interfaces/IV3DexAdapter.sol";
/**
* @title V3ProviderLib
* @author Lista DAO
* @notice Deposit-quoting and USD-valuation math for {V3Provider}, carved out as an external library so
* the vault runtime stays under EIP-170. Linked and DELEGATECALL-ed, like {V3PositionLib}.
* @dev The vault's immutables (adapter, tokens, decimals) are not visible under DELEGATECALL, so the
* caller passes them in as {Ctx}. Errors are declared here as well as on the vault: a custom
* error selector is derived from its signature alone, so `ZeroShares()` raised here is
* indistinguishable from the vault's own.
*/
library V3ProviderLib {
/// @dev Fixed-point scale for the deposit composition-ratio math.
uint256 internal constant WAD = 1e18;
error ZeroShares();
error OracleZero();
error ProviderNotRegistered();
error InvalidMarket();
/// @param adapter DEX adapter holding the position.
/// @param oracle Resilient oracle pricing TOKEN0/TOKEN1 in 8-decimal USD.
struct Ctx {
address adapter;
address oracle;
address token0;
address token1;
uint8 dec0;
uint8 dec1;
}
/// @dev Entries only: without Moolah.setProvider, withdrawals bypass the vault's hooks. Runs via
/// DELEGATECALL, so address(this) is the vault. Exits are never gated.
function requireRegistered(IMoolah moolah, MarketParams calldata marketParams) external view {
if (moolah.providers(MarketParamsLib.id(marketParams), address(this)) != address(this)) {
revert ProviderNotRegistered();
}
}
/// @dev The market must use the vault (address(this) under DELEGATECALL) as its collateral token.
function requireCollateral(IMoolah moolah, Id id) external view {
if (moolah.idToMarketParams(id).collateralToken != address(this)) revert InvalidMarket();
}
/// @notice 8-decimal USD value of a (amount0, amount1) pair at the resilient oracle's prices.
function amountsValueUsd(Ctx memory c, uint256 amount0, uint256 amount1) external view returns (uint256) {
return _amountsValueUsd(c, amount0, amount1);
}
/// @notice The shares a deposit mints and the amounts it consumes — pro-rata of the live composition.
/// @dev Both the consumed amounts and the share credit come from the composition the vault holds at the
/// CURRENT pool price — the same composition `removeLiquidity` hands back on the way out. Issuance
/// and redemption therefore share one basis, so a deposit followed by an immediate exit returns the
/// principal (to the wei: amounts round UP and shares round DOWN, so any dust stays with the
/// existing holders), and the price a depositor enters at is the price they can leave at.
///
/// This does NOT make an entry manipulation-proof. A third party can move the pool price before the
/// deposit lands, which shifts the composition and so the ratio the deposit binds to; the depositor
/// then buys a skewed basket that is worth less once the price reverts, up to the position's
/// convexity span over the range. The credit stays fair FOR that price — nothing is over- or
/// under-issued — so the guard is the caller's per-leg `amount0Min`/`amount1Min`. Those are a
/// tolerance, not a switch: they reject any shift that starves a leg past its floor and permit
/// every shift below it, so what they leave the depositor exposed to is exactly the tolerance the
/// caller chose. Size them off a fresh `previewDepositAmounts` quote with a tight band — at the
/// configured +/-50 bps range the composition is hypersensitive, and a 3 bps price nudge already
/// moves the starved leg to 84% of its quote — and pass a non-zero `minShares` alongside them.
///
/// A credit taken from the FAIR composition instead would put issuance and redemption on two
/// different bases, and the gap between them is exactly the deposit-withdraw cycle Bailsec raised
/// (Issue_05). Capping the credit with a spot-composition `min()` does not close that gap either:
/// the per-leg fraction is first order in the spot-vs-fair deviation, so it taxes an ordinary
/// deposit far harder than the second-order leak it was meant to remove.
///
/// The pool price stays out of the *collateral valuation* path: {V3ProviderOracle} still prices the
/// share off the rate-anchored fair composition. That is not a second basis an attacker can
/// arbitrage — it mints and burns nothing — and by LP convexity a redemption at any spot returns at
/// least the oracle's fair value, so the oracle errs conservative. `haircutBps` carries that gap.
function quoteDeposit(
Ctx memory c,
uint256 supplyBefore,
uint256 amount0Desired,
uint256 amount1Desired
) external view returns (uint256 shares, uint256 amount0Used, uint256 amount1Used) {
IV3DexAdapter adapter = IV3DexAdapter(c.adapter);
(uint256 t0, uint256 t1) = adapter.positionAmountsAt(adapter.spotSqrtPriceX96());
if (_amountsValueUsd(c, t0, t1) == 0) revert ZeroShares();
uint256 frac = _compositionFractionWad(amount0Desired, amount1Desired, t0, t1);
amount0Used = (t0 * frac + WAD - 1) / WAD;
amount1Used = (t1 * frac + WAD - 1) / WAD;
shares = (supplyBefore * frac) / WAD;
}
function _amountsValueUsd(Ctx memory c, uint256 amount0, uint256 amount1) internal view returns (uint256) {
uint256 price0 = IOracle(c.oracle).peek(c.token0); // 8 decimals
uint256 price1 = IOracle(c.oracle).peek(c.token1); // 8 decimals
// Fail closed: a broken feed on either leg (price 0) must revert, not silently value the position on
// one leg (which would under-price the collateral and enable unfair liquidation / over-borrow).
if (price0 == 0 || price1 == 0) revert OracleZero();
return (amount0 * price0) / (10 ** c.dec0) + (amount1 * price1) / (10 ** c.dec1);
}
/// @dev Per-leg fraction of a composition that (amount0, amount1) covers: min(a0/c0, a1/c1) in WAD.
function _compositionFractionWad(
uint256 amount0,
uint256 amount1,
uint256 comp0,
uint256 comp1
) internal pure returns (uint256) {
if (comp0 == 0) return (amount1 * WAD) / comp1;
if (comp1 == 0) return (amount0 * WAD) / comp0;
uint256 frac0 = (amount0 * WAD) / comp0;
uint256 frac1 = (amount1 * WAD) / comp1;
return frac0 < frac1 ? frac0 : frac1;
}
}
src/moolah/interfaces/IMoolah.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.34;
type Id is bytes32;
struct MarketParams {
address loanToken;
address collateralToken;
address oracle;
address irm;
uint256 lltv;
}
/// @dev Warning: For `feeRecipient`, `supplyShares` does not contain the accrued shares since the last interest
/// accrual.
struct Position {
uint256 supplyShares;
uint128 borrowShares;
uint128 collateral;
}
/// @dev Warning: `totalSupplyAssets` does not contain the accrued interest since the last interest accrual.
/// @dev Warning: `totalBorrowAssets` does not contain the accrued interest since the last interest accrual.
/// @dev Warning: `totalSupplyShares` does not contain the additional shares accrued by `feeRecipient` since the last
/// interest accrual.
struct Market {
uint128 totalSupplyAssets;
uint128 totalSupplyShares;
uint128 totalBorrowAssets;
uint128 totalBorrowShares;
uint128 lastUpdate;
uint128 fee;
}
struct Authorization {
address authorizer;
address authorized;
bool isAuthorized;
uint256 nonce;
uint256 deadline;
}
struct Signature {
uint8 v;
bytes32 r;
bytes32 s;
}
/// @dev This interface is used for factorizing IMoolahStaticTyping and IMoolah.
/// @dev Consider using the IMoolah interface instead of this one.
interface IMoolahBase {
/// @notice The EIP-712 domain separator used in the encoding of the signatures for `setAuthorizationWithSig`.
function domainSeparator() external view returns (bytes32);
/// @notice The fee recipient of all markets.
/// @dev The recipient receives the fees of a given market through a supply position on that market.
function feeRecipient() external view returns (address);
/// @notice Whether the `irm` is enabled.
function isIrmEnabled(address irm) external view returns (bool);
/// @notice Whether the `lltv` is enabled.
function isLltvEnabled(uint256 lltv) external view returns (bool);
/// @notice Whether `authorized` is authorized to modify `authorizer`'s position on all markets.
/// @dev Anyone is authorized to modify their own positions, regardless of this variable.
function isAuthorized(address authorizer, address authorized) external view returns (bool);
/// @notice The `authorizer`'s current nonce. Used to prevent replay attacks with EIP-712 signatures.
function nonce(address authorizer) external view returns (uint256);
/// @notice Enables `irm` as a possible IRM for market creation.
/// @dev Warning: It is not possible to disable an IRM.
function enableIrm(address irm) external;
/// @notice Enables `lltv` as a possible LLTV for market creation.
/// @dev Warning: It is not possible to disable a LLTV.
function enableLltv(uint256 lltv) external;
/// @notice Sets the `newFee` for the given market `marketParams`.
/// @param newFee The new fee, scaled by WAD.
/// @dev Warning: The recipient can be the zero address.
function setFee(MarketParams memory marketParams, uint256 newFee) external;
/// @notice Sets `newFeeRecipient` as `feeRecipient` of the fee.
/// @dev Warning: If the fee recipient is set to the zero address, fees will accrue there and will be lost.
/// @dev Modifying the fee recipient will allow the new recipient to claim any pending fees not yet accrued. To
/// ensure that the current recipient receives all due fees, accrue interest manually prior to making any changes.
function setFeeRecipient(address newFeeRecipient) external;
/// @notice Creates the market `marketParams`.
/// @dev Here is the list of assumptions on the market's dependencies (tokens, IRM and oracle) that guarantees
/// Moolah behaves as expected:
/// - The token should be ERC-20 compliant, except that it can omit return values on `transfer` and `transferFrom`.
/// - The token balance of Moolah should only decrease on `transfer` and `transferFrom`. In particular, tokens with
/// burn functions are not supported.
/// - The token should not re-enter Moolah on `transfer` nor `transferFrom`.
/// - The token balance of the sender (resp. receiver) should decrease (resp. increase) by exactly the given amount
/// on `transfer` and `transferFrom`. In particular, tokens with fees on transfer are not supported.
/// - The IRM should not re-enter Moolah.
/// - The oracle should return a price with the correct scaling.
/// @dev Here is a list of properties on the market's dependencies that could break Moolah's liveness properties
/// (funds could get stuck):
/// - The token can revert on `transfer` and `transferFrom` for a reason other than an approval or balance issue.
/// - A very high amount of assets (~1e35) supplied or borrowed can make the computation of `toSharesUp` and
/// `toSharesDown` overflow.
/// - The IRM can revert on `borrowRate`.
/// - A very high borrow rate returned by the IRM can make the computation of `interest` in `_accrueInterest`
/// overflow.
/// - The oracle can revert on `price`. Note that this can be used to prevent `borrow`, `withdrawCollateral` and
/// `liquidate` from being used under certain market conditions.
/// - The price from the oracle must have 8 decimals.
/// - A very high price returned by the oracle can make the computation of `maxBorrow` in `_isHealthy` overflow, or
/// the computation of `assetsRepaid` in `liquidate` overflow.
/// @dev The borrow share price of a market with less than 1e4 assets borrowed can be decreased by manipulations, to
/// the point where `totalBorrowShares` is very large and borrowing overflows.
function createMarket(MarketParams memory marketParams) external;
/// @notice Supplies `assets` or `shares` on behalf of `onBehalf`, optionally calling back the caller's
/// `onMoolahSupply` function with the given `data`.
/// @dev Either `assets` or `shares` should be zero. Most use cases should rely on `assets` as an input so the
/// caller is guaranteed to have `assets` tokens pulled from their balance, but the possibility to mint a specific
/// amount of shares is given for full compatibility and precision.
/// @dev Supplying a large amount can revert for overflow.
/// @dev Supplying an amount of shares may lead to supply more or fewer assets than expected due to slippage.
/// Consider using the `assets` parameter to avoid this.
/// @param marketParams The market to supply assets to.
/// @param assets The amount of assets to supply.
/// @param shares The amount of shares to mint.
/// @param onBehalf The address that will own the increased supply position.
/// @param data Arbitrary data to pass to the `onMoolahSupply` callback. Pass empty data if not needed.
/// @return assetsSupplied The amount of assets supplied.
/// @return sharesSupplied The amount of shares minted.
function supply(
MarketParams memory marketParams,
uint256 assets,
uint256 shares,
address onBehalf,
bytes memory data
) external returns (uint256 assetsSupplied, uint256 sharesSupplied);
/// @notice Withdraws `assets` or `shares` on behalf of `onBehalf` and sends the assets to `receiver`.
/// @dev Either `assets` or `shares` should be zero. To withdraw max, pass the `shares`'s balance of `onBehalf`.
/// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
/// @dev Withdrawing an amount corresponding to more shares than supplied will revert for underflow.
/// @dev It is advised to use the `shares` input when withdrawing the full position to avoid reverts due to
/// conversion roundings between shares and assets.
/// @param marketParams The market to withdraw assets from.
/// @param assets The amount of assets to withdraw.
/// @param shares The amount of shares to burn.
/// @param onBehalf The address of the owner of the supply position.
/// @param receiver The address that will receive the withdrawn assets.
/// @return assetsWithdrawn The amount of assets withdrawn.
/// @return sharesWithdrawn The amount of shares burned.
function withdraw(
MarketParams memory marketParams,
uint256 assets,
uint256 shares,
address onBehalf,
address receiver
) external returns (uint256 assetsWithdrawn, uint256 sharesWithdrawn);
/// @notice Borrows `assets` or `shares` on behalf of `onBehalf` and sends the assets to `receiver`.
/// @dev Either `assets` or `shares` should be zero. Most use cases should rely on `assets` as an input so the
/// caller is guaranteed to borrow `assets` of tokens, but the possibility to mint a specific amount of shares is
/// given for full compatibility and precision.
/// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
/// @dev Borrowing a large amount can revert for overflow.
/// @dev Borrowing an amount of shares may lead to borrow fewer assets than expected due to slippage.
/// Consider using the `assets` parameter to avoid this.
/// @param marketParams The market to borrow assets from.
/// @param assets The amount of assets to borrow.
/// @param shares The amount of shares to mint.
/// @param onBehalf The address that will own the increased borrow position.
/// @param receiver The address that will receive the borrowed assets.
/// @return assetsBorrowed The amount of assets borrowed.
/// @return sharesBorrowed The amount of shares minted.
function borrow(
MarketParams memory marketParams,
uint256 assets,
uint256 shares,
address onBehalf,
address receiver
) external returns (uint256 assetsBorrowed, uint256 sharesBorrowed);
/// @notice Repays `assets` or `shares` on behalf of `onBehalf`, optionally calling back the caller's
/// `onMoolahRepay` function with the given `data`.
/// @dev Either `assets` or `shares` should be zero. To repay max, pass the `shares`'s balance of `onBehalf`.
/// @dev Repaying an amount corresponding to more shares than borrowed will revert for underflow.
/// @dev It is advised to use the `shares` input when repaying the full position to avoid reverts due to conversion
/// roundings between shares and assets.
/// @dev An attacker can front-run a repay with a small repay making the transaction revert for underflow.
/// @param marketParams The market to repay assets to.
/// @param assets The amount of assets to repay.
/// @param shares The amount of shares to burn.
/// @param onBehalf The address of the owner of the debt position.
/// @param data Arbitrary data to pass to the `onMoolahRepay` callback. Pass empty data if not needed.
/// @return assetsRepaid The amount of assets repaid.
/// @return sharesRepaid The amount of shares burned.
function repay(
MarketParams memory marketParams,
uint256 assets,
uint256 shares,
address onBehalf,
bytes memory data
) external returns (uint256 assetsRepaid, uint256 sharesRepaid);
/// @notice Supplies `assets` of collateral on behalf of `onBehalf`, optionally calling back the caller's
/// `onMoolahSupplyCollateral` function with the given `data`.
/// @dev Interest are not accrued since it's not required and it saves gas.
/// @dev Supplying a large amount can revert for overflow.
/// @param marketParams The market to supply collateral to.
/// @param assets The amount of collateral to supply.
/// @param onBehalf The address that will own the increased collateral position.
/// @param data Arbitrary data to pass to the `onMoolahSupplyCollateral` callback. Pass empty data if not needed.
function supplyCollateral(
MarketParams memory marketParams,
uint256 assets,
address onBehalf,
bytes memory data
) external;
/// @notice Withdraws `assets` of collateral on behalf of `onBehalf` and sends the assets to `receiver`.
/// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
/// @dev Withdrawing an amount corresponding to more collateral than supplied will revert for underflow.
/// @param marketParams The market to withdraw collateral from.
/// @param assets The amount of collateral to withdraw.
/// @param onBehalf The address of the owner of the collateral position.
/// @param receiver The address that will receive the collateral assets.
function withdrawCollateral(
MarketParams memory marketParams,
uint256 assets,
address onBehalf,
address receiver
) external;
/// @notice Liquidates the given `repaidShares` of debt asset or seize the given `seizedAssets` of collateral on the
/// given market `marketParams` of the given `borrower`'s position, optionally calling back the caller's
/// `onMoolahLiquidate` function with the given `data`.
/// @dev Either `seizedAssets` or `repaidShares` should be zero.
/// @dev Seizing more than the collateral balance will underflow and revert without any error message.
/// @dev Repaying more than the borrow balance will underflow and revert without any error message.
/// @dev An attacker can front-run a liquidation with a small repay making the transaction revert for underflow.
/// @param marketParams The market of the position.
/// @param borrower The owner of the position.
/// @param seizedAssets The amount of collateral to seize.
/// @param repaidShares The amount of shares to repay.
/// @param data Arbitrary data to pass to the `onMoolahLiquidate` callback. Pass empty data if not needed.
/// @return The amount of assets seized.
/// @return The amount of assets repaid.
function liquidate(
MarketParams memory marketParams,
address borrower,
uint256 seizedAssets,
uint256 repaidShares,
bytes memory data
) external returns (uint256, uint256);
/// @notice Liquidates the broker position of `borrower` by burning `badDebtShares` from the fee recipient's supply
/// position.
/// @dev This function can only be called by the market's broker.
/// @dev This function does not check whether the position is unhealthy. It is the broker's responsibility to only
/// call this function when the position is unhealthy.
/// @param marketParams The market of the position.
/// @param borrower The owner of the position.
/// @param badDebtShares The amount of borrow shares to liquidate.
/// @return The amount of assets seized.
/// @return The amount of assets repaid.
function liquidateBrokerPosition(
MarketParams memory marketParams,
address borrower,
uint256 badDebtShares
) external returns (uint256, uint256);
/// @notice Executes a flash loan.
/// @dev Flash loans have access to the whole balance of the contract (the liquidity and deposited collateral of all
/// markets combined, plus donations).
/// @dev Warning: Not ERC-3156 compliant but compatibility is easily reached:
/// - `flashFee` is zero.
/// - `maxFlashLoan` is the token's balance of this contract.
/// - The receiver of `assets` is the caller.
/// @param token The token to flash loan.
/// @param assets The amount of assets to flash loan.
/// @param data Arbitrary data to pass to the `onMoolahFlashLoan` callback.
function flashLoan(address token, uint256 assets, bytes calldata data) external;
/// @notice Sets the authorization for `authorized` to manage `msg.sender`'s positions.
/// @param authorized The authorized address.
/// @param newIsAuthorized The new authorization status.
function setAuthorization(address authorized, bool newIsAuthorized) external;
/// @notice Sets the authorization for `authorization.authorized` to manage `authorization.authorizer`'s positions.
/// @dev Warning: Reverts if the signature has already been submitted.
/// @dev The signature is malleable, but it has no impact on the security here.
/// @dev The nonce is passed as argument to be able to revert with a different error message.
/// @param authorization The `Authorization` struct.
/// @param signature The signature.
function setAuthorizationWithSig(Authorization calldata authorization, Signature calldata signature) external;
/// @notice Accrues interest for the given market `marketParams`.
function accrueInterest(MarketParams memory marketParams) external;
/// @notice Add/removes `accounts` from the liquidation whitelist of markets `ids`.
function batchToggleLiquidationWhitelist(Id[] memory ids, address[][] memory accounts, bool isAddition) external;
/// @notice Returns the liquidation whitelist of the market `id`.
function getLiquidationWhitelist(Id id) external view returns (address[] memory);
/// @notice Returns whether `account` is in the liquidation whitelist of the market `id`.
function isLiquidationWhitelist(Id id, address account) external view returns (bool);
/// @notice Set the minimum loan token assets(USD) (supply and borrow).
function setMinLoanValue(uint256 minLoan) external;
/// @notice get the minimum loan token assets (supply and borrow) for the market.
function minLoan(MarketParams memory marketParams) external view returns (uint256);
/// @notice add/remove the provider for the token.
function setProvider(Id id, address provider, bool isAddition) external;
/// @notice get the provider for the market.
function providers(Id id, address token) external view returns (address);
/// @notice get the broker for the market
function brokers(Id id) external view returns (address);
/// @notice Return the whitelist of the market `id`.
function getWhiteList(Id id) external view returns (address[] memory);
/// @notice Returns `true` if `account` is whitelisted of market `id`.
function isWhiteList(Id id, address account) external view returns (bool);
/// @notice Add/Remove `account` from the whitelist of the market `id`.
function setWhiteList(Id id, address account, bool isAddition) external;
/// @notice Returns the default market fee.
function defaultMarketFee() external view returns (uint256);
/// @notice Returns whether `token` is blacklisted for flash loans.
function flashLoanTokenBlacklist(address token) external view returns (bool);
/// @notice Set the default market fee for new markets.
function setDefaultMarketFee(uint256 newFee) external;
/// @notice Sets the flash loan token blacklist status.
function setFlashLoanTokenBlacklist(address token, bool isBlacklisted) external;
/// @notice Returns whether `account` is blacklisted.
function vaultBlacklist(address account) external view returns (bool);
/// @notice Sets the blacklist status of `account`.
function setVaultBlacklist(address account, bool isBlacklisted) external;
/// @notice Set/Remove the market broker for the market `id`.
function setMarketBroker(Id id, address broker, bool isAddition) external;
}
/// @dev This interface is inherited by Moolah so that function signatures are checked by the compiler.
/// @dev Consider using the IMoolah interface instead of this one.
interface IMoolahStaticTyping is IMoolahBase {
/// @notice The state of the position of `user` on the market corresponding to `id`.
/// @dev Warning: For `feeRecipient`, `supplyShares` does not contain the accrued shares since the last interest
/// accrual.
function position(
Id id,
address user
) external view returns (uint256 supplyShares, uint128 borrowShares, uint128 collateral);
/// @notice The state of the market corresponding to `id`.
/// @dev Warning: `totalSupplyAssets` does not contain the accrued interest since the last interest accrual.
/// @dev Warning: `totalBorrowAssets` does not contain the accrued interest since the last interest accrual.
/// @dev Warning: `totalSupplyShares` does not contain the accrued shares by `feeRecipient` since the last interest
/// accrual.
function market(
Id id
)
external
view
returns (
uint128 totalSupplyAssets,
uint128 totalSupplyShares,
uint128 totalBorrowAssets,
uint128 totalBorrowShares,
uint128 lastUpdate,
uint128 fee
);
/// @notice The market params corresponding to `id`.
/// @dev This mapping is not used in Moolah. It is there to enable reducing the cost associated to calldata on layer
/// 2s by creating a wrapper contract with functions that take `id` as input instead of `marketParams`.
function idToMarketParams(
Id id
) external view returns (address loanToken, address collateralToken, address oracle, address irm, uint256 lltv);
/// @notice Returns whether the position of `borrower` in the given market `marketParams` is healthy.
function isHealthy(MarketParams memory marketParams, Id id, address borrower) external view returns (bool);
}
/// @title IMoolah
/// @author Lista DAO
/// @dev Use this interface for Moolah to have access to all the functions with the appropriate function signatures.
interface IMoolah is IMoolahBase {
/// @notice The state of the position of `user` on the market corresponding to `id`.
/// @dev Warning: For `feeRecipient`, `p.supplyShares` does not contain the accrued shares since the last interest
/// accrual.
function position(Id id, address user) external view returns (Position memory p);
/// @notice The state of the market corresponding to `id`.
/// @dev Warning: `m.totalSupplyAssets` does not contain the accrued interest since the last interest accrual.
/// @dev Warning: `m.totalBorrowAssets` does not contain the accrued interest since the last interest accrual.
/// @dev Warning: `m.totalSupplyShares` does not contain the accrued shares by `feeRecipient` since the last
/// interest accrual.
function market(Id id) external view returns (Market memory m);
/// @notice The market params corresponding to `id`.
/// @dev This mapping is not used in Moolah. It is there to enable reducing the cost associated to calldata on layer
/// 2s by creating a wrapper contract with functions that take `id` as input instead of `marketParams`.
function idToMarketParams(Id id) external view returns (MarketParams memory);
function getPrice(MarketParams calldata marketParams) external view returns (uint256);
function _getPrice(MarketParams memory marketParams, address user) external view returns (uint256);
/// @notice grants `role` to `account`.
function grantRole(bytes32 role, address account) external;
}
src/moolah/interfaces/IOracle.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.34;
struct TokenConfig {
/// @notice asset address
address asset;
/// @notice `oracles` stores the oracles based on their role in the following order:
/// [main, pivot, fallback],
/// It can be indexed with the corresponding enum OracleRole value
address[3] oracles;
/// @notice `enableFlagsForOracles` stores the enabled state
/// for each oracle in the same order as `oracles`
bool[3] enableFlagsForOracles;
/// @notice `timeDeltaTolerance` stores the tolerance of
/// the difference between the block timestamp and the price update time
/// the unit is seconds
uint256 timeDeltaTolerance;
}
/// @title IOracle
/// @author Lista Dao
/// @notice Interface that oracles used by Lista Dao must implement.
/// @dev It is the user's responsibility to select markets with safe oracles.
interface IOracle {
function peek(address asset) external view returns (uint256);
function getTokenConfig(address asset) external view returns (TokenConfig memory);
}
src/moolah/libraries/MarketParamsLib.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.34;
import { Id, MarketParams } from "../interfaces/IMoolah.sol";
/// @title MarketParamsLib
/// @author Lista DAO
/// @notice Library to convert a market to its id.
library MarketParamsLib {
/// @notice The length of the data used to compute the id of a market.
/// @dev The length is 5 * 32 because `MarketParams` has 5 variables of 32 bytes each.
uint256 internal constant MARKET_PARAMS_BYTES_LENGTH = 5 * 32;
/// @notice Returns the id of the market `marketParams`.
function id(MarketParams memory marketParams) internal pure returns (Id marketParamsId) {
assembly ("memory-safe") {
marketParamsId := keccak256(marketParams, MARKET_PARAMS_BYTES_LENGTH)
}
}
}
src/provider/interfaces/IV3DexAdapter.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.34;
/**
* @title IV3DexAdapter
* @author Lista DAO
* @notice Seam between the vault (V3Provider) / oracle (SlisBNBV3ProviderOracle) and the DEX custodian
* (V3DexAdapter). The adapter is the SOLE holder of the V3 NFT, the idle inventory and all
* NPM/pool interaction. The vault and oracle never touch NPM/pool directly — they call the
* adapter's `onlyProvider` write functions and read its raw-NAV/composition views (staticcall).
*
* @dev Conventions:
* - Raw NAV: all views return amounts WITHOUT any oracle haircut. The vault uses them for
* share accounting; the oracle applies its own haircut on top for Moolah pricing.
* - Token custody: before `addLiquidity` the provider transfers the input tokens to the adapter;
* the adapter refunds unused tokens to `refundTo` and, on `removeLiquidity`, sends the
* withdrawn underlying directly to `receiver` (avoids a provider→user double hop).
* - "amounts" are token0/token1 raw units; sqrt prices are X96.
*/
interface IV3DexAdapter {
/* ───────────────────── pool / position accessors ────────────── */
function TOKEN0() external view returns (address);
function TOKEN1() external view returns (address);
function DECIMALS0() external view returns (uint8);
function DECIMALS1() external view returns (uint8);
function POOL() external view returns (address);
/// @notice Wrapped-native token of the chain (WBNB on BSC, WETH on Ethereum).
function WRAPPED_NATIVE() external view returns (address);
/// @notice The vault (V3Provider) authorized to drive this adapter.
function provider() external view returns (address);
function tokenId() external view returns (uint256);
function tickLower() external view returns (int24);
function tickUpper() external view returns (int24);
function idleToken0() external view returns (uint256);
function idleToken1() external view returns (uint256);
/* ───────────────── raw-NAV / composition views ──────────────── */
/// @notice token0/token1 represented by the whole position at `sqrtPriceX96`, INCLUDING uncollected
/// fees (tokensOwed) and idle inventory. Raw (no haircut). Single source of truth that both
/// the vault (share accounting) and oracle (Moolah pricing) read.
function positionAmountsAt(uint160 sqrtPriceX96) external view returns (uint256 total0, uint256 total1);
/// @notice token0/token1 for a given `liquidity` at `sqrtPriceX96` (position math only, no fees/idle).
/// Used by the vault's value-based share mint to value freshly added liquidity at the fair price.
function amountsForLiquidity(
uint128 liquidity,
uint160 sqrtPriceX96
) external view returns (uint256 amount0, uint256 amount1);
/// @notice Current liquidity of the managed position (0 if none).
function totalLiquidity() external view returns (uint128);
/// @notice Fair valuation price: exchange-rate-implied for slisBNB/WBNB, pool TWAP otherwise.
function fairSqrtPriceX96() external view returns (uint160);
/// @notice Current pool spot price (slot0).
function spotSqrtPriceX96() external view returns (uint160);
/// @notice Live LST↔native center rate the next rebalance will use (0 for pure-TWAP pairs).
function centerRate() external view returns (uint256);
/// @notice Simulate adding `amount0Desired/amount1Desired` at the current spot price.
function previewAddLiquidity(
uint256 amount0Desired,
uint256 amount1Desired
) external view returns (uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Simulate removing `shares/totalShares` of the position (liquidity + idle) at spot.
/// @dev Upper bound: execution rounds the burn, the pool payout and the idle share separately and can
/// deliver a few wei less. Size minAmount0/1 with a tolerance.
function previewRemoveLiquidity(
uint256 shares,
uint256 totalShares
) external view returns (uint256 amount0, uint256 amount1);
/* ─────────────────────── writes (onlyProvider) ──────────────── */
/// @notice Add liquidity from tokens already transferred to the adapter; mint a fresh NFT if none
/// exists, otherwise increase. Unused input is refunded to `refundTo`.
/// @return liquidityAdded Liquidity units added.
/// @return amount0Used token0 actually consumed by the pool.
/// @return amount1Used token1 actually consumed by the pool.
function addLiquidity(
uint256 amount0Desired,
uint256 amount1Desired,
uint256 amount0Min,
uint256 amount1Min,
address refundTo
) external returns (uint128 liquidityAdded, uint256 amount0Used, uint256 amount1Used);
/// @notice Remove the `shares/totalShares` pro-rata slice of liquidity AND idle inventory, sending
/// the underlying directly to `receiver` (WBNB unwrapped to native BNB). Used by the vault's
/// withdraw / redeemShares. No protocol value floor — the caller's minAmount0/1 is the guard
/// (keeps liquidation live).
function removeLiquidity(
uint256 shares,
uint256 totalShares,
uint256 minAmount0,
uint256 minAmount1,
address receiver
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collect accrued fees and re-add them plus idle inventory as liquidity (compound). BOT-gated
/// at the provider; `amount0Min`/`amount1Min` are the caller-supplied slippage floor.
function collectAndCompound(uint256 amount0Min, uint256 amount1Min) external;
/// @notice Record tokens already transferred to the adapter as idle inventory, without minting into
/// the pool. Used by the vault deposit path so new deposits enter as idle at the current fair
/// composition (off-pool priced); a later spot-gated compound() deploys them.
function creditIdle(uint256 amount0, uint256 amount1) external;
/* ─────────────────────── rebalance / rate config ────────────────── */
/// @notice Exchange rate at the last successful center/init (rate-implied pairs; 0 for TWAP pairs).
function lastCenterRate() external view returns (uint256);
/// @notice Min relative exchange-rate drift before rebalance is allowed (BPS; 0 = off).
function centerRateThresholdBps() external view returns (uint256);
/// @notice Set the rate-drift threshold required for rebalance (onlyRole MANAGER).
function setCenterRateThresholdBps(uint256 centerRateThresholdBps) external;
/// @notice Whether `swapPair` is a whitelisted venue for the rebalance inventory-conversion swap.
function swapPairWhitelist(address swapPair) external view returns (bool);
/// @notice Whitelist (or remove) a swap venue for the rebalance inventory conversion (onlyRole
/// MANAGER). A venue may never be TOKEN0 / TOKEN1 / POOL / POSITION_MANAGER.
function setSwapPairWhitelist(address swapPair, bool status) external;
/// @notice Per-swap rate-anchored loss cap for the rebalance conversion swap (ppm, 1e6 = 100%).
function maxSwapLossBp() external view returns (uint256);
/// @notice Set the per-swap rate-anchored loss cap (onlyRole MANAGER; ppm, 1e6 = 100%).
function setMaxSwapLossBp(uint256 maxSwapLossBp) external;
/// @notice Max |pool spot − fair| price deviation (bps) tolerated when adding liquidity at pool spot.
function maxSpotDeviationBps() external view returns (uint256);
/// @notice Set the spot-vs-fair deviation gate (onlyRole MANAGER; bps of price, 0 disables).
function setMaxSpotDeviationBps(uint256 maxSpotDeviationBps) external;
/// @notice Min blocks between liquidity-adding compounds; inside the window every compound attempt
/// (compound() or the rebalance no-op path) reverts CompoundCooldown. Armed only on an add.
function cooldownBlocks() external view returns (uint256);
/// @notice Block of the last compound that actually added liquidity.
function lastCompoundBlock() external view returns (uint256);
/// @notice Set the compound cooldown (onlyRole MANAGER; blocks, 0 disables).
function setCooldownBlocks(uint256 cooldownBlocks) external;
/// @notice Max |live center rate − BOT-supplied expectedCenterRate| deviation (bps) tolerated on
/// rebalance (0 disables the guard).
function maxCenterRateDeviationBps() external view returns (uint256);
function rangeLowerBps() external view returns (uint256);
function rangeUpperBps() external view returns (uint256);
function setRangeBps(uint256 rangeLowerBps, uint256 rangeUpperBps) external;
/// @notice Set the center-rate deviation gate (onlyRole MANAGER; bps, 0 disables).
function setMaxCenterRateDeviationBps(uint256 maxCenterRateDeviationBps) external;
/// @notice Recenter the position and convert inventory to the optimal ratio. onlyProvider (the provider
/// gates on BOT). `expectedCenterRate` = the live rate the BOT built against (0 = skip); reverts
/// if it deviates from the on-chain rate by more than `maxCenterRateDeviationBps`.
/// `noOp` = compound-only: compound into the existing range (minAmount0/1 as floors), revert
/// RangeMoved if the range moved, InvalidParam if swapData / target / minLiquidity is set. The
/// rate-drift / expectedCenterRate guards still apply; a plain keeper compound is compound().
function rebalance(
uint256 minAmount0,
uint256 minAmount1,
uint256 minLiquidity,
uint160 targetSqrtPriceX96,
uint256 expectedCenterRate,
uint256 deadline,
bytes calldata swapData,
bool noOp
) external;
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 20,
"enabled": true
},
"evmVersion": "osaka",
"remappings": [
"@src/=src/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"moolah/=src/moolah/",
"moolah-vault/=src/moolah-vault/",
"liquidator/=src/liquidator/",
"interest-rate-model/=src/interest-rate-model/",
"vault-allocator/=src/vault-allocator/",
"@solady/=lib/solady/src/",
"forge-std/=lib/forge-std/src/",
"timelock/=src/timelock/",
"revenue/=src/revenue/",
"murky/=lib/murky/",
"lista-dao-contracts.git/=lib/lista-dao-contracts.git/contracts/",
"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol=lib/lista-dao-contracts.git/node_modules/@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol",
"@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol=lib/lista-dao-contracts.git/node_modules/@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol",
"@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol=lib/lista-dao-contracts.git/node_modules/@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol",
"lib/lista-dao-contracts.git/:@openzeppelin/contracts-upgradeable/=lib/lista-dao-contracts.git/node_modules/@openzeppelin/contracts-upgradeable/",
"lista-v3/=lib/lista-v3/src/",
"lista-dao-contracts/=lib/lista-dao-contracts.git/contracts/",
"@chainlink/=lib/lista-dao-contracts.git/node_modules/@chainlink/",
"@ensdomains/=lib/lista-v3/lib/solidity-lib/node_modules/@ensdomains/",
"@pythnetwork/=lib/lista-dao-contracts.git/node_modules/@pythnetwork/",
"@solidity-parser/=lib/lista-v3/lib/solidity-lib/node_modules/",
"@uniswap/=lib/lista-v3/node_modules/@uniswap/",
"base64-sol/=lib/lista-v3/node_modules/base64-sol/",
"ds-test/=lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"eth-gas-reporter/=lib/lista-dao-contracts.git/node_modules/eth-gas-reporter/",
"halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"hardhat/=lib/lista-dao-contracts.git/node_modules/hardhat/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/murky/lib/openzeppelin-contracts/",
"openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/",
"prettier-plugin-solidity/=lib/lista-v3/lib/solidity-lib/node_modules/prettier-plugin-solidity/",
"solady/=lib/solady/src/",
"solidity-lib/=lib/lista-v3/lib/solidity-lib/contracts/",
"solidity-stringutils/=lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.