Maple Finance 백서

Maple Finance

원문

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

e `processRedemptions()` function has a reentrancy guard since it performs external calls. *NOTE*: The amount of shares must be specified and are assumed to be a reasonable amount where out of gas issues don't occur. ### Exchange Rate When a withdrawal request is processed, the amount of assets withdrawn is calculated by converting the requested shares into assets using the current exchange rate. This means that the exchange rate for different users' withdrawal requests may vary depending on when the requests are processed. If any loans have been impaired or are in the process of liquidation, the value of each share will decrease until the impairments and/or liquidations are finalized. Therefore, performing a withdrawal during a liquidation may result in a lower amount of assets being withdrawn compared to if the withdrawal occurs after the liquidation is finalized and some or all losses have been recovered. The formula for calculating the exchange rate of shares to assets is defined as: `exchangeRate = (totalAssets - unrealizedLosses) / totalSupply` ### Partial Redemptions If there is insufficient liquidity available during the processing of a request, it will be processed partially (*note this is only applicable to the last request being processed in the queue*). This means that only a portion of the shares from the original withdrawal request will be redeemed. The remainder will retain their original position in the queue and may be processed again at any time. The formula for calculating the number of shares that can be redeemed is defined as follows: `redeemableShares(user) = min(lockedShares(user), lockedShares(user) * availableAssets / requiredAssets)` ### Adjust or Cancel a Request (removeSharesById) The request owner can reduce or cancel a specific pending request at any time before it is processed by calling: `removeSharesById(requestId, sharesToRemove)` * Caller must be the request owner. * If `sharesToRemove` equals the current request shares, the request is cancelled. Otherwise the request is decreased and remains in the queue with the original position. * Returns `(sharesReturned, sharesRemaining)` and transfers the returned LP shares back to the owner. * Use `requests(requestId)` or `requestsByOwner(owner)` to inspect pending requests and shares. ### Manual Requests (2 step process) Each withdrawal request can be processed automatically (by default) or manually by calling `requestRedeem()` first then calling `redeem()`. The pool delegate or any protocol admin can enable manual requests for users who want to opt-out of automatic processing. The difference between automatic and manual requests is as follows: * Automatic requests will be immediately redeemed on processing. * Manual requests will be redeemed any time after processing (when the `redeem()` function is actually called). Manual withdrawal requests are primarily supported so that the protocol remains ERC-4626 compatible (**internal use only**). Automatic requests are the default and preferred way of handling withdrawals. ### Roles & Permissions * OnlyPoolManager: `addShares`, `processExit`, `removeShares` (Pool-driven queue interactions). * OnlyRedeemer (WITHDRAWAL\_REDEEMER instance, Pool Delegate, or Operational Admin): `processRedemptions`, `processEmptyRedemptions`, `removeRequest`. * Unprivileged user (request owner): `removeSharesById` (decrease or cancel a request). ### Events & Queue Internals * Events: `RequestCreated`, `RequestDecreased`, `RequestRemoved`, `RequestProcessed`, `ManualWithdrawalSet`, `EmptyRedemptionsProcessed`, `ManualSharesIncreased`, `ManualSharesDecreased`. * Queue pointers: `nextRequestId` and `lastRequestId` track processing range. `processEmptyRedemptions(n)` advances `nextRequestId` over empty entries to keep processing efficient. ### Legacy Functions For the sake of backwards compatibility with the `PoolManager`, certain functions used in the previous version of the withdrawal manager have been retained. These are as follows: * `lockedShares()`: returns the amount of `manualSharesAvailable` (only used for manual withdrawals). * `lockedLiquidity()`: returns zero, meaning it's at the pool delegate's discretion how much liquidity should be available for servicing withdrawals. * `isInExitWindow()`: returns `true`, since there are no more withdrawal windows and withdrawals can be processed at any time. ### Key Assumptions Generally a push pattern for token transfers is not recommended as it can lead to uncontrolled revert conditions. In the case of the `WithdrawalManager` this could mean issues such as the queue being blocked. This is a known issue and to address this we have added the `removeRequest()` function that can be called by the pool delegate or protocol admin to unblock the queue. Additionally: * No tokens with callbacks will be used. * This queue based withdrawal manager will only be used in permissioned pools, not public pools to avoid denial of service attacks. * Extensive research will be done when onboarding new ERC20 tokens as the underlying asset. * An LP being blacklisted by USDC/USDT is a low likelihood event due to the KYC'd nature of LPs in permissioned pools and the use of `removeRequest()` can address this issue. To highlight the key reason to support this push pattern is to address the business need from LPs. ### Invariants ``` * Withdrawal Manager (Queue) * Invariant A: ∑request.shares + ∑owner.manualShares == totalShares * Invariant B: balanceOf(this) >= totalShares * Invariant C: ∀ requestId(owner) != 0 -> request.shares > 0 && request.owner == owner * Invariant D: nextRequestId <= lastRequestId + 1 * Invariant E: nextRequestId != 0 * Invariant F: requests(0) == (0, 0) * Invariant G: ∀ requestId[lender] ∈ [0, lastRequestId] * Invariant H: requestId is unique ``` # Singletons # Globals Singleton: Protocol Configuration ## Overview MapleGlobals is a singleton contract used to save system-wide parameters that all Pool must abide to, and is also used to control time-locked actions, such as upgrades and pauseablilty. ## Permissioning The Governor (the `GovernorTimelock` contract) retains primary authority for modifying parameters stored in MapleGlobals. Additionally, the Operational Admin, authorized by the Governor, is empowered to alter specific operational parameters. Furthermore, the Security Admin is responsible for adjusting pause‑related parameters. ## Pausing A more granular approach was introduced in the June 2023 release with details found [here.](/technical-resources/security/emergency-protocol-pause). 1. Global pause 2. Per contract pause 3. Per function un-pause. ## Timelock Scheduling To perform upgrades in vital pool contracts, pool delegates need to first schedule upgrade calls in the globals contract and only after the pre-determined period has elapsed, that the actions can be triggered. More information on [timelocks](/technical-resources/admin-functions/timelocks). ## Whitelisting Instance Deployment from Factories The Governor (via the `GovernorTimelock`) or Operational Admin can whitelist individual addresses that can use the `createInstance` functions at each factory respectively, which is then stored in the `_canDeployFrom` storage mapping. Factories can call `globals.canDeploy(addressOfCaller)` to determine if the caller is allowed to deploy one of its instances, and the mapping itself can be queried via `globals.canDeployFrom(addressOfFactory, addressOfCaller)`. ## System Parameters In this section, the parameters stored in the globals contract are outlined. **Relevant Addresses** * `MapleTreasury` * `Governor` * `SecurityAdmin` - Special account allowed to trigger protocol-wide pause. * `MigrationAdmin` - Special account used during the liquidity migration. * `OperationalAdmin` - Special account given the authority by Governor to perform a subset of operational functions. * Factories, such as: * `LiquidatorFactory` * `FixedTermLoanFactory` * `OpenTermLoanFactory` * `FixedTermLoanManagerFactory` * `OpenTermLoanManagerFactory` * `FixedTermRefinancer` * `OpenTermRefinancer` * `FeeManager` * `LiquidatorFactory` * `PoolManagerFactory` * `WithdrawalManagerFactory` * Borrowers * Pool Delegates * Pool assets * Price oracles for pool assets **Pool Specific Parameters** * `platformManagementFeeRate` * `platformOriginationFeeRate` * `platformServiceFeeRate` * `minCoverAmount` * `maxCoverLiquidationPercent` ## Proxy Architecture The MapleGlobals contract make use of NonTransparentProxy, instead of the transparent proxy used almost everywhere in the Maple code base. The reasoning is to add an extra layer of security, making always possible to set the implementation, even if it was previously set to the wrong address beforehand. # Governor Timelock **Overview** * Replaces a Governor EOA with a contract-based timelock so all governor-privileged transactions execute after a delay. * Separates responsibilities via roles and enforces a schedule → wait → execute lifecycle. * Prevents immediate parameter and role changes. Certain meta‑changes are themselves timelocked. **Key Roles** * `PROPOSER_ROLE`: Schedules proposals via `scheduleProposals(...)` or `proposeRoleUpdates(...)`. * `EXECUTOR_ROLE`: Executes queued proposals during their execution window via `executeProposals(...)`. * `CANCELLER_ROLE`: Unschedules proposals via `unscheduleProposals(...)` (cannot unschedule role updates). * `ROLE_ADMIN`: Proposes role changes using `proposeRoleUpdates(...)` and manages token withdrawer pending address. * `tokenWithdrawer` (separate address): Can rescue ERC20 tokens accidentally sent to the timelock. **Timelock Parameters** * Defaults are set at deployment to at least `MIN_DELAY = 1 day` and `MIN_EXECUTION_WINDOW = 1 day`. * Default parameters can be changed with `setDefaultTimelockParameters(delay, executionWindow)`. This function is `onlySelf` and must be executed via a timelocked proposal to the timelock itself. * Per‑function overrides: `setFunctionTimelockParameters(target, selector, delay, executionWindow)` supports either both values set to zero (use defaults) or both meeting minimums. This function is `onlySelf` and must be timelocked. * Changing a function’s timelock uses that function’s prior timelock parameters to gate the change (cannot reduce a delay instantly). **Proposal Lifecycle** * Schedule: `scheduleProposals(address[] targets, bytes[] data)` records proposals with `delayedUntil` and `validUntil` and computes a `proposalHash = keccak256(target, data)`. * Role updates: Must be scheduled via `proposeRoleUpdates(bytes32[] roles, address[] accounts, bool[] shouldGrant)` (not via `scheduleProposals`). These cannot be unscheduled. * Unschedule: `unscheduleProposals(uint256[] proposalIds)` allowed only when `isUnschedulable` is true (i.e., not role updates). * Execute: `executeProposals(uint256[] ids, address[] targets, bytes[] data)` checks existence, timing window, and data hash, deletes the proposal, then calls the target with the exact `data`. * Window semantics: Executable if `block.timestamp` is within `[delayedUntil, validUntil]` via `isExecutable(id)`. **Security Notes** * `onlySelf` gates sensitive meta‑operations (`updateRole`, timelock config), ensuring they can only be changed through the timelock. * Binds execution to exact calldata via the stored `proposalHash`. * Disallows scheduling to EOAs (`target.code.length > 0`). * Role updates, once queued, cannot be unscheduled. **Token Rescue** * `setPendingTokenWithdrawer(new)` (ROLE\_ADMIN) → `acceptTokenWithdrawer()` (new address) establishes the token withdrawer. * `withdrawERC20Token(token, amount)` callable only by `tokenWithdrawer` to rescue funds sent to the timelock. **Typical Workflows** * Schedule and execute a MapleGlobals change: 1. `scheduleProposals([globals], [abi.encodeWithSelector(globals.setPlatformServiceFeeRate.selector, newRate)])` (PROPOSER). 2. Wait until `isExecutable(id)` returns true within the execution window. 3. `executeProposals([id], [globals], [encodedData])` (EXECUTOR). * Grant `EXECUTOR_ROLE` to a new account: 1. `proposeRoleUpdates([EXECUTOR_ROLE], [newExecutor], [true])` (ROLE\_ADMIN). 2. After delay, `executeProposals([id], [timelock], [abi.encodeWithSelector(timelock.updateRole.selector, EXECUTOR_ROLE, newExecutor, true)])` (EXECUTOR). * Set a per‑function override (e.g., extend delay for `globals.setPriceOracle`): 1. Schedule `setFunctionTimelockParameters(globals, setPriceOracle.selector, 2 days, 1 day)` to the timelock (PROPOSER). 2. Execute after the prior timelock for that function has elapsed (EXECUTOR). **Events and Monitoring** * `ProposalScheduled`, `ProposalExecuted`, `ProposalUnscheduled` for lifecycle transitions. * `FunctionTimelockSet`, `DefaultTimelockSet` for configuration changes. * `RoleUpdated` for access changes. `PendingTokenWithdrawerSet` and `TokenWithdrawerAccepted` for rescue admin. **Deployment and Setup** * Constructor arguments: `tokenWithdrawer`, `proposer`, `executor`, `canceller`, `roleAdmin`. * Defaults initialize to minimums and can be increased later via timelocked calls. * Recommended mapping: * Governance multisig: `PROPOSER_ROLE`, `EXECUTOR_ROLE`, `ROLE_ADMIN`. * Security/ops multisig: `CANCELLER_ROLE` (to unschedule non‑role proposals when needed). **Context** * This contract replaces a Governor EOA so that all governor‑privileged transactions are enforced to pass through a timelock. * Pool Delegate–level timelocks (e.g., contract upgrades) remain documented separately. See `technical-resources/admin-functions/timelocks.md`. # MapleTreasury ### Overview The MapleTreasury contracts is how the Maple protocol collects and manages revenues. Revenues collected by the MapleTreasury will be used to fund further development of the protocol, but can also be distributed to the MPL token holders via xMPL. ### Access Control The `governor` which is read from `MapleGlobals` has admin rights interact with the MapleTreasury including pulling funds using `reclaimERC20`. ### Revenue Fees generated by the protocol are paid to the MapleTreasury. A more detailed breakdown can be found in the [fees](/technical-resources/protocol-overview/fees) section of the wiki. # Oracles Oracle price feeds used in the Maple protocol to determine auction pricing for collateral liquidations in the `getExpectedAmount` function in the LoanManager. Oracles for given assets are set using `Globals.setPriceOracle()`. For the majority of assets this will be Chainlink oracle wrappers, for USDC it will be a constant USD oracle. Oracle wrappers have the capability to provide a manual price in the event of an oracle outage, using the security multisig. In all other cases, it will simply pass through the value from `getLatestPrice` in the Chainlink oracle. # Pool Permission Manager ### Overview The Pool Permission Manager contract simplifies permission management for lenders and pool delegates. It streamlines the management of the global allowlist, permissions specific to each pool, and criteria for accessing various functions. This can eliminates the need for manual whitelisting of new addresses for each pool if the pool opts for using the right permission level. To set the eligibility criteria for lenders, the permissions or protocol admins utilizes the `setLenderBitmaps` function. Pool delegates can manage the criteria for accessing specific functions of a pool through the `setPoolBitmaps` function. The Pool Permission Manager will be deployed as a singleton non-transparent-proxy similar to the Globals contract. ### Permission Levels Pool delegates or protocol admins can modify the permission level for a specific lending pool using `setPoolPermissionLevel`. There are four permission levels that determine who can access a lending pool: * `PRIVATE`: This is the default permission level. It allows access only to lenders who are on the allowlist. If a lending pool is at this level, lenders not on the allowlist will be denied access to the pool's functions. * `FUNCTION_LEVEL`: At this level, access is allowed if the function-specific pool bitmaps match the criteria set. This means that lenders need to meet specific function-based criteria for access. (Note if a lender is on the allowlist for the pool the permission check early circuits to return true). * `POOL_LEVEL`: When a lending pool is at this level, access is granted if the pool bitmaps match, irrespective of specific functions. In other words, if the pool-level criteria match, lenders can interact with any function within the pool. (Note if a lender is on the allowlist for the pool the permission check early circuits to return true). * `PUBLIC`: This is the highest level of permission. A lending pool at this level provides unrestricted access to all functions. Once a lending pool is set to public, it cannot be changed back to permissioned. ### Bitmaps To manage `FUNCTION_LEVEL` and `POOL_LEVEL` permissions bitmaps are used. Each bit represents a criteria off-chain that a lender must meet in order to interact with a pool share token. A `uint256` is used to represent the bitmaps in the `PoolPermissionManager` this allows operators to configure up to 256 unique criteria. Whilst noting this gives an upper bound of 256 as a limit and there are implementations where we could extend the available bits infinitely, we have opt-ed to stick with 256 bits for simplicity and realistically we deem this to be more then sufficient. In a future upgrade this can be extended if required. Note: When setting the criteria via the `poolBitmaps` mapping the zero bytes key is used to denote the `POOL_LEVEL` criteria whereas the specific function Ids are used as keys for the `FUNCTION_LEVEL` criteria per pool manager. ### Access Configuration Pool delegates or protocol administrators can modify the allowlist of lenders using the `setLenderAllowlist` function. This function enables the addition or removal of lenders from the pool's allowlist, granting tailored control over pool-specific eligibility criteria. `configurePool` function allows pool delegates or protocol admins to set criteria for accessing specific functions within their lending pools by specifying pool-level bitmaps and function-specific bitmaps alongside the overall permission level. This has been added as a convenience function. ### Evaluating permissions The `hasPermission` function is responsible for determining whether a lender or a group of lenders has permission to access specific functions within a lending pool. These actions can include, but are not limited to, depositing assets, withdrawing assets, or any other operations defined by the lending protocol. A complete list of functions checked can be found in the `canCall()` function of the `PoolManager`. The `hasPermission` function evaluates whether access should be granted based on the following steps: * Public Pool: If the lending pool is set to the `PUBLIC` permission level, the function automatically allows access. This means that lenders can freely interact with the pool, as there are no restrictions. * Allowlist Check: If the lending pool is at the `PRIVATE` level, the function checks if the lender is on the allowlist. If the lender is on the allowlist, access is granted. If not, access is denied. * Bitmap Matching: When operating at the `FUNCTION_LEVEL` or `POOL_LEVEL`, the function evaluates whether the lender's permissions align with the specific function (for `FUNCTION_LEVEL`) or with the entire pool (for `POOL_LEVEL`). This matching is based on the lender's bitmap and the pool's bitmap. (Note if a lender is on the allowlist for the pool the permission check early circuits to return true). * Bitmap Matching Result: If the bitmaps match, access is granted. However, if there is no matching access is denied. ### Important Considerations For `FUNCTION_LEVEL` and `POOL_LEVEL` permissions it's important that t
프로젝트로 돌아가기