Maple Finance 백서

Maple Finance

원문

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

DRAWAL_MANAGER_QUEUE_FACTORY"` | `queueWMFactory` | `true` | | `setValidInstanceOf` | `"WITHDRAWAL_MANAGER_FACTORY"` | `queueWMFactory` | `true` | | `setValidInstanceOf` | `"QUEUE_POOL_MANAGER"` | `cashManagementUSDCPoolManager` | `true` | | `setValidInstanceOf` | `"QUEUE_POOL_MANAGER"` | `cashManagementUSDTPoolManager` | `true` | | `setCanDeployFrom` | `poolManagerFactory` | `poolDeployerV3` | `true` | | `setCanDeployFrom` | `withdrawalManagerFactory` | `poolDeployerV3` | `true` | | `setCanDeployFrom` | `queueWMFactory` | `poolDeployerV3` | `true` | In this table, the `Function Name` column contains the name of the function being called, the `Parameter 1`, `Parameter 2`, and `Parameter 3` columns contain the parameters being passed to the function. ### 4. Add Delay to Oracles This function sets a delay on price oracles for specific assets (WETH, WBTC) in the Globals contract. | Asset | Oracle | Delay | | ------ | ----------------------------------------------------------------------------------------- | --------- | | `weth` | [`ethUsdOracle`](https://etherscan.io/address/0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419) | `4 hours` | | `wbtc` | [`btcUsdOracle`](https://etherscan.io/address/0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c) | `4 hours` | ### 5. Setup Factories This function registers new implementations and default versions in various factories (PoolManager, FixedTermLoan, WithdrawalManager). It also enables upgrade paths for existing contracts to move to new implementations. | Factory | Function | Version | Arguments | | -------------------------------- | ------------------------ | ---------- | -------------------------------------------------------------------- | | Pool Manager Factory | `registerImplementation` | 300 | `300, poolManagerImplementationV300, poolManagerInitializer` | | Pool Manager Factory | `registerImplementation` | 301 | `301, poolManagerImplementationV301, poolManagerInitializer` | | Pool Manager Factory | `setDefaultVersion` | 300 | `300` | | Pool Manager Factory | `enableUpgradePath` | 200 -> 300 | `200, 300, poolManagerMigrator` | | Pool Manager Factory | `enableUpgradePath` | 201 -> 300 | `201, 300, poolManagerMigrator` | | Pool Manager Factory | `enableUpgradePath` | 300 -> 301 | `300, 301, poolManagerWMMigrator` | | Fixed Term Loan Factory | `registerImplementation` | 502 | `502, fixedTermLoanImplementationV502, fixedTermLoanInitializerV500` | | Fixed Term Loan Factory | `enableUpgradePath` | 501 -> 502 | `501, 502, fixedTermLoanV502Migrator` | | Fixed Term Loan Factory V2 | `registerImplementation` | 502 | `502, fixedTermLoanImplementationV502, fixedTermLoanInitializerV500` | | Fixed Term Loan Factory V2 | `setDefaultVersion` | 502 | `502` | | Withdrawal Manager Factory | `registerImplementation` | 110 | `110, cyclicalWMImplementation, cyclicalWMInitializer` | | Withdrawal Manager Factory | `setDefaultVersion` | 110 | `110` | | Queue Withdrawal Manager Factory | `registerImplementation` | 100 | `100, queueWMImplementation, queueWMInitializer` | | Queue Withdrawal Manager Factory | `setDefaultVersion` | 100 | `100` | ### 6. Setup PoolPermissionManager The newly deployed `poolPermissionManager` is configured to match each pool configuration, including allowing all existing lenders. ### 7. Upgrade Pool Contracts All the deployed `poolManager's` contracts will be upgraded to version 300. The upgrades are performed with security admin privileges, ensuring secure and authorized changes. ### 8. Upgrade Fixed Term Loans All the deployed `FixedTermLoan's` contracts are upgraded to a new version using security admin privileges. ### 9. Upgrade to Queue Withdrawal Manager The cash management pools will have their withdrawal manager migrated to the new `WithdrawalManagerQueue`. ### 10. Deprecate Fixed Term Loan Factory This is done by setting the default version to 0 to stop new instances being deployed. ### 11. Deprecate Pool Deployer V2 By setting the flag to false for the factory instances, we prevent new pools from being deployed through Pool Deployer V2. | Function Name | Parameter 1 | Parameter 2 | Parameter 3 | | ------------------ | -------------------------- | ---------------- | ----------- | | `setCanDeployFrom` | `poolManagerFactory` | `poolDeployerV2` | `false` | | `setCanDeployFrom` | `withdrawalManagerFactory` | `poolDeployerV2` | `false` | # Strategies Release Deployment Procedure ## Smart Contract Deployments & Upgrade Procedure for Strategies Release The following contracts will be deployed with the relevant release tags. * [Maple Globals](https://github.com/maple-labs/globals-v2/blob/main/contracts/MapleGlobals.sol) instance with updated logic. * [Pool Manager Implementation](https://github.com/maple-labs/pool-v2/blob/main/contracts/MaplePoolManager.sol) instance with updated logic. * [Pool Manager Initializer](https://github.com/maple-labs/pool-v2/blob/main/contracts/proxy/MaplePoolManagerInitializer.sol) instance with updated compiler. * [Pool Deployer](https://github.com/maple-labs/pool-v2/blob/main/contracts/MaplePoolDeployer.sol) instance with updated logic. * 3 instances of the new contract [Maple Strategy Factory](https://github.com/maple-labs/maple-strategies/blob/main/contracts/proxy/MapleStrategyFactory.sol). Each one will be used for `Aave`, `Sky` and `Basic` strategies. * New contract [Maple Aave Strategy Initializer](https://github.com/maple-labs/maple-strategies/blob/main/contracts/proxy/aaveStrategy/MapleAaveStrategyInitializer.sol) * New contract [Maple Aave Strategy Implementation](https://github.com/maple-labs/maple-strategies/blob/main/contracts/MapleAaveStrategy.sol) * New contract [Maple Basic Strategy Initializer](https://github.com/maple-labs/maple-strategies/blob/main/contracts/proxy/basicStrategy/MapleBasicStrategyInitializer.sol) * New contract [Maple Basic Strategy Implementation](https://github.com/maple-labs/maple-strategies/blob/main/contracts/MapleBasicStrategy.sol) * New contract [Maple Sky Strategy Initializer](https://github.com/maple-labs/maple-strategies/blob/main/contracts/proxy/skyStrategy/MapleSkyStrategyInitializer.sol) * New contract [Maple Sky Strategy Implementation](https://github.com/maple-labs/maple-strategies/blob/main/contracts/MapleSkyStrategy.sol) ## Upgrade procedure ### Setting up Pool Manager The following transactions will be made to the `PoolManagerFactory` by the `GOVERNOR` 1. `registerImplementation(400, <newly deployed PM>, <newly deployed PM Initializer>)` 2. `enableUpgradePath(300, 400, address(0))` 3. `enableUpgradePath(301, 400, address(0))` 4. `setDefaultVersion(400)` After that, on each Pool Manager that will be upgraded, the following function will be called: 1. `upgrade(400, "")` by `PoolDelegate/SecurityAdmin` The list of pools that will have their pool manager upgraded are: ``` * AQRU * Cash Management USDC * Blue Chip Secured Lending USDC * High Yield Corporate Loan USDC * High Yield Corporate Loan WETH * High Yield Secured Lending - USDC * Syrup USDC * syrup USDT ``` ### Setting up strategies For each of the 3 instances of `MapleStrategyFactory` deployed, the following transactions will be made by `GOVERNOR`: 1. `registerImplementation(100, <aave/basic/sky strategyImplementation>, <aave/basic/sky strategyInitializer>)` 2. `setDefaultVersion(100)` ### Setting up Globals Following transactions will be made by the `GOVERNOR` or `OPERATIONAL ADMIN` #### Upgrade Globals via Governor 1. `setImplementation(<newly deployed MapleGlobals implementation>`) #### Set Valid Instance Keys via Operational Admin 2. `setValidInstanceOf("STRATEGY_FACTORY", fixedTermLoanManagerFactory, true)` 3. `setValidInstanceOf("STRATEGY_FACTORY", openTermLoanManagerFactory, true)` 4. `setValidInstanceOf("STRATEGY_FACTORY", basicStrategyFactory, true)` 5. `setValidInstanceOf("STRATEGY_FACTORY", aaveStrategyFactory, true)` 6. `setValidInstanceOf("STRATEGY_FACTORY", skyStrategyFactory, true)` 7. `setValidInstanceOf("STRATEGY_VAULT", aToken(USDC), true)` 8. `setValidInstanceOf("STRATEGY_VAULT", aToken(USDT), true)` 9. `setValidInstanceOf("STRATEGY_VAULT", sUSDS, true)` 10. `setValidInstanceOf("PSM", usdsLitePSM, true)` ### Attaching Strategies For each PoolManager of syrupUSDC, syrupUSDT and High-Yield Secured that needs a given strategy added, the following function will be called by the `OPERATIONAL ADMIN` 1. `addStrategy(<aave/basic/sky strategyFactory>, <aave/basic/sky initializer data>)`. ### Strategy Manager Bot Set Key in Globals to allow Bot to manage strategy positions. 1. `setValidInstanceOf("STRATEGY_MANAGER", <turnkey_bot_address>, true)` # Crosschain Mint/Redeem This section documents Maple's CCIP-based crosschain receiver and its integration with Maple pools developed in partnership with Chainlink. # Maple CCIP Receiver The Maple CCIP Receiver is an upgradeable CCIP Any2EVM receiver that binds to a single Maple pool on the destination chain. It accepts chain transfers of either the pool asset (deposit flow) or the pool share token (redemption flow), validates the sender and pool, and returns the resulting tokens to the origin chain. Repository: <https://github.com/maple-labs/maple-cross-chain-receiver> ## Architecture ### Components * **CCIP Router**: Delivers inbound messages and sends outbound return messages. * **MapleCCIPReceiver**: Validates messages, executes pool actions, tracks fees, and handles recovery. * **Maple Pool (ERC-4626)**: Receives deposits and processes redemptions. * **WithdrawalManager**: Queues and manages redemption requests. * **Maple Globals**: Grants the `REDEMPTION_EXECUTOR` role used for redemption execution and request removal. ### High-level flow ![Maple CCIP Receiver high-level flow](https://2107472351-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MLg9y0GYo0LxapRXEes%2Fuploads%2Fgit-blob-d47543e8f1d5ec3757559eab2a8ef797a07aca02%2Fmaple-ccip-receiver-high-level-flow.png?alt=media) ## Message model and validation ### UniversalMessage data Incoming CCIP messages include a data payload that is decoded into a `UniversalMessage`: ```solidity struct UniversalMessage { bytes32 universalSenderAddress; address pool; bytes32 metaData; } ``` * **universalSenderAddress**: A bytes32 universal address (EVM addresses are padded, SVM addresses are native 32 bytes). * **pool**: Must match the single pool configured during initialization. * **metaData**: Tag for offchain tracking and partner attribution. ### Validation gates * **Sender validation**: The CCIP message sender is normalized into a bytes32 address and must match `universalSenderAddress`. * **Pool binding**: `pool` in the message must match the receiver's configured pool. * **Single token**: Only one token transfer per message is supported. * **Token routing**: * Inbound token == pool share token -> redemption flow. * Inbound token == pool asset token -> deposit flow. * Any other token -> revert. ### Chain routing The contract stores a `ChainType` for each CCIP chain selector. The chain type determines how outbound messages are formatted: * **EVM**: `receiver` is an EVM address; extra args use `GenericExtraArgsV2`. * **SVM**: `receiver` is the default SVM receiver; extra args use `SVMExtraArgsV1` with `tokenReceiver` set to the universal sender address. ## Core flows ### Deposit flow (asset token inbound) 1. CCIP Router calls `ccipReceive` with the asset token and encoded `UniversalMessage`. 2. Receiver validates sender, pool, and token, and checks that deposits are enabled. 3. Deposit fee (per token) is applied and stored as collected fees. 4. Receiver estimates CCIP fee for returning shares and verifies the contract has enough native tokens. 5. Receiver deposits assets into the pool via `deposit()` and receives shares. 6. Receiver sends the shares back to the origin chain via CCIP and emits `CrossChainDeposit`. ### Redemption flow (share token inbound) 1. CCIP Router calls `ccipReceive` with pool shares and encoded `UniversalMessage`. 2. Receiver validates sender, pool, and token, and checks that redemptions are enabled. 3. Redemption fee is computed in shares using `convertToExitShares`. 4. Receiver calls `requestRedeem()` and records the request (sender, chain selector, shares). 5. Receiver emits `CrossChainRedeem` with the request ID. 6. A `REDEMPTION_EXECUTOR` later calls `executeRedeemList()` to redeem shares into assets and return them via CCIP. ### Redemption request removal (share return) `removeRedemptionRequests()` allows the `REDEMPTION_EXECUTOR` to remove queued requests and return shares to users if a redemption must be canceled. The caller funds CCIP fees for the return transfer, and any excess ETH is refunded. ### Message routing decision ![Message routing decision](https://2107472351-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MLg9y0GYo0LxapRXEes%2Fuploads%2Fgit-blob-4b4d48eaccc8ccca3b2cc2cb0533e676b14cf72c%2Fmaple-ccip-receiver-message-routing.png?alt=media) ## CCIP send details Outbound transfers are sent with `IRouterClient.getFee()` and `IRouterClient.ccipSend()` using a `Client.EVM2AnyMessage`: * **feeToken** is `address(0)`, so fees are paid in the native token of the pool chain. * **EVM destinations** use `GenericExtraArgsV2` with `allowOutOfOrderExecution` enabled. * **SVM destinations** use `SVMExtraArgsV1` with `tokenReceiver` set to the universal sender address. ## Failure handling and recovery The receiver uses a defensive pattern to store failed messages for recovery: * On failure, the full `Any2EVMMessage` is stored and marked `FAILED` which contains the sender of the request which can be used for recovery. * `retryFailedMessage()` retries processing using the stored message. * `recoverFailedTokensBackToSender()` attempts a retry first, then sends tokens back to the original sender if retry fails. * `adminRescueTokens()` is a last-resort admin path that transfers tokens directly to a beneficiary. ![Failure handling and recovery flow](https://2107472351-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MLg9y0GYo0LxapRXEes%2Fuploads%2Fgit-blob-5516a7e2995390a4c039bacc3db009aca97c948a%2Fmaple-ccip-receiver-recovery-flow.png?alt=media) ## Roles and permissions * **DEFAULT\_ADMIN\_ROLE** * Configure chain types * Set deposit and redemption fees * Enable or disable deposits/redemptions * Withdraw tokens or native funds * Rescue tokens from failed messages * Authorize upgrades (UUPS) * **REDEMPTION\_EXECUTOR** (assigned in Maple Globals) * Execute queued redemptions * Remove redemption requests and return shares * **Public** * Retry and recover failed messages (fees may be required) ## Fee model * **Deposit fees**: Fixed per-token amount deducted from inbound assets before deposit. * **Redemption fees**: Fixed per-token amount charged in assets, converted to share units and deducted from inbound shares. * Collected fees accumulate in `s_tokenFeesBalances` and are withdrawable by an admin. ## Operational considerations * The contract must maintain a native token balance to pay CCIP fees for outbound transfers. * Chain selectors must be configured with a `ChainType` before messages can be sent. * Redemptions require a configured `REDEMPTION_EXECUTOR` in Maple Globals. * Use CCIP message IDs and emitted events (`MessageReceived`, `MessageSent`, `CrossChainDeposit`, `CrossChainRedeem`) for observability. * For integrators: validate deposits and redemptions so the amount is greater than the configured fee for that token. Deposit fees and redemption fees are configured on the receiver contract, so amounts below the fee will revert. # Failed Message Retry and Recovery This guide explains how to identify failed crosschain messages and use MapleCCIPReceiver's retry and recovery flows. It also shows how to check message status in the Chainlink CCIP Explorer. ## Prerequisites and permissions * `recoverFailedTokensBackToSender(messageId)` is permissionless and **payable**. Anyone can call it, but the caller must fund CCIP fees. * `retryFailedMessage(messageId)` is permissionless and **payable**, but it does **not** use `msg.value`; it relies on the contract’s native balance to pay CCIP fees during message processing. * `adminRescueTokens(messageId, beneficiary)` is **admin-only** and is intended as a last resort if normal recovery fails. Both retry and recovery require the message to exist in storage and be in `FAILED` state. If the message is missing or already resolved, the call reverts. ## Finding the messageId You can get the `messageId` from MapleCCIPReceiver event logs on the pool chain: * `MessageReceived` emits the inbound CCIP messageId. * `MessageFailed` emits the messageId when processing fails. * `MessageSent` emits the messageId for outbound return transfers (shares or assets). If you only have a transaction hash, you can search for the transaction in the CCIP Explorer or Block explorer (eg. Etherscan) and copy the messageId from the Explorer details. ## Check status in the Chainlink CCIP Explorer The CCIP Explorer tracks crosschain messages and supports searching by message ID. Steps: 1. Open the CCIP Explorer. 2. Paste the `messageId` into the search field. 3. Review the message status and associated source and destination transactions. This is useful to confirm whether the CCIP transfer has been executed on the destination chain or is still pending. ## Retry delivery in the CCIP Explorer (manual execution) If a CCIP message reaches the destination chain but execution fails (for example, due to an insufficient gas limit), Chainlink supports **manual execution** through the CCIP Explorer. This lets you override the gas limit and retry execution from the Explorer UI. The Chainlink docs describe this as “manual execution” and show the flow using the CCIP Explorer. Use this when the Explorer indicates the message is ready for manual execution or shows a failed execution on the destination chain. For details and prerequisites, follow Chainlink’s manual execution guide <https://docs.chain.link/ccip/concepts/manual-execution> . ## Retry vs. recover MapleCCIPReceiver stores failed messages and exposes two user-facing paths: ### 1) Retry processing (re-run the original logic) Use `retryFailedMessage(messageId)` when you want the original message to be processed again. * The function replays the original message logic. * Fees are paid by the contract's **native balance** (not `msg.value`). * Emits `MessageRecovered` if processing succeeds. * If the retry still fails, the transaction reverts and the message remains in `FAILED` state. ### 2) Recover tokens back to sender Use `recoverFailedTokensBackToSender(messageId)` to return tokens to the original sender if retry fails or is not appropriate. * The function attempts a retry first. If the retry fails, it sends the tokens back to the sender using CCIP. * The caller must provide enough native tokens to cover CCIP fees (`msg.value >= fees`). * Use `estimateRecoveryFee(messageId)` to estimate the fee in native units. * Any excess `msg.value` is refunded to the caller. * Emits `TokensRecovered` and a `MessageSent` for the recovery transfer. ## Funding considerations * **Retry path**: The contract must hold enough native tokens to pay CCIP fees for any outbound sends triggered during retry (for example, sending shares back after a deposit). If the contract balance is insufficient, the retry will revert with `NotEnoughBalance`. * **Recovery path**: The caller pays fees for the return transfer. The contract approves the router for the failed message’s tokens and uses CCIP to send them back. ## Viewing failed message state on-chain * `getFailedMessages(offset, limit)` returns failed message IDs and status. * `getMessage(messageId)` returns the stored `Any2EVMMessage` content. * A message can be in `FAILED` or `RESOLVED` state in the receiver's storage. Notes: * `getFailedMessages` only returns items
프로젝트로 돌아가기