Skip to content

big14way/chaingaurd

Repository files navigation

ChainGuard v2 — Network Congestion Insurance Protocol

Chainlink CRE Solidity TypeScript License: MIT

First-ever parametric insurance protocol for blockchain network congestion — instant, trustless payouts when gas fees spike, powered by Chainlink CRE.

Built for Chainlink Convergence Hackathon 2026


Table of Contents


The Problem

When blockchain networks experience congestion, gas fees can spike 10-100x in minutes. This causes real financial harm:

  • Cross-border payment failures: A Nigerian trader sending USDT for imports pays $10-50+ instead of $0.50 — the entire profit margin on a small trade, wiped out
  • DeFi liquidations: Users can't top up collateral when gas spikes make the transaction itself more expensive than the position
  • Missed trading opportunities: Time-sensitive arbitrage and DeFi operations become unaffordable during the exact moments they matter most

43% of Sub-Saharan Africa's crypto volume flows through stablecoins (Chainalysis 2024). Every congestion event directly impacts millions of users across emerging markets who depend on affordable blockchain transactions for daily commerce.

No solution exists today. Traditional insurance requires manual claims and weeks of processing. DeFi protocols have no way to automatically detect and compensate for network-wide congestion events. Users simply lose money and have no recourse.


Our Solution

ChainGuard is a parametric insurance protocol that automatically compensates users when network congestion exceeds predefined thresholds. No claims process. No manual verification. No trust required.

Why Parametric Insurance?

The insured event — network base fee — has unique properties that make it ideal for parametric insurance:

Property Why It Matters
On-chain & canonical Every node agrees on the base fee — no disputes possible
Exogenous No individual user can cause network-wide congestion — no moral hazard
Verifiable by CRE DON consensus on block header data ensures tamper-proof measurement
Continuous & measurable Base fee updates every block, enabling real-time monitoring

How Payouts Work

Payouts are automatic and proportional:

  • Severity is calculated based on how far the base fee exceeds the policy threshold
  • Duration multiplier rewards policies that endure sustained congestion (capped at 3x)
  • A 10% base factor ensures conservative, sustainable payouts
  • Payout is capped at the coverage amount

Formula: payout = min(coverage, coverage * severity * duration * 0.1)


How It Works

1. User purchases policy  ->  selects tier  ->  pays premium in USDC  ->  receives ERC-721 NFT
2. CRE Workflow runs every 5 minutes (cron trigger)
3. CRE reads on-chain base fee (EVM Read) + fetches external gas API (HTTP Client)
4. Data aggregated via DON consensus (median across nodes)
5. If base fee > threshold for N consecutive checks  ->  CRE writes congestion report on-chain
6. Smart contract calculates payout  ->  vault distributes USDC automatically

Insurance Tiers

Tier Max Coverage Threshold Consecutive Checks Premium
Flash $500 50 gwei 5 0.15%
Standard $5,000 30 gwei 10 0.30%
Premium $50,000 20 gwei 15 0.50%
Enterprise $500,000 15 gwei 20 0.75%

Chainlink CRE Integration

CRE is the brain of ChainGuard. The entire monitoring, detection, and payout trigger pipeline runs as a CRE workflow.

# CRE Capability How We Use It Code Location
1 Cron Trigger Schedules congestion check every 5 minutes main.ts L89-96
2 EVM Client (Read) Reads getLatestBaseFee() from insurance contract via callContract() main.ts L127-156
3 HTTP Client Fetches Etherscan gas oracle API via sendRequest() main.ts L162-191
4 DON Consensus (Median) Aggregates gas data across DON nodes via consensusMedianAggregation() main.ts L194-199
5 EVM Client (Write) Writes reportCongestion() to insurance contract via writeReport() main.ts L233-270

5 CRE capabilities used meaningfully in a single workflow — integrating on-chain data, external APIs, DON consensus, and on-chain writes.


Files Using Chainlink

Required by hackathon submission: links to all files that use Chainlink services.

CRE Workflow Files

