bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 53쪽 중 25쪽
p` is emitted directly by the vault, with no preceding `SubmitCap`.
`SetCurator` and `SetIsAllocator` are declared in the same library and likewise never emitted. The vault uses OpenZeppelin `AccessControl`, so role changes surface as `RoleGranted` / `RoleRevoked` filtered on the `CURATOR` / `ALLOCATOR` role hashes.
To reconstruct how a vault allocates deposits across underlying Moolah markets, track `SetSupplyQueue`/`SetWithdrawQueue` for ordering, `SetCap` for per-market limits, and `ReallocateSupply`/`ReallocateWithdraw` for actual moves.
### Vault allocator events (`VaultAllocator`)
The public reallocation helper (`src/vault-allocator/VaultAllocator.sol`) declares its events in `vault-allocator/libraries/EventsLib.sol`.
A public reallocation emits one `PublicWithdrawal` per market it pulls from and a `PublicReallocateTo` for the market it supplies into, all correlated by the indexed `vault`.
***
## See also
* [Smart Contract](/for-developer/lista-lending/smart-contract) — deployed contract addresses.
# Interest Rate Model (IRM)
Moolah markets delegate borrow-rate computation to a pluggable Interest Rate Model (IRM). Each market stores an `irm` address, and on every interest accrual Moolah calls that contract to obtain the current borrow rate.
Two IRM implementations ship with the protocol:
| IRM | Model | Where used |
| ------------------- | --------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `InterestRateModel` | Adaptive-curve rate as a function of utilization, with a rate-at-target that adapts over time | Standard utilization-based markets |
| `FixedRateIrm` | Administratively set fixed per-market rate | Fixed term / fixed rate broker products (see [Integration Patterns](/for-developer/lista-lending/integration-patterns)) |
Every IRM implements the shared `IIrm` interface:
```solidity
interface IIrm {
/// @notice Borrow rate per second (scaled by WAD); may modify storage.
function borrowRate(MarketParams memory marketParams, Market memory market) external returns (uint256);
/// @notice Borrow rate per second (scaled by WAD); read-only.
function borrowRateView(MarketParams memory marketParams, Market memory market) external view returns (uint256);
}
```
All rates in the IRM are expressed **per second, scaled by WAD (`1e18`)**. Moolah compounds this per-second rate over the elapsed time between interactions when accruing interest.
## Adaptive Curve Model
`InterestRateModel` computes the borrow rate as a curve function of utilization around a target utilization. The curve is anchored by a `rateAtTarget` value that itself adapts over time: when utilization sits above target, `rateAtTarget` drifts upward; when below target, it drifts downward. This pushes the market back toward the target utilization without governance intervention.
### Utilization and error
Utilization is total borrows divided by total supply:
```
utilization = totalBorrowAssets / totalSupplyAssets (WAD-scaled, 0 if no supply)
```
The model measures how far utilization is from target as a normalized error `err`, mapped so that `err = -1` at zero utilization, `err = 0` at target utilization, and `err = +1` at full (100%) utilization:
```
errNormFactor = utilization > TARGET_UTILIZATION ? (WAD - TARGET_UTILIZATION) : TARGET_UTILIZATION
err = (utilization - TARGET_UTILIZATION) / errNormFactor
```
### The curve
Given the current `rateAtTarget` and the error, the instantaneous rate is a piecewise-linear curve. Below target the rate is scaled down toward `rateAtTarget / CURVE_STEEPNESS`; above target it is scaled up toward `rateAtTarget * CURVE_STEEPNESS`:
```
r = ((1 - 1/C) * err + 1) * rateAtTarget if err < 0
((C - 1) * err + 1) * rateAtTarget if err >= 0
```
where `C = CURVE_STEEPNESS`. At `err = 0` (utilization exactly at target) the borrow rate equals `rateAtTarget`.
### Adaptation of `rateAtTarget`
`rateAtTarget` is stored per market (`mapping(Id => int256) rateAtTarget`) and is updated only on stateful interactions. Between two updates it moves according to `ADJUSTMENT_SPEED * err` per second, applied through a continuous-compounding (exponential) adaptation over the elapsed time:
```
linearAdaptation = (ADJUSTMENT_SPEED * err) * elapsed
endRateAtTarget = clamp(startRateAtTarget * exp(linearAdaptation), MIN_RATE_AT_TARGET, MAX_RATE_AT_TARGET)
# then bounded again by the market's own cap / floor before being stored:
endRateAtTarget = clamp(endRateAtTarget, rateFloor * 4, cap / 4)
```
The second clamp is applied to the value that is actually persisted, so after a `rateCap` or `rateFloor` change the stored `rateAtTarget` is bounded to `[rateFloor * 4, cap / 4]` — not only to the protocol-wide `MIN_RATE_AT_TARGET` / `MAX_RATE_AT_TARGET`. The factor of 4 is `CURVE_STEEPNESS`, so the bound expresses the cap/floor in terms of the curve endpoints. If `rateFloor * 4` exceeds `cap / 4`, the cap side wins.
The average rate returned to Moolah over the elapsed interval is approximated with a trapezoidal rule (using the start, mid, and end `rateAtTarget`), so the reported rate reflects the whole interval rather than only its endpoints. On a market's first interaction (`rateAtTarget == 0`), the model seeds both the average and end rate-at-target with `INITIAL_RATE_AT_TARGET`.
The resulting average rate is additionally bounded by a per-market cap and floor (`rateCap`, `rateFloor`) and a protocol-wide minimum cap (`minCap`); when no explicit cap is set, `DEFAULT_RATE_CAP` applies. These bounds are manager/bot-adjustable on-chain values.
Changing either bound settles first: `updateRateCap` and `updateRateFloor` (on both IRMs, and `setBorrowRate` on `FixedRateIrm`) call `Moolah.accrueInterest` for the market before writing the new value, so interest accrued under the old bound is booked at the old bound. The call is a no-op for a market that has never been touched (`lastUpdate == 0`).
## Adaptive-curve constants
These are compiled into `ConstantsLib` and inlined, so there is no getter to read them from — changing one requires a contract upgrade. All rate constants are **per second, WAD-scaled**; the percentages in *Meaning* are those same values expressed per year.
| Constant | On-chain value | Meaning |
| ------------------------ | ------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| `CURVE_STEEPNESS` | `4 ether` (`4e18`) | Curve steepness `C = 4`. Rate ranges from `rateAtTarget / 4` at 0% utilization to `rateAtTarget * 4` at 100%. |
| `TARGET_UTILIZATION` | `0.9 ether` (`0.9e18`) | Target utilization = 90%. |
| `ADJUSTMENT_SPEED` | `50 ether / 365 days` | Adaptation speed; `rateAtTarget` moves at `ADJUSTMENT_SPEED * err` per second (≈ 50 / year at full error). |
| `INITIAL_RATE_AT_TARGET` | `0.04 ether / 365 days` | Seed rate-at-target on first interaction; 4% APR-equivalent at target (rate spans \~1%–16% across the curve). |
| `MIN_RATE_AT_TARGET` | `0.001 ether / 365 days` | Lower clamp on `rateAtTarget`; 0.1% at target (curve minimum \~0.025%). |
| `MAX_RATE_AT_TARGET` | `2.0 ether / 365 days` | Upper clamp on `rateAtTarget`; 200% at target (curve maximum \~800%). |
| `DEFAULT_RATE_CAP` | `uint256(0.3 ether) / 365 days` | Default per-second cap on the returned borrow rate (30% annualized) when a market has no explicit `rateCap`. |
## `borrowRateView` vs `borrowRate`
Both entry points evaluate the same adaptive-curve math, but differ in whether they persist the updated `rateAtTarget`:
| | `borrowRateView` | `borrowRate` |
| ---------- | --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| Mutability | `view` (no state change) | State-changing |
| Caller | Anyone | `MOOLAH` only (reverts otherwise) |
| Effect | Computes the average rate for the current `market` snapshot without writing | Computes the rate, writes `rateAtTarget[id] = endRateAtTarget`, emits `BorrowRateUpdate` |
| Use case | Off-chain quoting, simulations, front-ends | Called by Moolah during interest accrual on `supply` / `borrow` / `repay` / etc. |
Because `borrowRate` requires `msg.sender == MOOLAH`, integrators reading a rate directly should call `borrowRateView`. The value it returns is the average per-second rate that *would* be applied for the given `market` snapshot; it does not advance `rateAtTarget`. `borrowRateView` uses the stored `rateAtTarget` and the elapsed time implied by `market.lastUpdate`, so its result already reflects adaptation that has not been committed on-chain.
## Reading the current rate on-chain
Two complementary reads are available:
1. **The anchor rate.** `rateAtTarget(Id id)` returns the stored per-second rate-at-target for a market (the height of the curve). It is seeded to `INITIAL_RATE_AT_TARGET`, clamped by the market's floor and cap, in the **market-creation transaction** — `createMarket` calls `IIrm.borrowRate` once to initialize the model. A `0` reading therefore means this IRM has never been invoked for that `Id`: the market does not exist, or it uses a different IRM.
```solidity
int256 anchor = IInterestRateModel(irm).rateAtTarget(id);
```
2. **The current borrow rate.** Fetch the market's live `MarketParams` and `Market` structs from Moolah, then call `borrowRateView`:
```solidity
uint256 ratePerSecond = IIrm(irm).borrowRateView(marketParams, market); // WAD-scaled
```
### Per-second → APY conversion
The returned rate is a per-second rate scaled by WAD. Moolah accrues interest with continuous (per-second Taylor-compounded) growth, so the borrow APY is:
```typescript
const SECONDS_PER_YEAR = 365 * 24 * 60 * 60; // 31_536_000
// ratePerSecond is the WAD-scaled uint returned by borrowRateView
const rateFloat = Number(ratePerSecond) / 1e18;
const borrowAPY = Math.expm1(rateFloat * SECONDS_PER_YEAR); // e.g. 0.05 == 5%
```
The supply APY is lower than the borrow APY, scaled by utilization and net of the market fee; it is not returned by the IRM and must be derived from market state.
## FixedRateIrm
For products that do not use the utilization-based curve, brokers can point a market at `FixedRateIrm`. Instead of computing a rate from utilization, it returns a per-market rate that has been set administratively.
| Element | Signature / value | Notes |
| -------------------------------------------- | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `MAX_BORROW_RATE` | `8.0 ether / 365 days` | Maximum settable per-second rate (800% annualized). |
| `borrowRateStored(Id id)` | `int256` | The fixed per-second rate stored for a market. |
| `setBorrowRate(Id id, int256 newBorrowRate)` | — | Sets the fixed rate. Access-controlled (bot role); must be `>= 0` and `<= MAX_BORROW_RATE`, and within any configured `rateCap` / `rateFloor`. Interest accrued under the previous rate is settled first (see below). |
| `borrowRateView(...)` / `borrowRate(...)` | `uint256` | Both return the stored rate (clamped to `MAX_BORROW_RATE`, then to the market cap and floor). Unlike the adaptive model, `borrowRate` here is also `view` and holds no adaptive state. A market whose rate has never been set has `borrowRateStored == 0`, so these return `0` (subject to any configured floor) rather than reverting. |
A `0` rate means no interest accrues, so treat an unset market as unconfigured rather than free. This IRM backs the fixed term / fixed rate broker products described in [Integration Patterns](/for-developer/lista-lending/integration-patterns).
## Related
* [Contract & Interface Reference](/for-developer/lista-lending/contract-reference) — `minLoan`, the global reentrancy guard and the rest of the Lista-specific controls.
* [Smart Contract](/for-developer/lista-lending/smart-contract) — deployed contract addresses.
# Smart Lending & StableSwap
Smart Lending lets a user deposit a **Lista StableSwap LP position as collateral** into Moolah, borrow against it, and keep earning trading fees on the underlying pool at the same time. The LP tokens never leave the system idle: they are held by a `SmartProvider`, wrapped 1:1 into a collateral token, and supplied to a Moolah market, while the pool they represent continues to accrue swap fees.
> The collateral token is **not a freely transferable ERC-20**. `mint` and `burn` are restricted to the minter, and `transfer` / `transferFrom` are restricted to Moolah and addresses holding the `TRANSFERER` role. Do not build a flow that moves it between arbitrary accounts — route position changes through the provider.
Route swaps through Lista StableSwap, or use an LP position as Moolah collateral:
* discover Lista StableSwap pools and route/quote swaps against them, and
* move StableSwap LP into a Moolah Smart Lending market via `SmartProvider`.
For deployed addresses, see [BSC Smart Lending](/for-developer/lista-lending/smart-contract/smart-contract-bsc-smart-lending) (do not hard-code addresses from this page — the address tables are the source of truth). For how providers fit into Moolah, see [Integration Patterns](/for-developer/lista-lending/integration-patterns).
Lista StableSwap is a two-coin Curve-style stable pool: every pool has exactly two coins (`N_COINS = 2`), indexed `0` and `1` in sorted-address order.
***
## Factory: pool discovery
`StableSwapFactory` is the registry of all deployed pools. Use it to enumerate pools and resolve a token pair to its pool and LP token.
| Read | Signature | Returns |
| ---------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
| Pool count | `pairLength() → uint256` | Number of registered pools. |
| Pool by index | `swapPairContract(uint256 index) → address` | The pool (swap) contract at `index`, for `index` in `[0, pairLength)`. |
| Pools for a pair | `getPairInfos(address tokenA, address tokenB) → StableSwapPairInfo[]` | All pools registered for the pair (order-independent — inputs are sorted internally). |
| Sort helper | `sortTokens(address tokenA, address tokenB) → (address token0, address token1)` | Canonical `(token0, token1)` ordering; reverts `IDENTICAL_ADDRESSES` if equal. |
`StableSwapPairInfo` is:
```solidity
struct StableSwapPairInfo {
address swapContract; // the StableSwap pool
address token0; // sorted coin 0
address token1; // sorted coin 1
address LPContract; // the StableSwapLP (ERC-20) minted by the pool
}
```
Coins are always stored in sorted order (`token0 < token1`). A single token pair can have more than one pool (for example a standard and a narrow-spread pool), which is why `getPairInfos` returns an array.
To keep an up-to-date pool list, index the factory's `NewStableSwapPair` event, or walk `swapPairContract(i)` over `[0, pairLength)`.
***
## Pool reads
Read pool state directly from the `StableSwapPool` (the `swapContract` address).
| Read | Signature | Notes |
| --------------------- | ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------- |
| Coin address | `coins(uint256 i) → address` | `i ∈ {0, 1}`. For a native-BNB pool the BNB side returns the sentinel `0xEeee…eEeE` (see [Native BNB](#native-bnb-handling)). |
| Pool balance | `balances(uint256 i) → uint256` | Pool-tracked balance of coin `i`, in that coin's own decimals. |
| LP token | `token() → address` | The `StableSwapLP` ERC-20 for this pool. |
| Amplification | `A() → uint256` | Current amplification coefficient (already de-scaled). |
| Swap fee | `fee() → uint256` | Fee numerator over `FEE_DENOMINATOR = 1e10`. |
| Admin fee | `admin_fee() → uint256` | Share of `fee` taken as protocol fee, over `1e10`. |
| Native support | `support_BNB() → bool` | `true` if one coin is native BNB. |
| Virtual price | `get_virtual_price() → uint256` | Invariant value per LP token, `1e18`-scaled. Reverts on reentrancy. |
| Precision multipliers | `PRECISION_MUL(uint256 i) → uint256` | `10 ** (18 - decimals_i)`; scales coin `i` to 18-decimal internal units. |
`StableSwapPoolInfo` is a stateless helper that reads a pool for you and adds convenience views:
| Helper | Signature | Returns |
| -------------- | ---------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Balances | `balances(address pool) → uint256[2]` | Both pool balances. |
| LP → coins | `calc_coins_amount(address pool, uint256 lpAmount) → uint256[2]` | Coin amounts a proportional withdrawal of `lpAmount` LP would yield. |
| Holder → coins | `get_coins_amount_of(address pool, address account) → uint256[2]` | Same, for an account's full LP balance. |
| Mint preview | `get_add_liquidity_mint_amount(address pool, uint256[2] amounts) → uint256` | LP that `add_liquidity(amounts)` would mint (net of deposit fee). |
| Reverse quote | `get_dx(address pool, uint256 i, uint256 j, uint256 dy, uint256 max_dx) → uint256` | Input of coin `i` required to receive `dy` of coin `j`, **grossed up** to cover the fee. Reverts `Excess balance` / `Exchange resulted in fewer coins than expected`. |
***
## Quoting a swap: `get_dy`
`get_dy` returns the output amount **net of the fee** — what you actually receive — in the output coin's own decimals:
```solidity
function get_dy(uint256 i, uint256 j, uint256 dx) external view returns (uint256);
```
* `i` — input coin index, `j` — output coin index (`{0,1}`, `i != j`).
* `dx` — input amount, in coin `i`'s decimals.
* Returns the amount of coin `j` out **after** the pool's swap fee.
Convention: token0 → token1 is `i = 0, j = 1`; token1 → token0 is `i = 1, j = 0`.
```solidity
// USDT (coin 0) in, USDC (coin 1) out.
// USDT 0x55d3... sorts below USDC 0x8AC7..., so USDT is coin 0 —
// read coins(0) / coins(1) rather than assuming an order.
uint256 amountOut = pool.get_dy(0, 1, dxUSDT);
```
`get_dy_without_fee(i, j, dx)` returns the pre-fee output if you need to isolate the fee component. The executed swap is:
```solidity
function exchange(uint256 i, uint256 j, uint256 dx, uint256 min_dy) external payable;
```
`min_dy` is your slippage floor; the swap reverts `Exchange resulted in fewer coins than expected` if the realized output is below it. Quote with `get_dy` immediately before execution and derive `min_dy` from it with your slippage tolerance.
***
## Oracle price-difference guard
Each pool holds a resilient-oracle reference and **can** enforce a price-difference guard on state-changing operations — but whether it does is per-pool and manager-controlled. Read `skipPriceDiff()` on the specific pool rather than assuming the guard protects you — `true` means the guard is **off**.
Where it is enabled, `exchange`, `add_liquidity`, and every `remove_liquidity*` variant call `checkPriceDiff()`, which reverts when the pool's implied price for either coin diverges from the oracle price beyond a per-coin threshold:
* `Price difference for token0 exceeds threshold`
* `Price difference for token1 exceeds threshold`
Relevant reads:
| Read | Signature | Notes |
| ------------- | ---------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------프로젝트로 돌아가기