
GoHedge
DeFi Insurance for Safer Crypto Yield
Demo
About
The problem it solves # Problem Most high-yield tokens lack hedging tools, resulting in low investor confidence and low volumes for L1 projects. # Solution GoHedge provides trigger-based insurance for L1 tokens. Users can purchase protection against price drops below a specified threshold, enabling confident investment in high-yield but risky protocols. ## Real-World Example **Scenario**: Farm2 is a new DeFi protocol offering 30% APY in Farm2 tokens, but the ecosystem is relatively new and volatile. ### For Developers/Sellers **Belief**: Current Farm2 price ($2.00) is undervalued **Action**: Creates an insurance contract on GoHedge **Trigger price**: $1.00 (50% downside protection) **Insurance fee**: 1 AVAX (premium collected) **Reserve**: 10 AVAX (payout if triggered) **Outcome**: Earns 1 AVAX fee if price stays above $1.00, loses 10 AVAX if price crashes **Note**: Trigger price, insurance fee, and reserve are fully customizable by the seller. ### For Investors/Buyers **Goal**: Wants Farm2's 30% APY but fears price volatility **Action**: Pays 1 AVAX insurance fee to Andre **Protection**: Gets 10 AVAX payout if Farm2 drops below $1.00 **Result**: Can safely farm Farm2 tokens knowing downside is limited ## Impact **For Investors**: Secure participation in high-yield protocols with defined risk limits **For Developers**: Increased ecosystem confidence and higher token volumes through available hedging options **For Markets**: Better price discovery and reduced volatility through risk distribution ## Use Cases 1. **New Protocol Launch**: Hedge against early volatility 2. **Yield Farming**: Protect principal while earning high APY 3. **Arbitrage Protection**: Hedge positions during cross-chain activities 4. **Government Finance**: Hedge sovereign foreign currency reserves 5. **Investment Funds**: Limit downside on multidimentional asset portfolios
How it's made
Challenges we ran into ## Challenge 1: Gas-Efficient Chainlink Automation **Problem**: Our biggest hurdle was designing Chainlink Automation logic that could scale without hitting gas limits. A simple loop checking every active insurance policy would quickly exceed the block gas limit, causing the entire automation run to fail and leaving valid policies unchecked. **Solution**: We implemented a sophisticated batching and gas-aware processing system: - **Stateful Batch Processing**: Instead of processing all insurances at once, our performTimeBasedUpkeep function processes a limited batch (20 contracts) per run. It intelligently tracks the index of the last contract checked, so the next automation run resumes from that point without duplicate processing. - **Real-time Gas Monitoring**: Before processing each contract, the function checks remaining gas using gasleft(). If it falls below our safety threshold (100,000 gas), it gracefully stops the current run, ensuring work already done is saved and the transaction doesn't fail. - **Optimized Data Structures**: We maintain a separate counter for active contracts, avoiding iteration through potentially thousands of inactive policies in our mapping. **Result**: Our GasAndPerformance.test.js suite validates this approach, ensuring the protocol remains reliable and cost-effective even with thousands of concurrent insurance policies. ## Challenge 2: Unified Native and ERC20 Token Support **Problem**: Supporting both native AVAX and ERC20 tokens (like USDC) as collateral presented a major architectural challenge. These token types have fundamentally different transfer mechanisms (msg.value vs transferFrom) and accounting models. A naive approach would require separate functions for each type, leading to code duplication and user confusion. **Solution**: We architected a unified, flexible system: - **Smart Contract Abstraction**: Our core Contract struct uses an address for reserveToken. The zero address (0x0) signifies native AVAX, while any other address points to an ERC20 contract. - **Conditional Execution Logic**: Core functions (createContract, purchaseInsurance, claimPayout, withdrawReserve) check the reserveToken address: - If address(0): Use payable, msg.value, and address.transfer() - If ERC20 address: Use IERC20(token).safeTransferFrom() and safeTransfer() - **Seamless User Experience**: This happens behind the scenes - users interact with the protocol identically regardless of token choice. **Result**: Our DummyUpgradeUSDC.test.js suite validates both AVAX and ERC20 functionality, ensuring consistent behavior across all collateral types. ## Challenge 3: Comprehensive Re-entrancy Protection **Problem**: Re-entrancy attacks are among the most dangerous DeFi vulnerabilities. While OpenZeppelin's ReentrancyGuard helps, our complex protocol lifecycle (create → purchase → trigger → claim) required additional security measures to prevent attacks at every state transition. **Solution**: We implemented a defense-in-depth strategy: - **Strict Checks-Effects-Interactions Pattern**: In claimPayout, we strictly follow CEI - first check all conditions, then update internal state (c.claimed = true), and only then perform external transfers. This prevents malicious contracts from re-entering before state updates. - **Attack Simulation Testing**: We built a dedicated MaliciousContract.sol and detailed SecurityTests.test.js suite that actively attempts re-entrancy attacks on claimPayout and withdrawReserve. Our tests prove the safeguards successfully block these attacks. - **One-way State Machine**: Critical state flags (active, triggered, claimed) enforce a logical one-way flow. Contracts cannot be claimed before triggering, and cannot be triggered twice, providing an additional security layer beyond re-entrancy guards. **Result**: This multi-layered approach creates a demonstrably resilient protocol against one of DeFi's most common attack vectors, validated through targeted penetration testing.