# KairosSwap - Full Protocol Documentation > KairosSwap is a DeFi protocol for on-chain interest rate swaps on Base. Users trade interest rate movements with leverage, hedge interest rate risk, and lock in fixed yields. The protocol operates as a peer-to-pool model where buyers trade swaps against an LP (liquidity provider) pool, with both parties collateralized to manage counterparty risk. ## Protocol Overview KairosSwap enables two-sided interest rate swap markets where: - **Buyers** take directional positions on interest rates (fixed or floating) - **LPs (Liquidity Providers)** supply collateral to a shared pool that backs all active swaps - **Rates** are sourced from on-chain oracles tracking real lending protocol rates (Aave, Compound, Morpho) and off-chain rates (SOFR via Pyth) - **Settlement** is permissionless and automatic at maturity Markets come in pairs: - **BUY_FIXED**: Buyer locks a fixed rate, LP receives the floating rate - **BUY_FLOATING**: Buyer locks a floating rate, LP receives the fixed rate Both markets share the same oracles, swap token, and risk parameters. ## How Interest Rate Swaps Work ### Opening a Swap (Buying) 1. Buyer selects a market and direction (fixed or floating) 2. Buyer specifies a notional amount (the face value of the swap) 3. Protocol calculates the all-in swap rate: - **Base Rate**: Current oracle rate for the underlying lending market - **Utilization Fee**: Dynamic fee based on how much LP liquidity is in use (kinked model) - **Risk Premium**: Optional additional spread from a risk oracle 4. Buyer deposits collateral (calculated from notional, rates, term, and liquidation threshold) 5. LP pool locks corresponding collateral to back the swap 6. Swap is created with all rates recorded at entry ### During the Swap - The floating rate accrues based on the on-chain oracle index - The fixed rate accrues linearly over time - Buyer P&L = difference between fixed and floating payments - Either side can be winning depending on rate movements ### Settlement When the swap reaches maturity (entry time + swap term): - Anyone can call settlement (permissionless) - Fixed payment and floating payment are calculated - Net obligation determines who pays whom - Buyer collateral is released directly to their wallet - LP pool collateral is unlocked ### Early Exit Buyers can exit before maturity: - Accrued payments are calculated to current time - Remaining payments are projected to maturity and discounted - An early exit fee is applied - If remaining payments favor the buyer, the buyer forfeits them (only accrued amounts settle) ## User Roles ### Buyers (Traders) Actions available: - **Buy a swap**: Deposit collateral, specify notional amount, lock a rate - **Monitor positions**: Track unrealized P&L, collateral health, time to maturity - **Early exit**: Close a swap before maturity (with discount and fees) - **Settle**: Collect payout at maturity - **Claim Krystals**: Earn achievement tokens for completed swaps ### LPs (Liquidity Providers) Actions available: - **Supply collateral**: Deposit tokens into the LP pool, receive shares - **Withdraw collateral**: Redeem shares for underlying tokens - **Vault deposits**: Use managed vaults that allocate across multiple markets LP shares are priced mark-to-market based on the projected P&L of all active swaps in the pool. ## Key Protocol Parameters ### Collateral Requirements ``` Buyer Collateral = notional * (baseRate + utilFee + riskPremium) * swapTerm / (collateralizationRatio * SECONDS_IN_YEAR) LP Collateral = notional * baseRate * swapTerm / (collateralizationRatio * SECONDS_IN_YEAR) ``` ### Utilization Fee (Kinked Model) ``` If utilization <= kinkUtilization: fee = utilization * utilFeeSlopeWad Else: fee_at_kink = kinkUtilization * utilFeeSlopeWad excess = (utilization - kinkUtilization) / (1 - kinkUtilization) fee = fee_at_kink + excess^2 * maxKinkFeeWad ``` The fee increases linearly up to the kink point (e.g., 90% utilization), then rises quadratically beyond it, incentivizing LPs to add liquidity when pools are heavily utilized. ### Liquidation - Triggered when buyer collateral falls below the liquidation threshold - Anyone can call liquidation (permissionless, incentivized) - Liquidator receives an incentive from seized collateral - LP pool collateral is released ### Protocol Fees - Optional protocol fee on swap creation (capped at 1%) - Optional market creation fee (flat fee in specified token) - Fees sent to protocol multisig ## Precision and Constants - **WAD**: 1e18 (standard precision, where 1e18 = 100%) - **SECONDS_IN_YEAR**: 31,536,000 - **MIN_RATE**: 1e14 (0.01% minimum rate) - **INITIAL_INDEX**: 1e27 (oracle index starting value) All rates and factors use WAD precision. Rates can be negative (protocol supports negative interest rate environments). ## Oracle System The protocol uses a rate index system for tracking floating rates: - One cumulative index shared across all markets using the same oracle - Updated on every transaction - Formula: `newIndex = currentIndex * (1 + rate * elapsed / SECONDS_IN_YEAR)` - If an oracle fails or reverts, the index freezes but the market stays operational Supported oracle sources: - **Aave**: Borrow rates from Aave V3 pools - **Compound**: Supply/borrow rates from Compound V3 - **Morpho**: Rates from Morpho Blue vaults - **Pyth SOFR**: Secured Overnight Financing Rate via Pyth Network ## LP Share Pricing LP shares use mark-to-market pricing: - For each time bucket, weighted average rates of active swaps are calculated - Remaining P&L on active swaps is projected per bucket - Total pool value = actual collateral + projected P&L - Share price = total pool value / total shares outstanding This means LP share prices fluctuate based on unrealized P&L of the pool's swap book. ## Krystals (Achievement System) KairosTimeKrystals are ERC-20 tokens earned by completing swaps: - Awarded when swaps settle successfully - Amount based on trading activity and performance - Cross-network balance tracking supported ## Available Markets Markets are defined by: - **Underlying asset**: The token used for collateral and settlement (e.g., USDC) - **Reference rate**: The lending protocol rate being tracked (e.g., Aave USDC borrow rate) - **Swap term**: Duration of the swap (e.g., 30 days, 90 days) - **Direction**: BUY_FIXED or BUY_FLOATING Each market displays: - Current base rate (from oracle) - Available liquidity - Utilization rate - Historical rate charts ## Smart Contract Architecture ### Core Contracts - **SwapCore**: Main protocol logic - market management, swap lifecycle, collateral, settlement - **Admin**: Administrative controls - pausing, fee configuration, parameter updates ### Libraries - **SwapFormulas**: Mathematical calculations for collateral, payments, utilization fees - **Utils**: Settlement logic, liquidation mechanics, market initialization - **RateIndexLib**: Oracle index management and accumulation - **Views**: Read-only query functions for protocol state ### Adapter Contracts - **KairosMarketAdapter / Factory**: Adapter pattern for market interactions - **KairosBuyerAdapter / Factory**: Adapter pattern for buyer interactions ### Oracle Contracts - **ReferenceRateAave**: Aave V3 borrow rate oracle - **ReferenceRateCompound**: Compound V3 rate oracle - **ReferenceRateMorpho**: Morpho Blue rate oracle - **ReferenceRatePythSOFR**: SOFR rate via Pyth Network - **KairosOracleBeta**: Legacy owner-only rate oracle - **KairosOracle**: EIP-712 signed rate oracle with N-of-M verification - **ForwardCurve / DiscountCurve**: Yield curve modeling - **TWARateOracle**: Time-weighted average rate oracle ## Network and Deployment - **Primary Network**: Base (Ethereum L2) - **Token Standard**: ERC-20 for collateral tokens - **Compiler**: Solidity 0.8.20 with optimizer (200 runs, viaIR) ## Application Pages | Page | URL Pattern | Description | |------|------------|-------------| | Markets (Home) | `/` | Browse all active swap markets with filtering | | Market Detail | `/market/{marketId}` | Trade a specific market, view rate charts | | Markets List | `/market/list` | Alternative list view of markets | | Predictions | `/market/predictions` | Prediction card interface for markets | | Portfolio | `/portfolio` | Your positions, P&L, collateral, Krystals | | Portfolio (Other) | `/portfolio/{address}` | View another user's portfolio | | Leaderboard | `/leaderboard` | Rankings by Score (collateral posted × days held), swaps, volume and collateral | | Earn (Vaults) | `/earn` | Browse LP vaults | | Vault Detail | `/earn/{vaultAddress}` | Deposit/withdraw from a vault | | Faucet | `/faucet` | Mint test tokens (testnet only) | | Careers | `/careers` | Open positions | | Terms | `/terms` | Terms of service | | Settings | `/settings` | User preferences | ## Error Codes The protocol uses numeric error codes: - **100-199**: Configuration errors - **200-299**: Authorization errors - **300-399**: Market errors - **400-499**: Collateral errors - **450-469**: Pause errors - **500-599**: Swap errors - **550-559**: Early exit errors - **600-699**: Fee errors - **700-799**: Validation errors - **800-899**: Oracle errors