File Description
cre-workflow/congestion-monitor/main.ts Core CRE workflow — all 5 capabilities (cron, EVM read, HTTP, consensus, EVM write)
cre-workflow/congestion-monitor/config.staging.json CRE workflow configuration (schedule, chain selector, contract address, thresholds)
cre-workflow/congestion-monitor/config.production.json Production configuration (mainnet addresses)
cre-workflow/congestion-monitor/workflow.yaml CRE workflow deployment descriptor

Smart Contracts (CRE Callback Receivers)

File Description
contracts/core/ChainGuardInsurance.sol CRE callback receiverreportCongestion() function called by CRE workflow, onlyCRECallback modifier for access control
contracts/core/ChainGuardVault.sol Vault that distributes payouts triggered by CRE reports
contracts/core/ChainGuardPolicy.sol ERC-721 policy NFTs minted on purchase
contracts/libraries/CongestionCalculator.sol Payout calculation library (severity * duration * base factor)

Scripts & Tests

File Description
scripts/test-payout.ts End-to-end payout test — purchases policy, reports 5 breaches, verifies automatic USDC payout
scripts/cre-simulator.ts Local CRE workflow simulator (mimics CRE behavior without deployment)
scripts/set-cre-callback.ts Sets CRE callback address on insurance contract after workflow deployment
scripts/deploy.ts Full deployment script (all contracts + configuration)
test/ChainGuard.test.ts Comprehensive test suite (deployment, purchase, breach tracking, payout, cancellation)

Frontend (Reading CRE Data)

File Description
frontend/app/monitor/page.tsx Live congestion monitor — reads getCongestionStatus() from contract (data written by CRE)
frontend/app/dashboard/page.tsx User dashboard — displays policy breach progress tracked by CRE reports
frontend/lib/contracts.ts ABI definitions and contract addresses

Smart Contracts

Contract Address (Sepolia) Etherscan
ChainGuardInsurance 0xA9F06A78635bBe19d8773D8CdF0F0507838A5A93 Verified
ChainGuardVault 0xD231cB606d81CC8b013295569Eda90BB2D3b0c57 Verified
ChainGuardPolicy (NFT) 0x2c68f7504dD832f9DdBAB88b4c16E493A924647E Verified
MockUSDC 0x5F499a51E3755f33c09DdC515df8A017C2C7702f Verified

Project Structure

chainguard/
├── contracts/                              # Solidity smart contracts
│   ├── core/
│   │   ├── ChainGuardInsurance.sol         # CRE callback receiver + insurance logic
│   │   ├── ChainGuardVault.sol             # Premium pool + payout distribution
│   │   └── ChainGuardPolicy.sol            # ERC-721 policy NFTs
│   ├── interfaces/
│   │   ├── IChainGuardInsurance.sol
│   │   └── IChainGuardVault.sol
│   ├── libraries/
│   │   └── CongestionCalculator.sol        # Payout formula
│   └── mocks/
│       └── MockUSDC.sol                    # Test token (6 decimals)
├── cre-workflow/                           # CHAINLINK CRE WORKFLOW
│   └── congestion-monitor/
│       ├── main.ts                         # Core workflow (5 CRE capabilities)
│       ├── config.staging.json             # Sepolia config
│       ├── config.production.json          # Mainnet config
│       ├── workflow.yaml                   # Deployment descriptor
│       └── package.json
├── frontend/                              # Next.js 14 frontend
│   ├── app/
│   │   ├── page.tsx                       # Home + policy purchase
│   │   ├── dashboard/page.tsx             # My policies
│   │   └── monitor/page.tsx               # Live congestion monitor
│   ├── components/Header.tsx
│   └── lib/
│       ├── contracts.ts                   # ABIs + addresses
│       ├── useChainGuard.ts               # Purchase hook
│       ├── usePolicies.ts                 # Policy reading hook
│       └── web3.ts                        # Wagmi + ConnectKit config
├── scripts/
│   ├── deploy.ts                          # Full deployment
│   ├── test-payout.ts                     # End-to-end payout proof
│   ├── cre-simulator.ts                   # Local CRE simulator
│   ├── set-cre-callback.ts               # CRE callback setup
│   ├── report-congestion.ts              # Manual congestion report
│   └── configure.ts                       # Post-deployment config
├── test/
│   └── ChainGuard.test.ts                # Comprehensive test suite
├── hardhat.config.ts                      # Hardhat + Sepolia + Tenderly VNet
└── README.md

