Lista DAO 백서

Lista DAO

원문

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

-lending/smart-contract/smart-contract-bsc-brokers); match on the same loan and collateral tokens. * **`termId`** — read the target broker's `getFixedTerms()`, which returns `{ termId, duration, apr }` per offered term. See [Broker Reference](/for-developer/lista-lending/broker-reference). *** ## Reference flow 1. Read the user's position on `outMarket` — `collateral` and `borrowShares`. 2. Pick the fixed-term market with the same pair, and a `termId` from its broker's `getFixedTerms()`. 3. `MOOLAH.isAuthorized(user, positionManager)`; if false, have the user call `setAuthorization(positionManager, true)`. 4. Call `migrateCommonMarketToFixedTermMarket` with the collateral amount and **one** of borrow amount or borrow shares. After conversion the debt lives at the broker, so read it with `getUserTotalDebt(user)` and repay through the broker rather than through Moolah. *** ## See also * [Moolah Lending SDK](/for-developer/lista-lending/sdk) — this flow has no SDK builder; assemble the call directly. # Moolah Lending SDK The Moolah Lending SDK is the TypeScript integration path for Lista Lending (Moolah) on BNB Chain and Ethereum, published on public npm under the `@lista-dao` scope. It is **wallet-agnostic**: read methods call the chain (via [viem](https://viem.sh)) or the public Lista API, and write methods return an array of plain transaction-step descriptors that you execute with your own wallet client. The SDK never holds keys, never signs, and never broadcasts on your behalf. > **Check the published version before you pin.** The two packages release independently of the protocol, so the npm release can trail the contracts — run `npm view @lista-dao/moolah-lending-sdk version` and compare against the [Smart Contract](/for-developer/lista-lending/smart-contract) tables. Where the SDK is behind, the contract reference is authoritative and you can call Moolah directly; see [Contract & Interface Reference](/for-developer/lista-lending/contract-reference). ## Packages | Package | Description | | ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | | [`@lista-dao/moolah-lending-sdk`](https://www.npmjs.com/package/@lista-dao/moolah-lending-sdk) | The `MoolahSDK` builder — reads chain/API data, returns transaction steps. | | [`@lista-dao/moolah-sdk-core`](https://www.npmjs.com/package/@lista-dao/moolah-sdk-core) | Types, pure simulation functions, contract ABIs, the `Decimal` utility, `MoolahApiClient`. | Installing the lending SDK pulls the core package in and re-exports a convenience subset of it. The pure **simulate functions**, interest-rate helpers, and contract **ABIs** are *not* re-exported — import those from `@lista-dao/moolah-sdk-core` directly. ```bash pnpm add @lista-dao/moolah-lending-sdk pnpm add viem@^2.22.10 ``` `viem` is a direct dependency of both packages (`viem@^2.22.10`), so you do not need it to *use* the SDK — but you will use it to execute the returned steps. Install a version in the same range so your package manager dedupes to one copy: **two viem instances cause client and type mismatches** across the `publicClients` boundary. ## Writing transactions: builders, not senders `build*Params` methods return an ordered array of step descriptors. Each carries a `params` object with `{ to, abi, functionName, args, value, chainId, data }`, plus an optional `meta`. Execute them in order with your own wallet client. ```typescript import { parseUnits } from "viem"; const supplySteps = await sdk.buildSupplyParams({ chainId: 56, marketId, assets: parseUnits("100", 18), walletAddress }); const borrowSteps = await sdk.buildBorrowParams({ chainId: 56, marketId, assets: parseUnits("50", 18), walletAddress }); // Collateral must land before the borrow, so run the supply steps first. for (const step of [...supplySteps, ...borrowSteps]) { // `params.to` maps onto viem's `address`; `chainId` and `data` are extra // fields that `writeContract` does not accept. const hash = await walletClient.writeContract({ address: step.params.to, abi: step.params.abi, functionName: step.params.functionName, args: step.params.args, value: step.params.value, }); await publicClient.waitForTransactionReceipt({ hash }); } ``` Three things about that loop: * **Execute every step, in order, and never dedupe by `step`.** A builder prepends `"approve"` steps when an allowance is needed. * **Ethereum mainnet USDT emits&#x20;*****two*****&#x20;approve steps** when a non-zero but insufficient allowance already exists — a reset to `0` (flagged `meta.reset === true`) followed by the real approve — because that contract rejects non-zero → non-zero allowance changes. A sufficient allowance emits none at all. * **The SDK's "supply" is the collateral side.** `buildSupplyParams` calls `supplyCollateral`; Moolah's own `supply` — lending the loan asset — has no builder and is reached through a vault. ## Known gaps Verified against `@lista-dao/moolah-lending-sdk@1.0.11` / `@lista-dao/moolah-sdk-core@1.0.12` — re-check these once the SDK ships a new release: * **Do not resolve addresses from `getContractAddress` / `getContractAddressOptional`.** Several entries in the bundled address book are unset — on BNB Chain as well as Ethereum. The first throws, the second returns the **zero address**, which is the more dangerous failure since a caller can send to it. Use the [Smart Contract](/for-developer/lista-lending/smart-contract) tables instead. * `getBrokerUserPositions` and `getMarketUserDataWithBroker` do not work on Ethereum. * Native-asset (ETH) markets and vaults are not detected correctly — use the ERC-20 paths. * `getBrokerFixedTerms` decodes with the `LendingBroker` ABI, so it does not support a `CreditBroker`, whose `FixedTermAndRate` carries a fourth field (`termType`). ## Reading market state `getMarketExtraInfo` and `getMarketUserData` return the market's live economic state — `LLTV`, `borrowRate`, `utilRate`, `priceRate`, `minLoan`, and the user's `collateral`, `borrowed`, `loanable`, `withdrawable`, `LTV`. `getMarketRuntimeData` returns extra info, write config and user data in one call. **`priceRate` is loan tokens per one collateral token** — `collateral × priceRate` is a loan-denominated value. Inverting it inverts every LTV and liquidation figure you derive from it. Human-scaled amounts come back as `Decimal` (a fixed-point helper with `add`/`sub`/`mul`/`div`, rounding controls and comparisons); raw on-chain integers — borrow shares, timestamps, rate caps, the `MarketParams` struct — stay `bigint`. ## See also * [Integration Patterns](/for-developer/lista-lending/integration-patterns) — provider and broker models. * [Moolah Lending API](/for-developer/services/lending-api) — the REST surface the API-sourced reads use. # Contract & Interface Reference **Moolah** is the singleton that holds every Lista Lending market. Call it directly from Solidity, or from any stack that cannot use the [SDK](/for-developer/lista-lending/sdk); the signatures, structs and Lista-specific controls below are what you need to do that. Moolah is powered by Morpho and built on the Morpho Blue smart contracts, then extended with Lista-specific controls. For the layers around it: the ERC-4626 vault is in [Vault Reference](/for-developer/lista-lending/vault-reference), provider-gated collaterals in [Providers](/for-developer/lista-lending/providers), and the fixed-term broker surface in [Broker Reference](/for-developer/lista-lending/broker-reference). Every market — regardless of collateral, oracle, or IRM — lives inside this one contract and is addressed by a market `Id`. For deployed addresses, see the [Smart Contract](/for-developer/lista-lending/smart-contract) reference; For higher-level flows see [Integration Patterns](/for-developer/lista-lending/integration-patterns); for the callback interfaces and emitted events see [Events & Callbacks](/for-developer/lista-lending/events-and-callbacks). *** ## Types & structs ### `Id` ```solidity type Id is bytes32; ``` A market's identifier is the `keccak256` hash of the ABI-encoded `MarketParams` (five 32-byte words, in struct order). Two markets with identical parameters therefore collapse to the same `Id`. ```solidity Id id = Id.wrap(keccak256(abi.encode(marketParams))); ``` The same value is exposed on-chain via the `idToMarketParams(Id)` view (the reverse mapping) and is used as the key for `position`, `market`, providers, brokers, and both whitelists. ### `MarketParams` The immutable definition of a market. Once created, these values cannot change; a new combination is simply a new market. | Field | Type | Meaning | | ----------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `loanToken` | `address` | The asset supplied and borrowed. | | `collateralToken` | `address` | The asset posted as collateral. | | `oracle` | `address` | Price source; must expose `peek(address)`. Every oracle Lista deploys on the `IOracle` path except `IdleOracle` (which returns a literal `0` for its idle collateral) returns an 8-decimal price — the legacy CDP's own `peek()` surface is 18-decimal, but that's a separate, unrelated contract. Moolah itself never validates the decimals convention either way: market creation merely probes that `peek` does not revert — see [Consuming Oracle Prices](/for-developer/multi-oracle/consuming-prices). | | `irm` | `address` | Interest Rate Model. Must be enabled via `isIrmEnabled`. | | `lltv` | `uint256` | Liquidation Loan-To-Value, scaled by `WAD` (`1e18`). Must be enabled via `isLltvEnabled`. | ### `Position` Per-user, per-market state: `mapping(Id => mapping(address => Position))`. | Field | Type | Meaning | | -------------- | --------- | ------------------------------------------- | | `supplyShares` | `uint256` | Supply-side shares owned by the user. | | `borrowShares` | `uint128` | Borrow-side (debt) shares owed by the user. | | `collateral` | `uint128` | Collateral balance posted by the user. | > For `feeRecipient`, `supplyShares` does not include fee shares accrued since the last interest accrual. ### `Market` Aggregate per-market accounting: `mapping(Id => Market)`. | Field | Type | Meaning | | ------------------- | --------- | --------------------------------------------------------------------------------- | | `totalSupplyAssets` | `uint128` | Total supplied assets (excl. interest since last accrual). | | `totalSupplyShares` | `uint128` | Total supply shares outstanding. | | `totalBorrowAssets` | `uint128` | Total borrowed assets (excl. interest since last accrual). | | `totalBorrowShares` | `uint128` | Total borrow shares outstanding. | | `lastUpdate` | `uint128` | Timestamp of the last interest accrual. A non-zero value means the market exists. | | `fee` | `uint128` | Market fee on interest, scaled by `WAD`. Capped at `MAX_FEE`. | Shares use OpenZeppelin's virtual-shares method (`VIRTUAL_SHARES = 1e6`, `VIRTUAL_ASSETS = 1`) to mitigate share-price manipulation; conversions round in the protocol's favor. ### `Authorization` & `Signature` Used by `setAuthorizationWithSig` for gasless (EIP-712) authorization delegation. | `Authorization` field | Type | Meaning | | --------------------- | --------- | ---------------------------------------------------------------- | | `authorizer` | `address` | The account granting authorization (and the recovered signer). | | `authorized` | `address` | The account being authorized to manage `authorizer`'s positions. | | `isAuthorized` | `bool` | The authorization value to set. | | `nonce` | `uint256` | Must equal `authorizer`'s current `nonce`; prevents replay. | | `deadline` | `uint256` | Signature expiry timestamp. | `Signature` is a standard `{ uint8 v; bytes32 r; bytes32 s; }`. The EIP-712 domain is `EIP712Domain(uint256 chainId,address verifyingContract)`; the type hash is `Authorization(address authorizer,address authorized,bool isAuthorized,uint256 nonce,uint256 deadline)`. The current chain's separator is readable via `domainSeparator()`. *** ## Core external functions Where a function takes both `assets` and `shares`, **exactly one must be zero** (enforced by `exactlyOneZero`); the other side is derived by the shares math. ### Market creation ```solidity function createMarket(MarketParams memory marketParams) external; ``` Creates a market. Reverts unless `irm` and `lltv` are enabled, `loanToken`/`collateralToken`/`oracle` are non-zero, and the market does not already exist. Records `lastUpdate = block.timestamp`, sets the market `fee` to `defaultMarketFee`, stores the reverse mapping, probes the oracle for both tokens, and initializes the IRM. Emits `CreateMarket`. When the `OPERATOR` role has members, only an `OPERATOR` may create markets; otherwise creation is permissionless. > **Approve the contract that actually pulls the tokens — that isn't always Moolah.** For direct core calls with no provider or broker in the way, `supply` and `supplyCollateral` pull with `transferFrom` where the spender is the Moolah singleton, so approve Moolah for those. Gating is per leg, not per market: a **collateral provider** takes over `supplyCollateral` / `withdrawCollateral`; a **broker** takes over `borrow` / `repay`. A broker does not gate collateral — on a broker market with no collateral provider you still call `supplyCollateral` on Moolah and approve Moolah for it. Two cases route the pull elsewhere: when a **collateral provider** is set, Moolah requires `msg.sender == provider`, so the provider itself calls `supplyCollateral` and must have already pulled the tokens from you (e.g. `SmartProvider`/`SlisBNBProvider` both do `transferFrom(msg.sender, address(this), ...)` before calling Moolah) — **approve the provider, not Moolah**. When a **broker** is set, `Moolah.repay` requires `msg.sender == broker`, so the end user cannot call it directly — the broker itself pulls the repayment from the user (e.g. `LendingBrokerOperatorLib` does `transferFrom(user, address(this), ...)`) before forwarding to Moolah — **approve the broker contract, not Moolah, for repay on a broker market.** See [Integration Patterns](/for-developer/lista-lending/integration-patterns). ### Supply / withdraw (loan-side liquidity) ```solidity function supply(MarketParams memory marketParams, uint256 assets, uint256 shares, address onBehalf, bytes memory data) external returns (uint256 assetsSupplied, uint256 sharesSupplied); ``` Supplies loan assets on behalf of `onBehalf`, minting supply shares. Accrues interest first. If `data` is non-empty, calls back `onMoolahSupply` on the caller before pulling tokens via `transferFrom`. Subject to the per-market whitelist and vault blacklist, and to the `minLoan` floor on the resulting position. ```solidity function withdraw(MarketParams memory marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver) external returns (uint256 assetsWithdrawn, uint256 sharesWithdrawn); ``` Burns supply shares of `onBehalf` and sends assets to `receiver`. Caller must be `onBehalf` or authorized. Reverts if it would push `totalBorrowAssets` above `totalSupplyAssets` (`insufficient liquidity`). ### Borrow / repay (debt-side) ```solidity function borrow(MarketParams memory marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver) external returns (uint256 assetsBorrowed, uint256 sharesBorrowed); ``` Borrows loan assets against `onBehalf`'s collateral and sends them to `receiver`. Accrues interest, then requires the resulting position to be healthy (`_isHealthy`) and the market to keep `totalBorrowAssets <= totalSupplyAssets`. Access depends on the market's routing: if a **broker** is set, only the broker may borrow (and must be the receiver); else if the caller is the market's **provider**, the receiver must be that provider; otherwise the caller must be `onBehalf` or authorized. Subject to the whitelist and the `minLoan` floor. ```solidity function repay(MarketParams memory marketParams, uint256 assets, uint256 shares, address onBehalf, bytes memory data) external returns (uint256 assetsRepaid, uint256 sharesRepaid); ``` Repays `onBehalf`'s debt, burning borrow shares. Accrues interest first; if `data` is non-empty, calls back `onMoolahRepay` before pulling tokens. If a broker is set for the market, only the broker may repay. A partial repay that would leave debt below `minLoan` reverts. > **To close a position entirely, pass the full `borrowShares` and leave `assets = 0`.** Reading the debt as assets and repaying that figure leaves sub-`minLoan` dust once interest accrues between your read and execution, and the whole call reverts — a repay-all button built that way fails for every user. ### Collateral management ```solidity function supplyCollateral(MarketParams memory marketParams, uint256 assets, address onBehalf, bytes memory data) external; ``` Posts collateral for `onBehalf`. Does **not** accrue interest (not required, saves gas). If a provider is set for the collateral token, only the provider may call. If `data` is non-empty, calls back `onMoolahSupplyCollateral` before pulling tokens. Subject to the whitelist. ```solidity function withdrawCollateral(MarketParams memory marketParams, uint256 assets, address onBehalf, address receiver) external; ``` Withdraws collateral to `receiver`. Accrues interest, then requires the position to remain healthy. If a provider is set, only the provider may call (and must be the receiver); otherwise the caller must be `onBehalf` or authorized. ### Liquidation ```solidity function liquidate(MarketParams memory marketParams, address borrower, uint256 seizedAssets, uint256 repaidShares, bytes memory data) external returns (uint256 seized, uint256 repaid); ``` Liquidates an unhealthy `borrower`. Exactly one of `seizedAssets` / `repaidShares` must be zero; the other is derived using the liquidation incentive factor `min(MAX_LIQUIDATION_INCENTIVE_FACTOR, 1 / (1 - LIQUIDATION_CURSOR * (1 - lltv)))`. Accrues interest, checks the position is unhealthy at the oracle price, seizes collateral to the caller, and pulls the repaid loan assets. If collateral reaches zero, remaining debt is realized as bad debt against the market's supply side. Gated by the per-market **liquidation whitelist**. If `data` is non-empty, `onMoolahLiquidate` is called before the repay transfer. ```solidity function liquidateBrokerPosition(MarketParams memory marketParams, address borrower, uint256 badDebtShares) external returns (uint256 seized, uint256 repaid); ``` Broker-only path to write down `badDebtShares` of a broker-market borrower against the market's supply side — the loss is socialized across all suppliers by reducing `totalSupplyAssets`, and the fee recipient's position is not touched. Callable only by the market's broker; this path performs **no** health check, so the broker is responsible for determining that the position is unhealthy. ### Flash loans ```solidity function flashLoan(address token, uint256 assets, bytes calldata data) external; ``` Transfers `assets` of `token` to the caller, invokes `onMoolahFlashLoan`, then pulls the same `assets` back in the same transaction. Has access to the contract's entire balance of `token` (all markets' liquidity and collateral combined). The flash **fee is zero**. Reverts if the token is on the flash-loan blacklist or `assets` is zero. Not ERC-3156 compliant. `whenNotPause
프로젝트로 돌아가기