A decentralized multi-asset cross-margin lending and risk protocol featuring dynamic proportional-integral-derivative (PID) interest rate curves, continuous Dutch auction liquidation waterfalls, transient-storage flash accounting, and composite oracle circuit breakers.
ZenithMargin is designed to address structural inefficiencies in decentralized money markets, specifically:
- Dynamic Rate Inefficiencies: Traditional two-slope piecewise curves react sluggishly to sustained high utilization or sudden liquidity drains. ZenithMargin couples a two-slope base curve with a discrete Proportional-Integral-Derivative (PID) feedback loop that dynamically adjusts borrowing rates to actively drive utilization toward an optimal equilibrium.
- Toxic MEV Liquidations: Fixed-bonus liquidation models incentivize predatory front-running and sandwiching by liquidators. ZenithMargin implements a continuous linear Dutch auction mechanism where liquidation incentives decay over a 30-minute epoch, guaranteeing fair price discovery and minimizing collateral loss for distressed positions.
- High Gas Overheads in Flash Accounting: By employing Cancun EIP-1153 transient storage (
TSTORE/TLOAD), reentrancy locks and flash-borrowing net balances are verified at the transaction frame boundary with zero persistent storage cost. - Oracle Discrepancies and Price Volatility: A composite oracle hub cross-checks primary Chainlink feeds with secondary feeds, enforcing staleness heartbeats and maximum price deviation thresholds, backed by automated volatility circuit breakers.
graph TD
User([User / Borrower]) -->|Deposit / Borrow / Repay| Router[ZenithRouter]
Router -->|Multicall Routing| Pool[ZenithPool]
subgraph Core Engine
Pool <--> PositionMgr[ZenithPositionManager]
Pool <--> ReserveMgr[ZenithReserveManager]
Pool -->|Mints / Burns| CToken[ZenithCollateralToken]
Pool -->|Mints / Burns Scaled| DToken[ZenithDebtToken]
end
subgraph Mathematical Subsystem
Pool --> WadRay[WadRayMath]
Pool --> PIDMath[PIDControllerMath]
Liquidator --> DutchMath[DutchAuctionMath]
PositionMgr --> RiskMath[RiskWeightMath]
end
subgraph Risk & Liquidation Subsystem
Liquidator[ZenithDutchLiquidator] -->|Seize Collateral| Pool
StabilityPool[ZenithStabilityPool] -->|Offset Debt O(1)| Pool
ReserveMgr -->|Allocate Reserves| Insurance[ZenithInsuranceFund]
end
subgraph Oracle & Safety Subsystem
OracleHub[ZenithOracleHub] --> ChainlinkPrimary[(Primary Feed)]
OracleHub --> FallbackFeed[(Secondary Feed)]
Breaker[ZenithCircuitBreaker] -->|Volatility Trigger| Guardian[ZenithEmergencyGuardian]
Guardian -->|Pause Operations| Pool
end
subgraph Transient Flash Accounting
FlashMinter[ZenithFlashMinter] -->|EIP-1153 TSTORE/TLOAD| TransientLock[ZenithTransientLock]
end
Let
The error signal
The continuous feedback control law translates into discrete updates with time step
-
Proportional Term:
$$P(t) = K_p \cdot e(t)$$ -
Integral Term with Anti-Windup Clamping:
$$I(t) = \text{clamp}\left(I(t - \Delta t) + K_i \cdot e(t) \cdot \Delta t, -I_{max}, I_{max}\right)$$ -
Derivative Term:
$$D(t) = K_d \cdot \frac{e(t) - e(t - \Delta t)}{\Delta t}$$
The aggregate borrowing rate
Where the baseline piecewise rate is: $$R_{base}(u_t) = \begin{cases} R_0 + \frac{u_t}{u^} \cdot R_{slope1}, & u_t \le u^ \ R_0 + R_{slope1} + \frac{u_t - u^}{1 - u^} \cdot R_{slope2}, & u_t > u^* \end{cases}$$
Debt balances accrue continuously using 27-decimal fixed-point Ray arithmetic. Let
The user principal
When an account health factor breaches the minimum threshold:
A Dutch auction is initiated with duration
For any repayment of debt
-
ZenithPool.sol:- Master state machine holding reserve balances and coordinating liquidity.
- Accrues variable debt indices and supply liquidity indices on every interaction.
- Enforces supply and borrow caps, paused action guards, and transient reentrancy checks.
-
ZenithPositionManager.sol:- Cross-margin risk evaluation engine.
- Aggregates collateral and debt across multiple reserves into 18-decimal normalized USD values.
- Enforces collateral isolation policies and ensures health factors remain above
$1.0 \times 10^{18}$ WAD.
-
ZenithDebtToken.sol:- Scaled variable debt token implementing the ERC-20 interface with disabled transfers.
- Scales minting and burning by the reserve variable borrow index.
-
ZenithCollateralToken.sol:- Yield-bearing receipt token representing pooled collateral deposits (zTokens).
- Validates user position solvency prior to executing transfers between accounts.
-
ZenithDutchLiquidator.sol:- Continuous Dutch auction manager enabling permissionless liquidations.
- Decays liquidation bonus over 1800-second epochs, preventing front-running extraction.
-
ZenithStabilityPool.sol:-
$O(1)$ constant-time stability pool absorbing liquidations instantly. - Tracks compounded reward product snapshots, allowing depositors to claim seized collateral.
-
-
ZenithOracleHub.sol:- Multi-source price feed manager reading 8-decimal and 18-decimal Chainlink aggregators.
- Validates heartbeat freshness and checks cross-feed price deviation against maximum basis point thresholds.
-
ZenithCircuitBreaker.sol:- Automated volatility monitoring subsystem that tracks rolling price changes over a 15-minute window.
- Automatically trips and pauses borrow and liquidation actions when price movements exceed 20%.
-
ZenithTransientLock.sol&ZenithFlashMinter.sol:- EIP-1153 transient storage (
TSTORE/TLOAD) reentrancy guard. - ERC-3156 flash lender that validates net-zero balance restoration at zero persistent gas cost.
- EIP-1153 transient storage (
-
ZenithRouter.sol:- Periphery multicall contract providing atomic
supplyAndBorrowandrepayAndWithdrawexecution.
- Periphery multicall contract providing atomic
+-----------------------------------------------------------------------------+
| ZENITHMARGIN PROTOCOL DASHBOARD |
+-----------------------------------------------------------------------------+
| Reserve Pool: WETH / USDC |
| Utilization Rate: [=============================..........] 74.2% (Target: 80%)|
| Current Base Rate: 4.20% APR |
| PID Adjustment: -0.35% APR (Integral Decay Active) |
| Effective Borrow: 3.85% APR |
+-----------------------------------------------------------------------------+
| ACCOUNT HEALTH MONITOR |
| Health Factor: [======================================] 1.82 (SAFE) |
| Total Collateral: $ 15,000.00 USD (5.0000 WETH @ $3,000.00) |
| Total Borrowed: $ 5,000.00 USD (5,000.00 USDC) |
| Borrow Power Used: [=====================.................] 59.2% |
+-----------------------------------------------------------------------------+
| DUTCH AUCTION LIQUIDATION CASCADE |
| Auction ID #14: Liquidating Account 0x7a3... |
| Initial Incentive: +20.0% Bonus Collateral |
| Current Incentive: +11.4% Bonus Collateral (t = 640s / 1800s) |
| Descent Gradient: [\\\\\\\\\\\\\\\\\\\\...................] 35.5% Elapsed |
| Status: ACTIVE BIDDING OPEN |
+-----------------------------------------------------------------------------+
| TRANSIENT STORAGE STATUS (EIP-1153) |
| Frame Reentrancy Lock: UNLOCKED [CLEARED] |
| Flash Loan Net Solvency: RESOLVED |
+-----------------------------------------------------------------------------+
ZenithMargin contains 59 test suites covering unit math, access control, oracle deviation, multi-asset lifecycle integration, and stateful invariant fuzz tests:
# Run the complete test suite with 256 fuzz runs forge test -vvv --fuzz-runs 256 # Verify code formatting forge fmt --check # Check contract bytecode sizes forge build --sizes
Stateful fuzz invariant testing runs 256 iterations with 8,192 calls per suite across randomized actor actions (supplying, borrowing, repaying, and warping time):
| Test Suite | Runs | Total Calls | Reverts | Outcome |
|---|---|---|---|---|
invariant_ProtocolSolvency |
256 | 8,192 | 0 | PASS |
invariant_MonotonicBorrowIndex |
256 | 8,192 | 0 | PASS |
invariant_TransientLockCleared |
256 | 8,192 | 0 | PASS |
Deploy to local Anvil or live testnet:
# Deploy full suite forge script script/DeployZenith.s.sol:DeployZenith --broadcast # Run liquidation cascade simulation forge script script/SimulateLiquidationCascade.s.sol:SimulateLiquidationCascade
- EIP-1153 Dependency: Requires an EVM runtime supporting the Cancun hard fork (
TSTORE/TLOAD). - Oracle Latency: Chainlink heartbeats are set to 24 hours for stable assets and 1 hour for volatile assets; during extreme volatility, circuit breakers halt interactions before liquidations execute.
- Single-Asset Isolated Mode: When isolated collateral is active, users cannot cross-margin with alternative assets to prevent risk contamination.
This project is licensed under the MIT License.