GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — GitHub - ZengLLQ/zenith-margin: Decentralized cross-margin lending and risk protocol featuring dynamic PID-driven interest rate curves, continuous Dutch auction liquidation waterfalls, and transient-storage flash accounting.

BranchesTags
Open more actions menu

Latest commit

 

History

1 Commit
1 Commit

Folders and files

NameName
Last commit message
Last commit date
.github/workflows
.github/workflows
 
 
lib/forge-std
lib/forge-std
 
 
script
script
 
 
src
src
 
 
test
test
 
 
.gitignore
.gitignore
 
 
LICENSE
LICENSE
 
 
README.md
README.md
 
 
foundry.toml
foundry.toml
 
 

Repository files navigation

ZenithMargin

CI License: MIT EVM Solidity Coverage

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.


Executive Overview

ZenithMargin is designed to address structural inefficiencies in decentralized money markets, specifically:

  1. 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.
  2. 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.
  3. 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.
  4. 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.

System Architecture

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
Loading

Mathematical Formulation

1. Discrete PID-Adjusted Interest Rate Curve

Let $u_t = \frac{D_t}{S_t}$ denote the market utilization ratio at timestamp $t$, where $D_t$ is total active debt and $S_t$ is total active supply. The target optimal utilization is denoted by $u^*$.

The error signal $e(t)$ is defined as: $$e(t) = u_t - u^*$$

The continuous feedback control law translates into discrete updates with time step $\Delta t = t - t_{prev}$:

  1. Proportional Term: $$P(t) = K_p \cdot e(t)$$

  2. 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)$$

  3. Derivative Term: $$D(t) = K_d \cdot \frac{e(t) - e(t - \Delta t)}{\Delta t}$$

The aggregate borrowing rate $R_{borrow}(t)$ combines the baseline two-slope piecewise rate $R_{base}(u_t)$ with the PID correction $\Delta R_{PID}(t)$: $$R_{borrow}(t) = \text{clamp}\left(R_{base}(u_t) + P(t) + I(t) + D(t), R_{min}, R_{max}\right)$$

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}$$

2. Ray-Scaled Variable Debt Index Accrual

Debt balances accrue continuously using 27-decimal fixed-point Ray arithmetic. Let $I_D(t)$ be the variable debt index: $$I_D(t) = I_D(t_{prev}) \times \left(1 + \frac{R_{borrow}(t) \cdot \Delta t}{31,536,000}\right)$$

The user principal $d_{user}(t)$ with scaled debt balance $\bar{d}{user}$ is computed without storage loops: $$d{user}(t) = \bar{d}_{user} \times I_D(t)$$

3. Continuous Dutch Auction Liquidation Mechanics

When an account health factor breaches the minimum threshold: $$H_{user} = \frac{\sum_{i} C_i \cdot P_i \cdot LT_i}{\sum_{j} D_j \cdot P_j} &lt; 1.0$$

A Dutch auction is initiated with duration $\tau$ (1800 seconds). The clearing price ratio $P_{auction}(t)$ (collateral seized per unit of debt repaid) descends linearly from an initial incentive $P_{start}$ down to a safety floor $P_{floor}$: $$P_{auction}(t) = P_{start} - \min\left(1, \frac{t - t_0}{\tau}\right) \cdot (P_{start} - P_{floor})$$

For any repayment of debt $\Delta D$, the seized collateral $\Delta C$ is evaluated as: $$\Delta C = \Delta D \cdot P_{auction}(t)$$


Subsystem Architecture

Core Modules

  1. 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.
  2. 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.
  3. ZenithDebtToken.sol:

    • Scaled variable debt token implementing the ERC-20 interface with disabled transfers.
    • Scales minting and burning by the reserve variable borrow index.
  4. ZenithCollateralToken.sol:

    • Yield-bearing receipt token representing pooled collateral deposits (zTokens).
    • Validates user position solvency prior to executing transfers between accounts.
  5. ZenithDutchLiquidator.sol:

    • Continuous Dutch auction manager enabling permissionless liquidations.
    • Decays liquidation bonus over 1800-second epochs, preventing front-running extraction.
  6. ZenithStabilityPool.sol:

    • $O(1)$ constant-time stability pool absorbing liquidations instantly.
    • Tracks compounded reward product snapshots, allowing depositors to claim seized collateral.
  7. 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.
  8. 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%.
  9. 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.
  10. ZenithRouter.sol:

    • Periphery multicall contract providing atomic supplyAndBorrow and repayAndWithdraw execution.

7-Bit ASCII Terminal Visualization

+-----------------------------------------------------------------------------+
|                        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                                           |
+-----------------------------------------------------------------------------+

Verification & Testing

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

Invariant Test Results

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

Deployment & Scripts

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

Security Model & Known Limitations

  • 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.

License

This project is licensed under the MIT License.

About

Decentralized cross-margin lending and risk protocol featuring dynamic PID-driven interest rate curves, continuous Dutch auction liquidation waterfalls, and transient-storage flash accounting.

Topics

cross-margindefidutch-auctionlendingliquidationoraclesperpetualspid-controllerrisk-enginetransient-storage

Resources

Readme
MIT license
Activity

Stars

0 stars

Watchers

0 watching

Forks

0 forks
Report repository

Releases

Packages

Contributors

Languages

You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.