Cap 백서

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

| Description | | ---------------------------------- | ------------------------------------------------ | | `setLastBorrow(address)` | Records borrow timestamp (Lender only) | | `setLtvBuffer(uint256)` | Update the LTV safety buffer (ray, must be > 1%) | | `setFeeRecipient(address)` | Update the fallback reward recipient | | `setCoverageCap(address, uint256)` | Set a USD cap on an Operator's coverage | *** ### Data Structures #### `DelegationStorage` ```solidity struct DelegationStorage { EnumerableSet.AddressSet agents; mapping(address => AgentData) agentData; EnumerableSet.AddressSet networks; address oracle; uint256 epochDuration; uint256 ltvBuffer; address feeRecipient; mapping(address => uint256) coverageCap; } ``` | Field | Description | | --------------- | --------------------------------------------------------------------- | | `agents` | Set of all registered Operators | | `agentData` | Per-Operator config: network, LTV, liquidation threshold, last borrow | | `networks` | Set of all registered network middleware contracts | | `oracle` | Oracle contract used for price feeds (passed to network middleware) | | `epochDuration` | Epoch length in seconds — aligns with Symbiotic's slash window | | `ltvBuffer` | Minimum gap between LTV and liquidation threshold (ray, default 5%) | | `feeRecipient` | Receives rewards when an Operator has no active coverage | | `coverageCap` | Per-Operator USD cap on coverage | #### `AgentData` ```solidity struct AgentData { address network; uint256 ltv; uint256 liquidationThreshold; uint256 lastBorrow; } ``` | Field | Description | | ---------------------- | ------------------------------------------------------ | | `network` | Network middleware contract (EigenLayer or Symbiotic) | | `ltv` | Maximum loan-to-value ratio in ray (`1e27 = 100%`) | | `liquidationThreshold` | Health threshold triggering liquidation in ray | | `lastBorrow` | `block.timestamp` of the Operator's most recent borrow | *** ### EigenLayer Integration The EigenLayer integration consists of three contracts: **`EigenAgentManager`** — The per-Operator contract deployed when an Operator registers on EigenLayer. It tracks which EigenLayer operator address backs this Cap Operator and queries the AVS's allocation system for slashable collateral. **`EigenOperator`** — Manages an EigenLayer operator's registration into the Cap AVS (opt-in to the AVS, register operator sets, manage allocation delays). **`EigenServiceManager`** — The EigenLayer AVS entry point. Registered as the `ServiceManager` on EigenLayer. Handles slash execution by interacting with EigenLayer's `AllocationManager`. Key EigenLayer concepts: * Operators opt into the Cap AVS via `EigenServiceManager` * Delegators stake into EigenLayer strategies (e.g. stETH, EIGEN) and delegate to an EigenLayer operator * Slashable collateral is the USD value of delegated stake that Cap can slash via the `AllocationManager` *** ### Symbiotic Integration The Symbiotic integration consists of five contracts: **`SymbioticAgentManager`** — Tracks collateral for Operators backed by Symbiotic Delegators. Queries Symbiotic vault/delegator contracts for slashable amounts. **`SymbioticOperator`** — Handles Symbiotic operator registration, opt-in to vaults and networks. **`SymbioticNetwork`** — The Symbiotic network contract. Cap is registered as a Symbiotic network; this contract manages network-level configuration. **`SymbioticNetworkMiddleware`** — The primary integration point. Implements `coverage`, `slashableCollateral`, `slash`, and `distributeRewards` for the Symbiotic path. Aggregates collateral across all Symbiotic vaults that have allocated to Cap. **`CapSymbioticVaultFactory`** — Deploys new Symbiotic collateral vaults compatible with Cap's network. Delegators use these vaults to stake collateral that backs Cap Operators. *** ## Usage Examples ### 1. Querying an Operator's borrowing position ```solidity interface IDelegation { function coverage(address _agent) external view returns (uint256); function slashableCollateral(address _agent) external view returns (uint256); function ltv(address _agent) external view returns (uint256); function liquidationThreshold(address _agent) external view returns (uint256); } address delegation = 0x...; address operator = 0x...; uint256 coverageUsd = IDelegation(delegation).coverage(operator); // coverageUsd in USD with 8 decimals, e.g. 1_000_000e8 = $1M uint256 maxBorrowUsd = coverageUsd * IDelegation(delegation).ltv(operator) / 1e27; // maxBorrowUsd = how much USD value the Operator can borrow in total ``` ### 2. Admin: onboarding a new Operator ```solidity interface IDelegation { function registerNetwork(address _network) external; function addAgent(address _agent, address _network, uint256 _ltv, uint256 _liquidationThreshold) external; function setCoverageCap(address _agent, uint256 _coverageCap) external; } address delegation = 0x...; address network = 0x...; // SymbioticNetworkMiddleware or EigenAgentManager address operator = 0x...; // 1. Register the network if not already registered IDelegation(delegation).registerNetwork(network); // 2. Add the Operator: 80% LTV, 90% liquidation threshold, both in ray IDelegation(delegation).addAgent(operator, network, 0.8e27, 0.9e27); // 3. Set a $10M USD coverage cap IDelegation(delegation).setCoverageCap(operator, 10_000_000e8); ``` ### 3. Checking slash eligibility before liquidation ```solidity interface IDelegation { function slashableCollateral(address _agent) external view returns (uint256); function slashTimestamp(address _agent) external view returns (uint48); } interface ILender { function agent(address _agent) external view returns ( uint256, uint256 slashable, uint256 debt, uint256, uint256, uint256 health ); } address delegation = 0x...; address lender = 0x...; address operator = 0x...; (, uint256 slashable, uint256 debt,,, uint256 health) = ILender(lender).agent(operator); uint256 slashableRaw = IDelegation(delegation).slashableCollateral(operator); // health < 1e27 = undercollateralised, liquidation can be opened // slashableRaw > 0 = collateral exists to cover the liquidation ``` # Fee Auction The FeeAuction distributes protocol yield — collected as backing assets from Operator interest payments — to stcUSD holders via a Dutch auction mechanism. stcUSD holders bid cUSD at a continuously decaying price to purchase the accumulated backing assets at a discount, creating a fixed-rate yield experience. Each successful purchase resets the auction at double the settlement price, establishing a self-calibrating price discovery cycle. The FeeReceiver acts as the upstream collector, receiving vault interest from the Lender and holding it until the FeeAuction sweeps it. ## Mechanics ### Dutch Auction Price Curve The auction price decays linearly from `startPrice` to 10% of `startPrice` over `duration` seconds: ``` price = startPrice × (1 - 0.9 × elapsed / duration) ``` * At `t = 0`: price = `startPrice` (100%) * At `t = duration`: price = `startPrice × 0.1` (10%) * Price never reaches zero — it floors at 10% of the start price All price values are in the `paymentToken` (cUSD) with 18 decimals. ### Buy Flow 1. **Price check**: `currentPrice()` is compared against caller's `_maxPrice`. Reverts with `InvalidPrice` if `currentPrice > _maxPrice`. 2. **Validation**: Asset list must be non-empty and match `_minAmounts` length; `_receiver` must be non-zero; deadline must be in the future. 3. **New auction reset**: `startTimestamp` is set to `block.timestamp`; `startPrice` is set to `max(currentPrice × 2, minStartPrice)`. 4. **Asset transfer**: Full balances of each requested `_asset` held by the FeeAuction are transferred to `_receiver`. Reverts with `InsufficientBalance` if any asset balance is below `_minAmounts[i]`. 5. **Payment**: `currentPrice` in `paymentToken` is pulled from `msg.sender` and sent to `paymentRecipient` (the stcUSD distribution contract or treasury). ### Self-Calibrating Start Price Each successful purchase sets the next auction's `startPrice` to `2 × settlementPrice`. This means: * If buyers wait for a deep discount, the next auction starts low. * If buyers buy early, the next auction starts high. * The auction converges on a market-clearing rate for protocol yield. The `minStartPrice` floor prevents the auction from becoming trivially cheap during low-activity periods. ### Interest Flow End-to-End ``` Operator repays interest ↓ Lender sends vault interest to interestReceiver (FeeReceiver) ↓ FeeReceiver holds backing assets (USDC, wETH, etc.) ↓ Buyer calls buy() on FeeAuction, pays cUSD at current price ↓ Buyer receives backing assets; cUSD goes to paymentRecipient ↓ paymentRecipient distributes yield to stcUSD holders ``` *** ## Architecture ### FeeAuction #### Core Functions **`buy(uint256 _maxPrice, address[] _assets, uint256[] _minAmounts, address _receiver, uint256 _deadline)`** ```solidity function buy( uint256 _maxPrice, address[] calldata _assets, uint256[] calldata _minAmounts, address _receiver, uint256 _deadline ) external; ``` Purchase all accumulated fee assets at the current Dutch auction price. | Parameter | Type | Description | | ------------- | ----------- | ----------------------------------------------------------------------- | | `_maxPrice` | `uint256` | Maximum cUSD to pay; reverts if `currentPrice > _maxPrice` | | `_assets` | `address[]` | List of backing assets to receive from the auction contract | | `_minAmounts` | `uint256[]` | Minimum balance of each asset to accept (slippage protection per asset) | | `_receiver` | `address` | Address to receive the purchased backing assets | | `_deadline` | `uint256` | Unix timestamp after which the tx reverts | *** **`currentPrice()`** ```solidity function currentPrice() external view returns (uint256 price); ``` Returns the current auction price in `paymentToken` units. Decays linearly from `startPrice` to `startPrice × 0.1` over `duration`. Use this before calling `buy` to set `_maxPrice`. *** #### Admin Functions | Function | Description | | --------------------------- | ------------------------------------------------------------------ | | `setStartPrice(uint256)` | Manually reset the auction start price (must be ≥ `minStartPrice`) | | `setDuration(uint256)` | Update the auction duration in seconds | | `setMinStartPrice(uint256)` | Update the minimum allowed start price floor | | `setPaymentToken(address)` | Change the payment token (cUSD by default) | *** #### View Functions | Function | Returns | Description | | -------------------- | --------- | -------------------------------------- | | `currentPrice()` | `uint256` | Current auction price in payment token | | `startPrice()` | `uint256` | Starting price of the current auction | | `startTimestamp()` | `uint256` | When the current auction started | | `duration()` | `uint256` | Auction duration in seconds | | `minStartPrice()` | `uint256` | Floor price for future auction starts | | `paymentToken()` | `address` | Token buyers pay with (cUSD) | | `paymentRecipient()` | `address` | Receives the cUSD payment from buyers | *** #### Data Structures **`FeeAuctionStorage`** ```solidity struct FeeAuctionStorage { address paymentToken; address paymentRecipient; uint256 startPrice; uint256 startTimestamp; uint256 duration; uint256 minStartPrice; } ``` | Field | Description | | ------------------ | -------------------------------------------------------------------------------- | | `paymentToken` | ERC20 token buyers pay with — cUSD | | `paymentRecipient` | Receives cUSD from every purchase — distributes to stcUSD holders | | `startPrice` | Current auction starting price in `paymentToken` (18 decimals) | | `startTimestamp` | `block.timestamp` of the last purchase (or initialization) | | `duration` | Seconds for the price to decay from `startPrice` to `startPrice × 0.1` | | `minStartPrice` | Minimum `startPrice` floor — prevents the auction going below a meaningful level | *** #### Events | Event | Parameters | Emitted when | | ------------------ | ------------------------------------ | ----------------------------- | | `Buy` | `buyer, price, assets[], balances[]` | A successful purchase is made | | `SetDuration` | `duration` | Auction duration updated | | `SetMinStartPrice` | `minStartPrice` | Minimum start price updated | | `SetPaymentToken` | `paymentToken` | Payment token changed | | `SetStartPrice` | `startPrice` | Start price manually reset | *** #### Errors | Error | Condition | | --------------------- | ---------------------------------------------------------- | | `InvalidPrice` | `currentPrice > _maxPrice` | | `InvalidAssets` | Empty asset list or `assets.length ≠ minAmounts.length` | | `InvalidDeadline` | `_deadline < block.timestamp` | | `InvalidReceiver` | `_receiver == address(0)` | | `InvalidStartPrice` | `setStartPrice` called with value below `minStartPrice` | | `InvalidPaymentToken` | `setPaymentToken` called with zero address | | `InsufficientBalance` | Asset balance in the contract is below `_minAmounts[i]` | | `NoMinStartPrice` | `initialize` called with `_minStartPrice == 0` | | `NoDuration` | `initialize` or `setDuration` called with `_duration == 0` | *** ### FeeReceiver The FeeReceiver is a simple holding contract that sits between the Lender and the FeeAuction. The Lender sends vault interest to the FeeReceiver, which holds the assets until a buyer triggers the FeeAuction sweep. It has no complex logic — its purpose is to batch up interest from multiple reserves before each auction, so buyers receive a meaningful bundle of assets per purchase rather than tiny per-asset drips. *** ## Usage Examples ### 1. Buying auction assets (stcUSD holder / arbitrageur) ```solidity interface IFeeAuction { function currentPrice() external view returns (uint256); function buy( uint256 _maxPrice, address[] calldata _assets, uint256[] calldata _minAmounts, address _receiver, uint256 _deadline ) external; } address feeAuction = 0x...; address cusd = 0x...; address usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // Check current price uint256 price = IFeeAuction(feeAuction).currentPrice(); // Approve payment IERC20(cusd).approve(feeAuction, price); // Specify assets to buy and minimum amounts (0 = accept any amount) address[] memory assets = new address[](2); uint256[] memory minAmounts = new uint256[](2); assets[0] = usdc; assets[1] = weth; minAmounts[0] = 0; minAmounts[1] = 0; // Buy — receive all USDC and WETH held by the FeeAuction IFeeAuction(feeAuction).buy( price, // exact price (no slippage on price) assets, minAmounts, msg.sender, block.timestamp + 1 minutes ); ``` ### 2. Monitoring the auction price off-chain ```solidity interface IFeeAuction { function currentPrice() external view returns (uint256); function startPrice() external view returns (uint256); function startTimestamp() external view returns (uint256); function duration() external view returns (uint256); } function getAuctionState(address feeAuction) external view returns ( uint256 price, uint256 discountPct, // how far the price has decayed (0-90%) uint256 secondsLeft // seconds until price reaches floor ) { price = IFeeAuction(feeAuction).currentPrice(); uint256 start = IFeeAuction(feeAuction).startPrice(); uint256 elapsed = block.timestamp - IFeeAuction(feeAuction).startTimestamp(); uint256 dur = IFeeAuction(feeAuction).duration(); discountPct = elapsed >= dur ? 90 : (elapsed * 90 / dur); secondsLeft = elapsed >= dur ? 0 : dur - elapsed; } ``` ### 3. Full interest flow — from Operator repayment to stcUSD yield ``` 1. Operator calls Lender.repay(usdc, amount, operator) → Lender sends vault interest to FeeReceiver (interestReceiver) 2. FeeReceiver now holds USDC (and other backing assets from other reserves) 3. Buyer calls FeeAuction.buy(maxPrice, [usdc, weth], [0, 0], buyer, deadline) → Buyer pays cUSD at currentPrice → Buyer receives USDC + WETH from FeeAuction → cUSD goes to paymentRecipient 4. paymentRecipient distributes cUSD yield to stcUSD holders (yield rate = cUSD paid / total stcUSD supply, annualised) ``` # Oracle The Oracle system provides two types of data to the Cap protocol: **asset prices** (USD values for backing assets, collateral tokens, and Cap-native tokens) and **interest rates** (borrow rates for vault utilization and per-Operator restaker rates). Both systems share the same adapter architecture — a central contract stores a payload per asset, and delegates the actual calculation to a stateless library via `staticcall`. This makes the oracle fully composable: any data source can be integrated by deploying a new adapter library. ## Mechanics ### Adapter Architecture Each asset has an `OracleData` struct stored on-chain containing two fields: * `adapter` — the address of the library or contract that computes the value * `payload` — ABI-encoded calldata passed to the adapter When a price or rate is requested, the Oracle does a low-level `staticcall` to `adapter(payload)`. Errors in the adapter are silently swallowed — a failed call returns zero rather than reverting. This means any data source failure falls through to the backup rather than halting the protocol. ### Price Oracle: Primary and Backup Each asset has two `OracleData` slots — primary and backup. `getPrice` attempts the primary first: 1. Call `primary.adapter` with `primary.payload`. 2. If the returned price is zero **or** the timestamp is older than `staleness[asset]`, fall through. 3. Call `backup.adapter` with `backup.payload`. 4. If backup also fails or is stale, revert with `PriceError`. All prices are normalized to **8 decimals** (USD). Adapters are responsible for decimal conversion. ### Rate Oracle: Market and Utilization Rates drive two separate interest streams: * **Market rate** — an external floor rate (e.g. Aave borrow rate). Used as a benchmark. * **Utilization rate** — derived from the cUSD vault's time-weighted utilization (via VaultAdapter). This is the actual rate Operators pay on vault interest. Both are fetched via the same adapter pattern, but rate adapters use `call` rather than `staticcall` because VaultAdapter writes state (it updates the utilization index snapshot). Additionally, two admin-set rates are stored directly: * `benchmarkRate[asset]` — a manual floor rate per asset (ray) * `restakerRate[agent]` — per-Operator restaker interest rate (ray) *** ## Architecture ### PriceOracle Abstract contract. Inherited by the central `Oracle` contract. #### `getPrice(address _asset)` ```solidity function getPrice(address _asset) external view returns (uint256 price, uint256 lastUpdated); ``` Returns the asset's USD price (8 decimals) and the timestamp of the last update. Tries the primary adapter first; falls back to the backup if the primary returns zero or a stale price. Reverts with `PriceError` if both fail. *** #### Admin Functions | Function | Description | | ------------------------------------------------------ | ------------------------------------------------ | | `setPriceOracleData(address _asset, OracleData)` | Set primary price adapter + payload for an asset | | `setPriceBackupOracleData(address _asset, OracleData)` | Set backup price adapter + payload for an asset | | `setStaleness(address _asset, uint256 _staleness)` | Set max age (seconds) for a valid price | *** #### View Functions | Function | Returns | Description | | -------------------------------- | ------------ | ------------------------------------------- | | `priceOracleData(address)` | `OracleData` | Primary adapter + payload for the asset | | `priceBackupOracleData(address)` | `OracleData` | Backup adapter + payload for the asset | | `staleness(address)` | `uint256` | Max acceptable age in seconds for the price | *** ### RateOracle Abstract con
프로젝트로 돌아가기