Getting Started

Prerequisites

  • Node.js >= 18
  • CRE CLI installed (curl -sSL https://cre.chain.link/install.sh | bash)
  • Bun (required for CRE workflow compilation)
  • Sepolia ETH for testnet deployment
  • Tenderly account (free) for Virtual TestNet track

1. Clone & Install

git clone https://github.com/big14way/chaingaurd.git
cd chaingaurd

# Install smart contract dependencies
npm install

# Install CRE workflow dependencies
cd cre-workflow/congestion-monitor
npm install
cd ../..

# Install frontend dependencies
cd frontend
npm install
cd ..

2. Configure Environment

cp .env.example .env
# Edit .env with your private key, RPC URLs, and API keys

Required environment variables:

PRIVATE_KEY=           # Deployer wallet private key
SEPOLIA_RPC_URL=       # Sepolia RPC endpoint
ETHERSCAN_API_KEY=     # For contract verification

3. Compile Contracts

npx hardhat compile

Running Tests

npx hardhat test

Test coverage includes:

  • Contract deployment & tier initialization
  • Policy purchase & ERC-721 NFT minting
  • Coverage amount validation per tier
  • Congestion reporting & consecutive breach tracking
  • Breach counter reset on non-congestion
  • Payout triggering after required consecutive breaches
  • Unauthorized access rejection (CRE callback modifier)
  • Policy cancellation with premium refunds
  • View function correctness

CRE Workflow Simulation

cd cre-workflow

# Login to CRE
cre login

# Compile workflow to WASM
cre-compile congestion-monitor

# Simulate the congestion monitor workflow
cre workflow simulate congestion-monitor --target staging-settings

# With broadcast (sends real testnet transactions)
cre workflow simulate congestion-monitor --target staging-settings --broadcast

Simulation Output

The simulation executes all 4 steps:

  1. EVM Read — reads getLatestBaseFee() from insurance contract
  2. HTTP Fetch — fetches Etherscan gas oracle API
  3. DON Consensus — aggregates gas data via median
  4. EVM Write — writes reportCongestion() to contract

Tenderly Virtual TestNet

ChainGuard is deployed and tested on a Tenderly Virtual TestNet (fork of Sepolia).

Live Explorer

View all transactions on Tenderly Virtual TestNet Explorer

The explorer shows the full transaction history:

  • Contract deployments (MockUSDC, Vault, PolicyNFT, Insurance)
  • Policy purchase (USDC approve + purchasePolicy)
  • 5 consecutive congestion reports at 100 gwei
  • Automatic payout of 10 USDC triggered on 5th breach

Deployed Contracts (Tenderly VNet)

Contract Address
ChainGuardInsurance 0xa6fB60b593A87f0aE50dACD6d5bF75EdcA6C43b4
ChainGuardVault 0x3Cc8452981fA0cfF47427b44b7804B9B889ff25B
ChainGuardPolicy (NFT) 0xEc18bfD221F773345c782251c30d02eE21Aa0107
MockUSDC 0xd592da75C554beD6b42766968Fee71e4C6A0d8b2

Reproduce Locally

  1. Create a Virtual TestNet at dashboard.tenderly.co (fork Sepolia, enable Public Explorer)
  2. Add RPC URL to .env:
    TENDERLY_VIRTUAL_TESTNET_RPC=https://virtual.rpc.tenderly.co/YOUR_ID
    TENDERLY_VIRTUAL_TESTNET_CHAIN_ID=73571
    
  3. Deploy and test:
    npx hardhat run scripts/deploy.ts --network virtualSepolia
    npx hardhat run scripts/test-payout.ts --network virtualSepolia

Live Deployment (Sepolia)

Deployed & Verified Contracts

All contracts are live on Sepolia and verified on Etherscan:

Contract Address Etherscan
ChainGuardInsurance 0xA9F06A78635bBe19d8773D8CdF0F0507838A5A93 View
ChainGuardVault 0xD231cB606d81CC8b013295569Eda90BB2D3b0c57 View
ChainGuardPolicy (NFT) 0x2c68f7504dD832f9DdBAB88b4c16E493A924647E View
MockUSDC 0x5F499a51E3755f33c09DdC515df8A017C2C7702f View

Vault Liquidity: 100,000 USDC | Network: Ethereum Sepolia | Status: Fully Operational

Live Frontend

https://chainguard-v2.vercel.app

Or run locally:

cd frontend
npm install
npm run dev
# Open http://localhost:3000

The frontend allows you to:

  • Purchase insurance policies (approve USDC + purchase in one flow)
  • View your active policies with breach progress
  • Monitor network congestion with real on-chain data
  • Track CRE workflow reports and active policy count

Deploy Your Own

npx hardhat run scripts/deploy.ts --network sepolia

# Verify contracts
npx hardhat verify --network sepolia <CONTRACT_ADDRESS> <CONSTRUCTOR_ARGS>

End-to-End Payout Proof

We have proven the full insurance flow works on Sepolia testnet using scripts/test-payout.ts:

=== ChainGuard End-to-End Payout Test ===

Step 1: Purchase Flash Tier Policy
  Coverage: $100 USDC | Premium: 0.15 USDC | Threshold: 50 gwei
  Policy created! ID: 3

Step 2: Report Congestion (5x above 50 gwei)
  Breach 1/5 at 100 gwei (severity 10000 bps) ... Breach recorded
  Breach 2/5 at 100 gwei ... Breach recorded
  Breach 3/5 at 100 gwei ... Breach recorded
  Breach 4/5 at 100 gwei ... Breach recorded
  Breach 5/5 at 100 gwei ... PAYOUT TRIGGERED! Amount: 10.0 USDC

Step 3: Verify Payout
  USDC gained: 20.0 USDC (2 active policies paid out)
  Policy status: Claimed

SUCCESS! Policy was claimed and payout was sent!

Run the test yourself:

npx hardhat run scripts/test-payout.ts --network sepolia

Demo

Demo Video: [YouTube Link — TBD]

Tenderly Explorer: View all transactions

Demo covers:

  1. CRE workflow simulation detecting congestion (cre workflow simulate)
  2. Policy purchase flow via frontend (tier selection, USDC approval, NFT minting)
  3. Dashboard showing active policy with breach progress
  4. Monitor page reading real on-chain congestion data
  5. Automatic payout triggered after consecutive breaches

Architecture

                    CRE Workflow (every 5 min)
                    ┌─────────────────────────┐
                    │  1. Cron Trigger         │
                    │  2. EVM Read (base fee)  │
                    │  3. HTTP (gas oracle)    │
                    │  4. DON Consensus        │
                    │  5. EVM Write (report)   │
                    └──────────┬──────────────┘
                               │
                               ▼
┌──────────┐    ┌──────────────────────────┐    ┌──────────────┐
│  User    │───>│  ChainGuardInsurance     │───>│ ChainGuard   │
│ (USDC)   │    │  - purchasePolicy()      │    │ Vault (USDC) │
│          │<───│  - reportCongestion()     │<───│ - sendPayout │
│          │    │  - breach tracking        │    │ - liquidity  │
└──────────┘    └──────────┬───────────────┘    └──────────────┘
                           │
                           ▼
                    ┌──────────────┐
                    │ PolicyNFT    │
                    │ (ERC-721)    │
                    │ - tradeable  │
                    └──────────────┘

Chainlink Services Used

# CRE Capability Integration Point File
1 Cron Trigger Schedules congestion check every 5 min main.ts
2 EVM Client Read Reads base fee from insurance contract main.ts
3 HTTP Client Fetches Etherscan gas oracle API main.ts
4 DON Consensus Median aggregation across nodes main.ts
5 EVM Client Write Writes congestion report on-chain main.ts

Team

ChainGuard Team — Built from Lagos, Nigeria


License

MIT License — see LICENSE for details.

About

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors