Cap 백서

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

tract. Inherited by the central `Oracle` contract. #### `marketRate(address _asset)` ```solidity function marketRate(address _asset) external returns (uint256 rate); ``` Returns the current market rate for `_asset` in ray format (`1e27 = 100%` annualised). Calls the configured market adapter (e.g. AaveAdapter). Returns zero if the adapter fails. *** #### `utilizationRate(address _asset)` ```solidity function utilizationRate(address _asset) external returns (uint256 rate); ``` Returns the utilization-based interest rate for `_asset` in ray. Calls the configured utilization adapter (VaultAdapter). This is the rate Operators pay on borrowed vault principal. *** #### Admin Functions | Function | Description | | ------------------------------------------------------ | ---------------------------------------------------- | | `setMarketOracleData(address _asset, OracleData)` | Configure the market rate adapter + payload | | `setUtilizationOracleData(address _asset, OracleData)` | Configure the utilization rate adapter + payload | | `setBenchmarkRate(address _asset, uint256 _rate)` | Set a manual benchmark rate floor (ray) | | `setRestakerRate(address _agent, uint256 _rate)` | Set the restaker interest rate for an Operator (ray) | *** #### View Functions | Function | Returns | Description | | -------------------------------- | --------------- | ------------------------------------- | | `benchmarkRate(address)` | `uint256` (ray) | Manually set rate floor for the asset | | `restakerRate(address)` | `uint256` (ray) | Per-Operator restaker interest rate | | `marketOracleData(address)` | `OracleData` | Market adapter + payload | | `utilizationOracleData(address)` | `OracleData` | Utilization adapter + payload | *** ### Data Structures #### `OracleData` ```solidity struct OracleData { address adapter; bytes payload; } ``` | Field | Description | | --------- | ------------------------------------------------------------------------------ | | `adapter` | Contract or library address called via `staticcall` (prices) or `call` (rates) | | `payload` | ABI-encoded calldata passed directly to the adapter | *** ## Price Adapters ### ChainlinkAdapter Reads a Chainlink price feed aggregator. Normalizes the returned value to 8 decimals regardless of the feed's native decimals. **Payload**: `abi.encodeCall(ChainlinkAdapter.price, (_source))` where `_source` is the Chainlink aggregator address. **Returns**: `(uint256 price, uint256 lastUpdated)` — price in 8 decimals, `lastUpdated` from `latestRoundData`. *** ### ChainlinkAdapterChained Multiplies multiple Chainlink feeds together to derive a cross-rate. For example, to price an asset quoted in ETH: feed `A/ETH` × feed `ETH/USD`. The final price is normalized to 8 decimals; `lastUpdated` is the minimum across all feeds (most conservative). **Payload**: `abi.encodeCall(ChainlinkAdapterChained.price, (_sources))` where `_sources` is an array of aggregator addresses. *** ### wstETHAdapter Prices wstETH by reading the stETH/USD Chainlink feed and multiplying by the stETH-to-wstETH conversion ratio from the Lido contract (`getPooledEthByShares(1 ether)`). **Payload**: `abi.encodeCall(wstETHAdapter.price, (_source, _stETH))` where `_source` is the stETH Chainlink aggregator and `_stETH` is the stETH token address. *** ### CapTokenAdapter Prices a cUSD vault token (e.g. cUSD itself) as the weighted average of its backing assets: ``` price = Σ(totalSupplies[asset] × assetPrice / 10^assetDecimals) / capTokenSupply × 10^capDecimals ``` Calls back into the Oracle via `msg.sender` to get each underlying asset's price. `lastUpdated` is the minimum across all underlying prices. Returns `1e8` if supply is zero. **Payload**: `abi.encodeCall(CapTokenAdapter.price, (_asset))` where `_asset` is the Cap vault token address. *** ### StakedCapAdapter Prices stcUSD (staked cUSD) by reading the cUSD price and multiplying by the `convertToAssets` ratio of the ERC4626 staking vault: ``` price = capTokenPrice × convertToAssets(1e18) / 1e18 ``` **Payload**: `abi.encodeCall(StakedCapAdapter.price, (_asset))` where `_asset` is the stcUSD address. *** ### FixedPriceOracle A standalone contract (not a library) that always returns `1e8` (1 USD). Used for stablecoins or test deployments. **Payload**: `abi.encodeCall(FixedPriceOracle.price, ())` — no parameters. *** ### UniswapV3Adapter On-chain TWAP oracle using Uniswap V3 pool observations. Supports chained routes (e.g. `TOKEN → WETH → USDC`) to derive prices for any token with sufficient liquidity. **Payload**: `abi.encode(tokens[], pools[], twapPeriods[])` where: * `tokens` — ordered token route (length = `pools.length + 1`) * `pools` — Uniswap V3 pool addresses for each hop * `twapPeriods` — TWAP window in seconds per hop The first token in the route must already have a registered price in the Oracle (used as the base price). The adapter validates the route via `validateData` before the payload is stored. *** ## Rate Adapters ### AaveAdapter Reads Aave's `getReserveData` to fetch the current variable borrow rate for an asset. Used as a market rate benchmark. **Payload**: `abi.encodeCall(AaveAdapter.rate, (_aaveDataProvider, _asset))`. *** ### VaultAdapter Computes a utilization-based interest rate using Cap's own vault utilization history. This is the primary rate source for vault interest. The adapter tracks a per-vault per-asset **utilization snapshot** (`index`, `lastUpdate`) and computes the time-weighted average utilization since the last call. The rate is determined by a two-slope model with a dynamic multiplier: * **Below kink**: rate = `slope0 × utilization / kink × multiplier`. Multiplier decays when utilization is low. * **Above kink**: rate = `(slope0 + slope1 × excess) × multiplier`. Multiplier grows when utilization is high. The multiplier is bounded by `[minMultiplier, maxMultiplier]` and adjusts at speed `rate` (ray per second). #### Admin Functions | Function | Description | | ------------------------------------------------------ | ------------------------------------------ | | `setSlopes(address _asset, SlopeData)` | Configure the two-slope curve for an asset | | `setLimits(uint256 _max, uint256 _min, uint256 _rate)` | Set multiplier bounds and adjustment speed | #### `SlopeData` ```solidity struct SlopeData { uint256 slope0; // ray — base rate at kink uint256 slope1; // ray — additional rate above kink per unit of excess uint256 kink; // ray — utilization ratio that separates the two slopes } ``` *** ## Usage Examples ### 1. Reading an asset price ```solidity interface IOracle { function getPrice(address _asset) external view returns (uint256 price, uint256 lastUpdated); } address oracle = 0x...; address usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; (uint256 price, uint256 updatedAt) = IOracle(oracle).getPrice(usdc); // price = 1_0000_0000 (1.00 USD, 8 decimals) uint256 usdValue = amount * price / 10 ** 6; // USDC has 6 decimals ``` *** ### 2. Configuring a Chainlink price feed ```solidity interface IOracle { function setPriceOracleData(address _asset, OracleData calldata) external; function setPriceBackupOracleData(address _asset, OracleData calldata) external; function setStaleness(address _asset, uint256 _staleness) external; } struct OracleData { address adapter; bytes payload; } address oracle = 0x...; address chainlinkAdapter = 0x...; address wbtcFeed = 0x...; // Chainlink WBTC/USD aggregator address wbtc = 0x...; // WBTC token // Primary: Chainlink WBTC/USD IOracle(oracle).setPriceOracleData(wbtc, OracleData({ adapter: chainlinkAdapter, payload: abi.encodeWithSignature("price(address)", wbtcFeed) })); // Allow up to 1 hour staleness IOracle(oracle).setStaleness(wbtc, 3600); ``` *** ### 3. Setting a restaker rate for an Operator ```solidity interface IOracle { function setRestakerRate(address _agent, uint256 _rate) external; function restakerRate(address _agent) external view returns (uint256); } address oracle = 0x...; address operator = 0x...; // Set 5% annual restaker rate (ray = 1e27) IOracle(oracle).setRestakerRate(operator, 0.05e27); // Verify uint256 rate = IOracle(oracle).restakerRate(operator); // rate = 5e25 (5% in ray) ``` # Access Controls Cap uses a two-contract access control system. The `AccessControl` contract is the single authority that maps `(function selector, contract address)` pairs to addresses that are allowed to call them. The `Access` abstract contract is a thin mixin inherited by every Cap contract — it provides the `checkAccess` modifier that calls out to `AccessControl` to validate each privileged operation. This architecture gives Cap fine-grained, per-function permissioning across the entire protocol with a single upgradeable registry. ## Mechanics ### Role Derivation Every permission in the system is represented as an OpenZeppelin role — a `bytes32` identifier. The role for a given `(selector, contract)` pair is computed as: ```solidity roleId = bytes32(selector) | bytes32(uint256(uint160(contract))); ``` The selector occupies the top 4 bytes; the contract address fills the lower 20 bytes. This means two functions with the same selector on different contracts get distinct roles automatically. ### Granting and Revoking Access `grantAccess` and `revokeAccess` are themselves access-controlled — only addresses holding the `role(grantAccess.selector, AccessControl)` role can modify permissions. The deployer (initial admin) receives: * `DEFAULT_ADMIN_ROLE` (OpenZeppelin admin role) * The role to call `grantAccess` on `AccessControl` * The role to call `revokeAccess` on `AccessControl` Self-revocation of the `revokeAccess` role is blocked — an admin cannot accidentally lock themselves out by revoking their own revocation privilege. ### `checkAccess` Modifier Every privileged function in Cap contracts uses the `checkAccess` modifier: ```solidity modifier checkAccess(bytes4 _selector) { _checkAccess(_selector); _; } ``` `_checkAccess` calls `IAccessControl.checkAccess(_selector, address(this), msg.sender)` on the stored `accessControl` address. If the caller does not hold the required role, the call reverts with `AccessDenied`. There are no owner or operator patterns — all access is role-based. The `bytes4(0)` selector is conventionally used for UUPS upgrade authorization (`_authorizeUpgrade`) across all upgradeable Cap contracts. *** ## Architecture ### AccessControl ```solidity contract AccessControl is IAccessControl, UUPSUpgradeable, AccessControlEnumerableUpgradeable ``` The central permissions registry. UUPS upgradeable; upgrade requires `DEFAULT_ADMIN_ROLE`. #### `initialize(address _admin)` ```solidity function initialize(address _admin) external initializer; ``` Bootstraps the contract. Grants `DEFAULT_ADMIN_ROLE` and both `grantAccess` / `revokeAccess` roles to `_admin`. *** #### `grantAccess(bytes4 _selector, address _contract, address _address)` ```solidity function grantAccess(bytes4 _selector, address _contract, address _address) external; ``` Grants `_address` permission to call `_selector` on `_contract`. Requires the caller to hold the `grantAccess` role on this `AccessControl` contract. | Parameter | Type | Description | | ----------- | --------- | ------------------------------------ | | `_selector` | `bytes4` | Function selector being permissioned | | `_contract` | `address` | Contract on which the function lives | | `_address` | `address` | Address being granted access | *** #### `revokeAccess(bytes4 _selector, address _contract, address _address)` ```solidity function revokeAccess(bytes4 _selector, address _contract, address _address) external; ``` Revokes `_address`'s permission to call `_selector` on `_contract`. Cannot be used to revoke the caller's own `revokeAccess` role (reverts with `CannotRevokeSelf`). *** #### `checkAccess(bytes4 _selector, address _contract, address _caller)` ```solidity function checkAccess(bytes4 _selector, address _contract, address _caller) external view returns (bool hasAccess); ``` Verifies that `_caller` holds the role for `(_selector, _contract)`. Reverts (via OpenZeppelin `_checkRole`) if they do not. Returns `true` if access is granted. *** #### `role(bytes4 _selector, address _contract)` ```solidity function role(bytes4 _selector, address _contract) public pure returns (bytes32 roleId); ``` Computes the role identifier for a `(selector, contract)` pair. Pure function — can be called off-chain to compute role IDs for `grantAccess` / `revokeAccess`. *** ### Access (mixin) ```solidity abstract contract Access is IAccess, Initializable, AccessStorageUtils ``` Inherited by every Cap contract that has privileged functions. Stores the `accessControl` address and exposes the `checkAccess` modifier. #### `__Access_init(address _accessControl)` Called from each contract's `initialize`. Stores the `AccessControl` contract address in ERC-7201 namespaced storage. *** ## Usage Examples ### 1. Granting a keeper permission to call `realizeInterest` ```solidity interface IAccessControl { function grantAccess(bytes4 _selector, address _contract, address _address) external; function role(bytes4 _selector, address _contract) external pure returns (bytes32); } address accessControl = 0x...; address lender = 0x...; address keeper = 0x...; bytes4 selector = ILender.realizeInterest.selector; // Grant the keeper permission to call realizeInterest on the Lender IAccessControl(accessControl).grantAccess(selector, lender, keeper); ``` *** ### 2. Revoking a deprecated admin address ```solidity interface IAccessControl { function revokeAccess(bytes4 _selector, address _contract, address _address) external; function role(bytes4 _selector, address _contract) external pure returns (bytes32); } address accessControl = 0x...; address delegation = 0x...; address oldAdmin = 0x...; // Revoke permission to call addAgent on the Delegation contract bytes4 selector = IDelegation.addAgent.selector; IAccessControl(accessControl).revokeAccess(selector, delegation, oldAdmin); ``` *** ### 3. Timelock Critical admin operations are executed through an OpenZeppelin [TimelockController](https://docs.openzeppelin.com/contracts/5.x/api/governance#TimelockController) deployed at [`0xD8236031d8279d82E615aF2BFab5FC0127A329ab`](https://etherscan.io/address/0xD8236031d8279d82E615aF2BFab5FC0127A329ab). The Timelock holds roles in Cap's AccessControl system like any other permissioned address — the difference is that all calls from the Timelock must first be scheduled and wait a minimum delay before execution. | Parameter | Value | | --------- | --------------------------------- | | Min Delay | 86,400 seconds (1 day) | | Type | OpenZeppelin `TimelockController` | The Timelock follows the standard OZ lifecycle: 1. **Schedule** — `schedule()` or `scheduleBatch()` queues an operation with at least `minDelay` seconds of waiting time 2. **Wait** — the operation cannot be executed until the delay has elapsed 3. **Execute** — `execute()` or `executeBatch()` runs the queued operation 4. **Cancel** (optional) — `cancel()` removes a pending operation before execution For full interface details, see the [OpenZeppelin TimelockController documentation](https://docs.openzeppelin.com/contracts/5.x/api/governance#TimelockController). *** ### 4. Checking access off-chain (role ID calculation) ```solidity interface IAccessControl { function role(bytes4 _selector, address _contract) external pure returns (bytes32 roleId); function hasRole(bytes32 role, address account) external view returns (bool); } address accessControl = 0x...; address vault = 0x...; address addr = 0x...; bytes4 selector = IVault.addAsset.selector; bytes32 roleId = IAccessControl(accessControl).role(selector, vault); bool canAddAsset = IAccessControl(accessControl).hasRole(roleId, addr); ``` # Tokens Cap has three token contracts: **cUSD** (the backing stablecoin vault), **stcUSD** (the yield-bearing staked version), and **L2Token** (a LayerZero OFT for cross-chain bridging). cUSD and stcUSD are deployed on mainnet; L2Token is deployed on destination chains. ## cUSD — CapToken `CapToken` is the cUSD stablecoin. It is a UUPS upgradeable contract that inherits the full `Vault`, `Minter`, and `FractionalReserve` modules — see those pages for the complete function reference. The token itself is an ERC20 whose supply is backed 1:1 (plus protocol fees) by a basket of whitelisted backing assets. **Key properties**: * Minted by depositing backing assets (`mint`) * Burned to withdraw backing assets (`burn`) or proportionally across all assets (`redeem`) * Supply is managed by the Vault module — no direct `mint`/`burn` by admin * Price is the weighted average of underlying asset values (via `CapTokenAdapter`) ### `initialize` ```solidity function initialize( string memory _name, string memory _symbol, address _accessControl, address _feeAuction, address _oracle, address[] calldata _assets, address _insuranceFund ) external initializer; ``` | Parameter | Description | | ------------------- | ------------------------------------------------------ | | `_name` / `_symbol` | ERC20 name and symbol (e.g. "Cap USD", "cUSD") | | `_accessControl` | AccessControl contract address | | `_feeAuction` | FeeAuction address — receives fractional reserve yield | | `_oracle` | Oracle contract address | | `_assets` | Initial list of whitelisted backing assets | | `_insuranceFund` | Receives mint/burn fees in cUSD | *** ## stcUSD — StakedCap `StakedCap` is a UUPS upgradeable ERC4626 vault that accepts cUSD deposits and distributes protocol yield to holders. Yield accrues as the Lender realizes vault interest and transfers cUSD to this contract. A **profit-locking** mechanism prevents flashloan manipulation by vesting newly notified yield linearly over `lockDuration` seconds. ### Mechanics #### Deposit and Withdrawal StakedCap is a standard ERC4626: deposit cUSD, receive stcUSD shares proportional to the current exchange rate. Withdraw shares to receive cUSD plus accrued yield. ``` sharePrice = totalAssets() / totalSupply() totalAssets() = storedTotal - lockedProfit() ``` `storedTotal` is the raw cUSD balance held by the contract. `lockedProfit()` is the portion of the most recent yield notification still vesting — it decays linearly to zero over `lockDuration`. #### `notify()` ```solidity function notify() external; ``` Permissionless. Snapshots the current balance above `storedTotal` as new locked profit and starts the vesting timer. Reverts with `StillVesting` if the previous yield batch has not fully unlocked yet — this prevents yield dilution by stacking notifications. **Typical flow**: The FeeAuction's `paymentRecipient` is the StakedCap contract. After a buyer purchases auction assets, cUSD flows to StakedCap. Any keeper (or the buyer themselves) then calls `notify()` to begin vesting. #### `lockedProfit()` ```solidity function lockedProfit() external view returns (uint256 locked); ``` Returns the portion of the last notified yield still locked. Decays linearly from `totalLocked` at `lastNotify` to zero at `lastNotify + lockDuration`. ``` lockedProfit = totalLocked × (lockDuration - elapsed) / lockDuration ``` Returns zero if `elapsed ≥ lockDuration`. *** ### View Functions | Function | Returns | Description | | ---------------- | --------- | -------------------------------------------------------------- | | `totalAssets()` | `uint256` | `storedTotal - lockedProfit()` — effective cUSD backing shares | | `lockedProfit()` | `uint256` | Yield still vesting (decays to 0 over `lockDuration`) | | `lastNotify()` | `uint256` | Timestamp of the most recent `notify()` call | | `lockDuration()` | `uint256` | Seconds over which newly notified yield vests | | `totalLocked()` | `uint256` | Total cUSD locked at the time of the last notify | *** ### `initialize` ```solidity function initia
프로젝트로 돌아가기