Lista DAO 백서

Lista DAO

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 53쪽 중 24쪽

d` applies; for the reentrancy model see [Reentrancy guard](#reentrancy-guard). ### Authorization ```solidity function setAuthorization(address authorized, bool newIsAuthorized) external; function setAuthorizationWithSig(Authorization calldata authorization, Signature calldata signature) external; ``` `setAuthorization` sets whether `authorized` may manage `msg.sender`'s positions across all markets. `setAuthorizationWithSig` does the same via an EIP-712 signature, consuming the authorizer's `nonce` and requiring `block.timestamp <= deadline`. Anyone may always manage their own positions regardless of these flags. ### Interest accrual ```solidity function accrueInterest(MarketParams memory marketParams) external; ``` Permissionlessly accrues interest for a market: queries `borrowRate` from the IRM, compounds it over the elapsed time (three-term Taylor approximation of continuous compounding), grows `totalBorrowAssets`/`totalSupplyAssets`, and mints fee shares to `feeRecipient` when the market `fee` is non-zero. Emits `AccrueInterest`. The interest-bearing entry points — `supply`, `withdraw`, `borrow`, `repay`, `withdrawCollateral`, `liquidate`, and `liquidateBrokerPosition` — accrue interest internally before touching balances. `supplyCollateral` deliberately skips accrual (collateral neither earns nor owes interest, so it saves gas), and `flashLoan` does not accrue. *** ## View functions | View | Signature | Returns | | ---------------- | ------------------------------------------------------ | -------------------------------------------------------------------------------------------- | | Position | `position(Id id, address user)` | The `Position` struct for a user in a market. | | Market | `market(Id id)` | The `Market` accounting struct. | | Params by id | `idToMarketParams(Id id)` | The `MarketParams` for a market (reverse of the `Id` hash). | | Authorization | `isAuthorized(address authorizer, address authorized)` | Whether `authorized` may manage `authorizer`'s positions. | | Nonce | `nonce(address authorizer)` | The authorizer's current EIP-712 nonce. | | Domain separator | `domainSeparator()` | The EIP-712 domain separator for the current chain. | | Health | `isHealthy(MarketParams, Id, address borrower)` | Whether a borrower's position is healthy. | | Price | `getPrice(MarketParams)` | Collateral price in loan-asset terms, scaled by `10 ** (36 + quoteDecimals - baseDecimals)`. | | IRM enabled | `isIrmEnabled(address irm)` | Whether an IRM may be used for new markets. | | LLTV enabled | `isLltvEnabled(uint256 lltv)` | Whether an LLTV may be used for new markets. | | Fee recipient | `feeRecipient()` | The global fee recipient. | | Default fee | `defaultMarketFee()` | Fee applied to newly created markets. | **Computing a market `Id`** off-chain is `keccak256(abi.encode(loanToken, collateralToken, oracle, irm, lltv))`; on-chain the equivalent is `MarketParamsLib.id(marketParams)`. The reverse (`Id` → params) is `idToMarketParams`. ### Relevant constants These are compile-time constants of the interface, not adjustable parameters — no governance call changes them. | Constant | Value | Role | | ---------------------------------- | --------------- | ----------------------------------------------------- | | `WAD` | `1e18` | Fixed-point scale for rates, fees, and `lltv`. | | `ORACLE_PRICE_SCALE` | `1e36` | Internal price scale used in health/liquidation math. | | `MAX_FEE` | `0.25e18` (25%) | Upper bound on any market fee. | | `LIQUIDATION_CURSOR` | `0.3e18` | Input to the liquidation incentive formula. | | `MAX_LIQUIDATION_INCENTIVE_FACTOR` | `1.15e18` | Cap on the liquidation incentive factor. | *** ## Lista-specific extensions These controls are additions on top of the Morpho Blue base and are what distinguishes Moolah from a vanilla deployment. ### Minimum loan floor (`minLoanValue` / `minLoan`) ```solidity function minLoan(MarketParams memory marketParams) external view returns (uint256); function minLoanValue() external view returns (uint256); ``` `minLoanValue` is a protocol-wide floor denominated in the oracle's 8-decimal USD unit. `minLoan(marketParams)` converts it into the market's loan-token amount using the oracle price and token decimals. Supply, borrow, and repay all enforce that a **non-zero** resulting position stays at or above this floor, which prevents dust positions that are uneconomical to liquidate. The value is a current, manager-adjustable on-chain value (`setMinLoanValue`, `MANAGER` role), not a fixed promise. ### Liquidation whitelist ```solidity function getLiquidationWhitelist(Id id) external view returns (address[] memory); function isLiquidationWhitelist(Id id, address account) external view returns (bool); ``` Per-market allowlist of eligible liquidators. When a market's list is **empty, liquidation is open to anyone**; once any address is added, only listed addresses may call `liquidate` for that market. Third-party liquidators should not call `liquidate` on this contract directly — go through `PublicLiquidator`. Reaching a market gated here needs **both** sides to line up: the `BOT` must have opened the market or borrower on `PublicLiquidator`, *and* `PublicLiquidator` itself must be on this market's `liquidationWhitelist`. See [Liquidator Integration](/for-developer/lista-lending/liquidator-integration). ### Supply/borrow whitelist ```solidity function getWhiteList(Id id) external view returns (address[] memory); function isWhiteList(Id id, address account) external view returns (bool); ``` Optional per-market gate on `supply`, `supplyCollateral`, and `borrow` (checked against `onBehalf`). An **empty list means the market is open**; a non-empty list restricts these actions to listed accounts. ### Vault & flash-loan blacklists ```solidity function vaultBlacklist(address account) external view returns (bool); function flashLoanTokenBlacklist(address token) external view returns (bool); ``` `vaultBlacklist` blocks a blacklisted `onBehalf` from receiving new supply. `flashLoanTokenBlacklist` disables `flashLoan` for a specific token. ### Providers & brokers routing ```solidity function providers(Id id, address token) external view returns (address); function brokers(Id id) external view returns (address); ``` A **provider** is registered per market and token, and its effect depends on which token it backs. A **collateral-token** provider is an exclusive gate: when set, only the provider may call `supplyCollateral`/`withdrawCollateral` (and on withdraw the `receiver` must be the provider). A **loan-token** provider is *not* an exclusive gate — it only constrains the borrow receiver: if the loan-token provider is the `borrow` caller, `receiver` must be the provider; ordinary authorized borrowers are unaffected, and plain `supply`/`withdraw` of the loan asset are never provider-gated. A **broker** is registered per market and, when present, gates borrow and repay origination — only the broker may `borrow` or `repay`. For a broker market, `_isHealthy` still prices collateral with the **plain market price** (`_getPrice` with `user = address(0)`) but replaces the borrower's debt with the broker's total debt (Moolah principal + interest accrued at the broker); `liquidateBrokerPosition` is a separate broker-only bad-debt write-down that performs **no** health check (health responsibility sits with the broker). `setMarketBroker` validates that the broker's `LOAN_TOKEN`, `COLLATERAL_TOKEN`, and `MARKET_ID` match the market. See [Integration Patterns](/for-developer/lista-lending/integration-patterns) for how these layers compose. ### Resilient oracle routing Markets read prices through the `oracle` in `MarketParams`, which exposes `peek(address asset)`. Each market names its own oracle, so which contract answers — a **Resilient Oracle** aggregating a main / pivot / fallback source per asset, or an asset-specific adaptor — is per-market configuration; read `marketParams.oracle` and check it against the [Standard Collaterals](/for-developer/multi-oracle/multi-oracle-standard) / [bStock Collaterals](/for-developer/multi-oracle/multi-oracle-bstock) tables. When a broker is present and a user address is supplied, price resolution routes through the broker so the effective price reflects the user's fixed-term/fixed-rate position; health checks otherwise use the plain oracle price. Oracle selection is a per-market safety responsibility. See [Consuming Oracle Prices](/for-developer/multi-oracle/consuming-prices). ### Reentrancy guard The core mutating entry points — `supply`, `withdraw`, `borrow`, `repay`, `supplyCollateral`, `withdrawCollateral`, `liquidate`, and `liquidateBrokerPosition` — are `nonReentrant`. `flashLoan` is intentionally **not** `nonReentrant` (its safety comes from the same-transaction repayment invariant). All of the above are additionally `whenNotPaused`. ### Pausing, and what it means for you Pause is the privileged control that can halt every `whenNotPaused` entry point: a `PAUSER` can stop supply, withdraw, borrow, repay, collateral movement, liquidation and `flashLoan`. Views are unaffected. Handle its revert. It is not the only state that can change under you, though — `providers`, `brokers`, and `minLoanValue` are separate mappings/variables, not part of `MarketParams` or `Market`, so a `market()` or `idToMarketParams()` read does not tell you whether they changed either; re-read them, or watch [Events & Callbacks](/for-developer/lista-lending/events-and-callbacks), rather than assuming a cached read still holds. `createMarket` is additionally gated whenever any `OPERATOR` exists. Everything else — enabling IRMs and LLTVs, setting fees, whitelists, providers, brokers, `minLoanValue`, and contract upgrades — is role-gated, so a third party cannot call any of it. Upgrade authority sits behind an OpenZeppelin `TimelockController` — read `getMinDelay()` on it for the delay in force. # Events & Callbacks Moolah hands control back to you in two ways: * **Callbacks** — synchronous, in-transaction hooks that Moolah invokes on the caller mid-execution (before it pulls the tokens it is owed), enabling atomic flows such as leverage loops, flash-liquidations, and position migrations. * **Events** — the logs Moolah, the IRM, and the vault layer emit for off-chain indexers, subgraphs, and monitoring. For function signatures, structs, and the `Id`/`MarketParams` types referenced below, see the [Contract & Interface Reference](/for-developer/lista-lending/contract-reference). For the higher-level provider/broker model, see [Integration Patterns](/for-developer/lista-lending/integration-patterns). *** ## Callbacks Moolah follows the Morpho-style callback pattern: several core entry points optionally call back into `msg.sender` after updating internal accounting but **before** transferring in the assets the caller owes. This lets an integrator source those assets inside the same transaction — for example, minting/swapping collateral, or repaying a loan out of seized collateral — so the whole operation is atomic and reverts as a unit if any leg fails. ### Firing rule Each entry point takes a trailing `bytes data` argument. For **supply**, **repay**, **supplyCollateral**, and **liquidate**, the callback fires **only when `data` is non-empty** (`data.length > 0`); pass empty `data` to skip it. **`flashLoan` is the exception**: its callback is always invoked, because the flash loan has no purpose without it. The callback is always made on `msg.sender`, so the contract that calls Moolah must be the contract that implements the interface. ### Callback interfaces All five interfaces are declared in `moolah/interfaces/IMoolahCallbacks.sol`. | Interface | Method | Fired by | Fires when | | --------------------------------- | ------------------------------------------------------ | ------------------ | ---------------- | | `IMoolahSupplyCallback` | `onMoolahSupply(uint256 assets, bytes data)` | `supply` | `data` non-empty | | `IMoolahRepayCallback` | `onMoolahRepay(uint256 assets, bytes data)` | `repay` | `data` non-empty | | `IMoolahSupplyCollateralCallback` | `onMoolahSupplyCollateral(uint256 assets, bytes data)` | `supplyCollateral` | `data` non-empty | | `IMoolahLiquidateCallback` | `onMoolahLiquidate(uint256 repaidAssets, bytes data)` | `liquidate` | `data` non-empty | | `IMoolahFlashLoanCallback` | `onMoolahFlashLoan(uint256 assets, bytes data)` | `flashLoan` | always | The first argument is the settled amount for that action: assets supplied/repaid/supplied-as-collateral, `repaidAssets` for a liquidation, or the flash-loaned amount. The `data` argument is the same opaque payload you passed into the originating call, so you can encode a route, a target market, or step parameters and decode them inside the callback. ### Execution order (the atomic window) Within the originating call, Moolah: 1. Updates its own accounting. 2. Emits the corresponding event (`Supply`, `Repay`, `SupplyCollateral`, `Liquidate`, `FlashLoan`). 3. For the actions where Moolah owes **you** assets, transfers them out now — the seized collateral for `liquidate`, the loaned token for `flashLoan`. (`supply`, `repay`, and `supplyCollateral` have no outbound transfer; you are the one paying in.) 4. Calls back into `msg.sender` (subject to the firing rule above), handing you control while the position is mid-update. 5. On return, pulls in the assets **you** owe via `transferFrom` (the supplied/repaid/collateral token, or the flash-loaned amount plus zero fee). If your balance or allowance is short, the whole transaction reverts. Your callback body runs in step 4, so it must leave `msg.sender` holding enough of the inbound token (and allowance to Moolah) for step 5 to succeed. ### Typical atomic flows > **Read this before designing a flow.** Moolah inherits a **single global** reentrancy guard, and eight entry points carry it — `supply`, `withdraw`, `borrow`, `repay`, `supplyCollateral`, `withdrawCollateral`, `liquidate` and `liquidateBrokerPosition`. `flashLoan` is the **only** callback entry point without it. So from inside `onMoolahSupply`, `onMoolahRepay`, `onMoolahSupplyCollateral` or `onMoolahLiquidate` you **cannot re-enter any of those eight** — they revert `ReentrancyGuardReentrantCall()`. Views, `accrueInterest` and `flashLoan` carry no guard and remain callable, but no position-mutating composition is possible. Multi-step Moolah composition is possible only from `onMoolahFlashLoan`. This is a deliberate divergence from upstream Morpho Blue, where the equivalent flows do work, so do not carry a Morpho design over unchanged. | Flow | Callback used | Sketch | | ----------------------------- | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Leverage loop** | `onMoolahFlashLoan` | Flash-loan the loan token; in the callback swap it to collateral, `supplyCollateral`, then `borrow` enough to repay the flash loan. Must be built on `flashLoan` — the `supplyCollateral` callback cannot borrow. | | **Flash-liquidation** | `onMoolahLiquidate` | Call `liquidate` with `data`; Moolah sends you the seized collateral first, then calls back. Swap that collateral on an **external** venue to raise the repayment. No Moolah call is needed inside the callback, which is why this one works. | | **Debt / position migration** | `onMoolahFlashLoan` | Flash-loan the loan token, use it to repay a position elsewhere, withdraw the freed collateral, move it, and re-borrow to repay the flash loan. | | **Zero-capital deleverage** | `onMoolahFlashLoan` | Flash-loan the loan token, `repay` with it, `withdrawCollateral`, swap part of the collateral back to the loan token and repay the flash loan. Not available via `onMoolahRepay`, which cannot call `withdrawCollateral`. | > Callbacks are a low-level primitive. If you are integrating in TypeScript and do not need custom atomic routing, the [Moolah Lending SDK](/for-developer/lista-lending/sdk) builds standard supply/borrow/repay transactions for you. *** ## Events ### Core market events (`Moolah`) Signatures and indexed parameters are in `moolah/libraries/EventsLib.sol` — read them from there or from the ABI. `Id` is the market identifier (the keccak hash of `MarketParams`). Five things will catch you out when reconstructing state from these logs: * **Position reconstruction.** A supplier's balance evolves through `Supply`/`Withdraw`; a borrower's through `Borrow`/`Repay`/`Liquidate`; collateral through `SupplyCollateral`/`WithdrawCollateral`. All are keyed by the indexed `Id` and the indexed `onBehalf` (or `borrower`) address. * **Interest.** `AccrueInterest` carries the `prevBorrowRate` used for the elapsed period, the `interest` added to the market, and the `feeShares` minted to the fee recipient. Note that the fee recipient can receive shares during accrual **without** a `Supply` event, so reconstruct fee-recipient balances from `AccrueInterest`, not `Supply`. * **Repay/Liquidate rounding.** The repaid amount — `assets` on `Repay`, `repaidAssets` on `Liquidate` — may exceed the market's `totalBorrowAssets` by 1 due to rounding. Account for this when reconciling. * **Bad debt.** On `Liquidate`, non-zero `badDebtAssets`/`badDebtShares` mean the position was underwater and the loss was socialized to suppliers of that market. * **Authorization.** Watch `SetAuthorization` (and `IncrementNonce` for signature-based authorizations) to track which managers can act on a position via the `authorized`/`onBehalf` model. Lista-specific administrative events (provider/broker wiring, whitelists, blacklists, min-loan, default fee) are also declared in the same `EventsLib` and documented alongside the functions that emit them in the [Contract & Interface Reference](/for-developer/lista-lending/contract-reference). ### Interest-rate model events (`InterestRateModel`) The IRMs emit their own events, and **three of them are emitted by both IRMs with byte-identical signatures**, so they share a `topic0` — `BorrowRateCapUpdate`, `BorrowRateFloorUpdate` and `MinCapUpdate` come from either `InterestRateModel` or `FixedRateIrm`. Filter by the emitting address, not by topic alone, or you will file fixed-rate broker-market logs as adaptive-curve events. Only `BorrowRateUpdate` is exclusive to the adaptive curve (`FixedRateIrm` declares it but never emits it, since its `borrowRate` is `view`). `BorrowRateUpdate` is emitted each time Moolah accrues interest against a market that uses this IRM (Moolah calls `IIrm.borrowRate` during `_accrueInterest`), so it is the finest-grained rate signal available to indexers. `avgBorrowRate` is the average per-second rate (scaled by WAD) applied over the accrual interval; `rateAtTarget` is the model's rate at target utilization after the update. Fixed-rate broker markets use a separate `FixedRateIrm`, which emits `SetBorrowRate(Id indexed id, int256 newBorrowRate)` when its rate is set. ### Vault events (`MoolahVault`) The ERC-4626 curator vault layer emits the standard `Deposit`/`Withdraw`/`Transfer` events plus its own lifecycle and configuration set, declared in `moolah-vault/libraries/EventsLib.sol`. Two declared event groups require special handling: **Do not index the vault's `Submit*` / `Revoke*` events.** `SubmitCap`, `SubmitTimelock`, `SetTimelock`, `SubmitGuardian`, `SetGuardian`, `SubmitMarketRemoval` and the `RevokePending*` family are all declared in `EventsLib` but emitted **nowhere**. They are inherited declarations; Lista uses two external OpenZeppelin `TimelockController`s per vault instead of the in-contract pending/timelock mechanism. Their addresses appear in `CreateMoolahVault` as `managerTimeLock` and `curatorTimeLock`; watch those for `CallScheduled` / `CallExecuted` / `Cancelled`. `SetCa
프로젝트로 돌아가기