Cap 백서

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

from `msg.sender`. 3. **Divest**: The FractionalReserve layer divests `amountOut + fee` of the asset from the active yield strategy if needed to cover the withdrawal. 4. **Transfer out**: `amountOut` is sent to `_receiver`; `fee` is sent to the insurance fund. `totalSupplies[asset]` is decremented. ### Redeeming cUSD Proportional withdrawal across every backing asset: 1. **Amount calculation**: The Minter computes proportional `amountsOut` and `fees` for each asset in the vault. 2. **cUSD burn**: `_amountIn` cUSD is burned from `msg.sender`. 3. **Divest many**: The FractionalReserve layer divests the required amounts across all assets. 4. **Transfer out**: For each asset, `amountsOut[i]` is sent to `_receiver` and `fees[i]` to the insurance fund. ### Borrowing and Repaying These paths are access-controlled and called only by the Lender contract: * **Borrow**: Divests the asset from the yield strategy if needed, decrements available balance, transfers to `_receiver`, increments `totalBorrows[asset]`. * **Repay**: Accepts the asset back from the Lender via `transferFrom`, decrements `totalBorrows[asset]`. ### Utilization Tracking The vault tracks a **cumulative utilization index** per asset — a time-weighted integral of the utilization ratio. This is consumed by the RateOracle to compute borrow interest rates. ``` utilizationIndex += utilization * (block.timestamp - lastUpdate) utilization = totalBorrows / totalSupplies (ray format, 1e27 = 100%) ``` The index is updated on every mint, burn, borrow, and repay via the `updateIndex` modifier. *** ## Architecture ### Core Functions #### `mint(address _asset, uint256 _amountIn, uint256 _minAmountOut, address _receiver, uint256 _deadline)` ```solidity function mint( address _asset, uint256 _amountIn, uint256 _minAmountOut, address _receiver, uint256 _deadline ) external returns (uint256 amountOut); ``` Deposit `_asset` and receive cUSD. Requires ERC20 approval from `msg.sender` to the vault. `_amountIn` is silently reduced to the remaining deposit cap if exceeded. | Parameter | Type | Description | | --------------- | --------- | --------------------------------------------- | | `_asset` | `address` | Whitelisted backing asset to deposit | | `_amountIn` | `uint256` | Amount of asset to deposit | | `_minAmountOut` | `uint256` | Minimum cUSD to receive (slippage protection) | | `_receiver` | `address` | Recipient of the minted cUSD | | `_deadline` | `uint256` | Unix timestamp after which the tx reverts | **Returns**: `amountOut` — cUSD minted to `_receiver` (excludes fee). *** #### `burn(address _asset, uint256 _amountIn, uint256 _minAmountOut, address _receiver, uint256 _deadline)` ```solidity function burn( address _asset, uint256 _amountIn, uint256 _minAmountOut, address _receiver, uint256 _deadline ) external returns (uint256 amountOut); ``` Burn `_amountIn` cUSD and receive `_asset`. The caller must hold the cUSD. | Parameter | Type | Description | | --------------- | --------- | ---------------------------------------------- | | `_asset` | `address` | Backing asset to withdraw | | `_amountIn` | `uint256` | Amount of cUSD to burn | | `_minAmountOut` | `uint256` | Minimum asset to receive (slippage protection) | | `_receiver` | `address` | Recipient of the asset | | `_deadline` | `uint256` | Unix timestamp after which the tx reverts | **Returns**: `amountOut` — asset sent to `_receiver` (excludes fee). *** #### `redeem(uint256 _amountIn, uint256[] calldata _minAmountsOut, address _receiver, uint256 _deadline)` ```solidity function redeem( uint256 _amountIn, uint256[] calldata _minAmountsOut, address _receiver, uint256 _deadline ) external returns (uint256[] memory amountsOut); ``` Burn `_amountIn` cUSD and receive a proportional share of every backing asset. `_minAmountsOut` must have one entry per vault asset in the same order as `assets()`. **Returns**: `amountsOut` — asset amounts sent to `_receiver` (one per vault asset). *** #### `borrow(address _asset, uint256 _amount, address _receiver)` ```solidity function borrow(address _asset, uint256 _amount, address _receiver) external; ``` Access-controlled. Called by the Lender to transfer assets to an Operator. Reverts with `InsufficientReserves` if available balance is too low. *** #### `repay(address _asset, uint256 _amount)` ```solidity function repay(address _asset, uint256 _amount) external; ``` Access-controlled. Called by the Lender when an Operator repays. Pulls `_amount` from `msg.sender` via `transferFrom`. *** #### `availableBalance(address _asset)` ```solidity function availableBalance(address _asset) external view returns (uint256 amount); ``` Returns `totalSupplies[_asset] - totalBorrows[_asset]` — the amount currently available to borrow or withdraw. *** #### `utilization(address _asset)` ```solidity function utilization(address _asset) external view returns (uint256 ratio); ``` Returns the current utilization ratio in ray format (`1e27 = 100%`). For example, `5e26` = 50% utilization. *** #### `currentUtilizationIndex(address _asset)` ```solidity function currentUtilizationIndex(address _asset) external view returns (uint256 index); ``` Returns the up-to-date cumulative utilization index including the current unsettled period. Used by the RateOracle for interest rate calculations. *** #### `getRemainingMintCapacity(address _asset)` ```solidity function getRemainingMintCapacity(address _asset) external view returns (uint256 remainingMintCapacity); ``` Returns how much more of `_asset` can be deposited before hitting the deposit cap. Returns 0 if the cap is already reached. *** #### Admin Functions | Function | Description | | ------------------------------------------------ | ----------------------------------------------------------------------- | | `addAsset(address _asset)` | Add a new backing asset to the vault | | `removeAsset(address _asset)` | Remove an asset (only if `totalSupplies == 0`) | | `pauseAsset(address _asset)` | Pause minting, burning, and borrowing for a specific asset | | `unpauseAsset(address _asset)` | Resume operations for a paused asset | | `pauseProtocol()` | Pause all vault operations globally | | `unpauseProtocol()` | Resume all vault operations | | `setInsuranceFund(address)` | Update the insurance fund address | | `rescueERC20(address _asset, address _receiver)` | Recover a non-vault, non-strategy token sent to the contract by mistake | *** ### Data Structures #### `VaultStorage` ERC-7201 namespaced storage for the Vault module. ```solidity struct VaultStorage { EnumerableSet.AddressSet assets; mapping(address => uint256) totalSupplies; mapping(address => uint256) totalBorrows; mapping(address => uint256) utilizationIndex; mapping(address => uint256) lastUpdate; mapping(address => bool) paused; address insuranceFund; } ``` | Field | Type | Description | | ------------------ | ----------------------------- | ----------------------------------------------------------- | | `assets` | `EnumerableSet.AddressSet` | Set of whitelisted backing assets | | `totalSupplies` | `mapping(address => uint256)` | Total asset deposited (principal, not accounting for yield) | | `totalBorrows` | `mapping(address => uint256)` | Total asset currently borrowed by Operators | | `utilizationIndex` | `mapping(address => uint256)` | Cumulative time-weighted utilization integral per asset | | `lastUpdate` | `mapping(address => uint256)` | Timestamp of the last index update per asset | | `paused` | `mapping(address => bool)` | Per-asset pause state | | `insuranceFund` | `address` | Address that receives minting/burning fees in cUSD | *** #### `MintBurnParams` ```solidity struct MintBurnParams { address asset; uint256 amountIn; uint256 amountOut; uint256 minAmountOut; address receiver; uint256 deadline; uint256 fee; } ``` #### `RedeemParams` ```solidity struct RedeemParams { uint256 amountIn; uint256[] amountsOut; uint256[] minAmountsOut; address receiver; uint256 deadline; uint256[] fees; } ``` *** ### Events | Event | Key Parameters | Emitted when | | -------------- | --------------------------------------------------- | ------------------------------- | | `Mint` | `minter, receiver, asset, amountIn, amountOut, fee` | cUSD minted | | `Burn` | `burner, receiver, asset, amountIn, amountOut, fee` | cUSD burned for a single asset | | `Redeem` | `redeemer, receiver, amountIn, amountsOut, fees` | cUSD redeemed across all assets | | `Borrow` | `borrower, asset, amount` | Operator borrow executed | | `Repay` | `repayer, asset, amount` | Operator repayment received | | `AddAsset` | `asset` | New backing asset added | | `RemoveAsset` | `asset` | Backing asset removed | | `PauseAsset` | `asset` | Asset paused | | `UnpauseAsset` | `asset` | Asset unpaused | *** ### Errors | Error | Condition | | ----------------------- | -------------------------------------------------------- | | `PastDeadline` | `block.timestamp > deadline` | | `Slippage` | `amountOut < minAmountOut` | | `InvalidAmount` | `amountOut == 0` | | `AssetPaused` | Mint/burn/borrow attempted on a paused asset | | `AssetNotSupported` | Asset is not in the vault's asset list | | `AssetAlreadySupported` | `addAsset` called for an already-listed asset | | `AssetHasSupplies` | `removeAsset` called while `totalSupplies > 0` | | `AssetNotRescuable` | `rescueERC20` called for a listed or strategy-held asset | | `InvalidMinAmountsOut` | `_minAmountsOut.length` doesn't match `assets().length` | | `InsufficientReserves` | Available balance is less than the amount requested | *** ## Usage Examples ### 1. Minting cUSD ```solidity interface IVault { function mint(address _asset, uint256 _amountIn, uint256 _minAmountOut, address _receiver, uint256 _deadline) external returns (uint256 amountOut); function getMintAmount(address _user, address _asset, uint256 _amountIn) external view returns (uint256 amountOut, uint256 fee); } address vault = 0x...; // cUSD vault proxy address usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; uint256 amountIn = 10_000e6; // 10,000 USDC // 1. Preview the mint (uint256 expectedOut, ) = IVault(vault).getMintAmount(msg.sender, usdc, amountIn); // 2. Approve and mint IERC20(usdc).approve(vault, amountIn); uint256 cusdReceived = IVault(vault).mint( usdc, amountIn, expectedOut * 99 / 100, // 1% slippage tolerance msg.sender, block.timestamp + 5 minutes ); ``` ### 2. Checking vault utilization before borrowing ```solidity interface IVault { function availableBalance(address _asset) external view returns (uint256); function utilization(address _asset) external view returns (uint256 ratio); function totalSupplies(address _asset) external view returns (uint256); function totalBorrows(address _asset) external view returns (uint256); } function vaultStatus(address vault, address asset) external view returns (uint256 available, uint256 utilizationPct) { available = IVault(vault).availableBalance(asset); utilizationPct = IVault(vault).utilization(asset) / 1e25; // convert ray to bps (1e27 → 100%) } ``` ### 3. Redeeming cUSD across all assets ```solidity interface IVault { function assets() external view returns (address[] memory); function getRedeemAmount(address _user, uint256 _amountIn) external view returns (uint256[] memory amountsOut, uint256[] memory fees); function redeem(uint256 _amountIn, uint256[] calldata _minAmountsOut, address _receiver, uint256 _deadline) external returns (uint256[] memory amountsOut); } address vault = 0x...; uint256 cusdAmount = 5_000e18; // Preview (uint256[] memory expected, ) = IVault(vault).getRedeemAmount(msg.sender, cusdAmount); // Apply 1% slippage tolerance to each asset uint256[] memory minOut = new uint256[](expected.length); for (uint256 i; i < expected.length; i++) { minOut[i] = expected[i] * 99 / 100; } IVault(vault).redeem(cusdAmount, minOut, msg.sender, block.timestamp + 5 minutes); ``` # Minter The Minter is an abstract contract inherited by the Cap vault that handles fee calculation and routing for minting, burning, and redeeming cUSD. Dynamic fees are applied based on each backing asset's current allocation relative to its optimal ratio, incentivising deposits that balance the reserve and penalising those that over-concentrate it. Whitelisted addresses bypass all dynamic fees, and a flat redeem fee applies when burning cUSD proportionally across all backing assets. ## Mechanics ### Dynamic Mint/Burn Fees Every cUSD mint or burn is priced using oracle-based valuations of the input asset and the cUSD token itself. After computing a pre-fee output amount, the contract calculates the **new ratio** — the asset's share of the total basket value after the swap — and runs it through a kinked piecewise-linear fee schedule. **Mint fee zones** (based on post-mint asset ratio): 1. **Below or at `optimalRatio`**: Only `minMintFee` applies (a flat floor, capped at 5%, typically 10 bps). 2. **Between `optimalRatio` and `mintKinkRatio`**: Fee rises linearly from `minMintFee` toward `minMintFee + slope0`. 3. **Above `mintKinkRatio`**: Fee steepens further, adding `slope1` proportional to the excess above the kink. **Burn fee zones** (based on post-burn asset ratio): 1. **At or above `optimalRatio`**: Zero fee — burning a well-allocated asset is always free. 2. **Between `burnKinkRatio` and `optimalRatio`**: Fee rises linearly using `slope0`. 3. **Below `burnKinkRatio`**: Fee steepens using `slope1` proportional to the shortfall below the kink. All rates, ratios, and fees are expressed in **ray format** where `1e27 = 100%`. For example, a `minMintFee` of `1e24` is 0.1% (10 bps). ### Mint/Burn Process Flow 1. **Pre-fee amount**: `_amountOutBeforeFee` fetches oracle prices for the asset and cUSD, computes the raw output amount, and derives the post-swap allocation ratio. 2. **Whitelist check**: If `$.whitelist[user]` is `true`, the pre-fee amount is returned unchanged with zero fee. 3. **Fee application**: For non-whitelisted users, `_applyFeeSlopes` selects the correct zone from the kinked curve, computes the fee in ray arithmetic, and deducts it from the output. 4. **Return**: `(amountOut, fee)` is returned to the calling vault for execution. ### Redeem Process Flow Redeeming burns cUSD in exchange for a **proportional slice of every backing asset** in the vault, at the current basket weights. This path avoids dynamic mint/burn fees entirely but applies a flat `redeemFee`. 1. A `shares` ratio is computed: `cUSD burned / total cUSD supply`, scaled to `1e33` precision. 2. For each asset in the vault, the user's proportional entitlement is `totalSupplies(asset) × shares / 1e33`. 3. If the user is whitelisted, `redeemFee` is set to zero; otherwise the flat fee is deducted from each asset amount. 4. Arrays of `amountsOut` and `fees` (one entry per asset) are returned. ### Deposit Caps Each backing asset has an independent deposit cap (`depositCap[asset]`). Deposits that would push total supply beyond this cap revert. A cap of `0` means unlimited. ### Whitelisting Whitelisted addresses receive fee-free minting, burning, and redeeming. This is intended for protocol-controlled addresses (e.g. the insurance fund, authorised integrators). The whitelist is managed by the access-controlled `setWhitelist` function. *** ## Architecture ### Core Functions #### `getMintAmount(address _asset, uint256 _amountIn)` ```solidity function getMintAmount(address _asset, uint256 _amountIn) external view returns (uint256 amountOut, uint256 fee); ``` Simulates a mint for `msg.sender`. Returns the cUSD amount received and the fee charged given the current basket state. | Parameter | Type | Description | | ----------- | --------- | --------------------------------- | | `_asset` | `address` | The backing asset being deposited | | `_amountIn` | `uint256` | Amount of `_asset` to deposit | **Returns**: `amountOut` — cUSD minted after fees; `fee` — cUSD equivalent of the fee deducted. *** #### `getMintAmount(address _user, address _asset, uint256 _amountIn)` ```solidity function getMintAmount(address _user, address _asset, uint256 _amountIn) external view returns (uint256 amountOut, uint256 fee); ``` Same as above but simulates for an arbitrary `_user` address. Use this overload when quoting on behalf of another address (e.g. checking whether a specific wallet is whitelisted). | Parameter | Type | Description | | ----------- | --------- | ----------------------------------------- | | `_user` | `address` | Address whose whitelist status is applied | | `_asset` | `address` | The backing asset being deposited | | `_amountIn` | `uint256` | Amount of `_asset` to deposit | *** #### `getBurnAmount(address _asset, uint256 _amountIn)` ```solidity function getBurnAmount(address _asset, uint256 _amountIn) external view returns (uint256 amountOut, uint256 fee); ``` Simulates burning `_amountIn` cUSD to receive `_asset`. Uses `msg.sender` for the whitelist check. | Parameter | Type | Description | | ----------- | --------- | ---------------------------- | | `_asset` | `address` | The backing asset to receive | | `_amountIn` | `uint256` | Amount of cUSD to burn | **Returns**: `amountOut` — asset amount received after fees; `fee` — fee in cUSD terms. *** #### `getBurnAmount(address _user, address _asset, uint256 _amountIn)` ```solidity function getBurnAmount(address _user, address _asset, uint256 _amountIn) external view returns (uint256 amountOut, uint256 fee); ``` Same as above but simulates for an arbitrary `_user`. *** #### `getRedeemAmount(uint256 _amountIn)` ```solidity function getRedeemAmount(uint256 _amountIn) external view returns (uint256[] memory amountsOut, uint256[] memory redeemFees); ``` Simulates redeeming `_amountIn` cUSD for a proportional share of every backing asset. Uses `msg.sender` for the whitelist check. | Parameter | Type | Description | | ----------- | --------- | ------------------------ | | `_amountIn` | `uint256` | Amount of cUSD to redeem | **Returns**: `amountsOut` — array of asset amounts (one per vault asset, in vault asset order); `redeemFees` — flat fee deducted per asset. *** #### `getRedeemAmount(address _user, uint256 _amountIn)` ```solidity function getRedeemAmount(address _user, uint256 _amountIn) external view returns (uint256[] memory amountsOut, uint256[] memory redeemFees); ``` Same as above but simulates for an arbitrary `_user`. *** #### `getFeeData(address _asset)` ```solidity function getFeeData(address _asset) external view returns (FeeData memory feeData); ``` Returns the current fee schedule for `_asset`. *** #### `setFeeData(address _asset, FeeData calldata _feeData)` ```solidity function setFeeData(address _asset, FeeData calldata _feeData) external; ``` Updates the fee schedule for `_asset`. Access-controlled. Reverts with: * `InvalidMinMintFee` if `minMintFee >= 0.05e27` (>= 5%) * `InvalidMintKinkRatio` if `mintKinkRatio == 0` or `>= 1e27` * `InvalidBurnKinkRatio` if `burnKinkRatio == 0` or `>= 1e27` * `InvalidOptimalRatio` if `optimalRatio == 0`, `>= 1e27`, or equals either kink *** #### `getRedeemFee()` ```solidity function getRedeemFee() external view returns (uint256 redeemFee); ``` Returns the current flat redeem fee in ray format (`1e27 = 100%`). *** #### `setRedeemFee(uint256 _redeemFee)` ```solidity function setRedeemFee(uint256 _redeemFee) external; ``` Sets the flat redeem fee. Access-controlled. Emits `SetRedeemFee`. *** #### `setWhitelist(address _user, bool _whitelisted)` ```solidity function setWhitelist(address _user, bool _whitelisted) external; ``` Grants or revokes fee-free access for `_user`. Access-controlled. Emits `SetWhitelist`. *** #### `setDepositCap(address _asset, uint256 _cap)` ```solidity function setDepositCap(address _asset, uint256 _cap) external; ``` Sets the maximum total deposit allowed for `_asset`. `_cap = 0` means no limit. Access-control
프로젝트로 돌아가기