NatStream
Our system leverages a unique incentive structure to drive efficient price discovery in the market.
Problem Statement
Natural Gas Disruption Hook: Oracle-Driven Dynamic Fee AMM for Volatile CommoditiesNatural Gas Disruption Hook is a Uniswap V4 hook that implements an asymmetric fee and bonus mechanism to mitigate Loss Versus Rebalancing (LVR) for highly volatile commodity asset pairs. The project addresses a critical problem in DeFi: traditional AMMs suffer from adverse selection when pool prices diverge from true market prices, causing liquidity providers to lose value to informed traders who exploit stale prices.The Problem: Commodity markets like natural gas experience extreme volatility due to supply disruptions (weather events, pipeline failures), demand shocks (seasonal changes, geopolitical events), and market speculation. Traditional constant product AMMs cannot efficiently handle these volatile pairs because they rely purely on internal pool dynamics without external price awareness, leading to massive LVR for liquidity providers and inefficient capital allocation.Our Solution: We built a Uniswap V4 hook that uses real-world price data from Flare's Data Connector (FDC) to create a self-correcting market mechanism. The hook compares the pool's current price against the oracle's theoretical price (derived from EIA and NYMEX commodity data). When prices diverge:Misaligned traders (those trading away from fair value) pay escalating fees from 0.3% to 10% based on deviation magnitudeAligned traders (those trading toward fair value) pay only 0.01% fees AND receive bonuses up to 5% of their swap amountThe bonuses are funded entirely by misaligned trader fees, creating a self-sustaining treasuryThis creates profitable arbitrage opportunities for aligned traders who receive MORE than the current pool price, naturally correcting price divergence and protecting LPs from adverse selection.Technical Architecture:Flare Integration: We use Flare's FDC (Flare Data Connector) to bring verified natural gas price data on-chain from Web2 APIs (EIA, NYMEX). FDC provides cryptographic proof that the data is authentic, preventing oracle manipulation. The DisruptionOracle contract verifies these proofs via Flare's enshrined FdcVerification contract and maintains a base price that represents true market value.LayerZero Integration: Our oracle operates on Flare (where FDC attestations are available), while the Uniswap V4 pool exists on Base. We built an OracleReceiver contract that implements LayerZero's lzReceive function to receive cross-chain price updates. This extends LayerZero's base interface with security features including source chain validation, staleness checks, and replay attack prevention via monotonic timestamps.Uniswap V4 Hook: The NatGasDisruptionHook extends BaseHook and implements beforeSwap and afterSwap callbacks. In beforeSwap, we calculate the price deviation and return a dynamic fee to V4's PoolManager. In afterSwap, we check if the trader was aligned with the oracle price and pay bonuses from the self-managed treasury. The hook uses quadratic curve libraries for fee/bonus calculations that scale smoothly with price deviation.Innovation: This is the first implementation of an oracle-aware dynamic fee AMM that creates asymmetric incentives. Unlike traditional oracle-based AMMs that simply reject trades outside price bounds, we financially incentivize price correction through bonus payments that exceed market price. The system degrades gracefully—if the treasury depletes, aligned traders still benefit from low fees, and the mechanism naturally refills the treasury as misaligned trades occur.Impact: This primitive enables DeFi markets for commodities and other volatile assets that were previously impractical for AMMs. It protects LP capital, reduces LVR, improves capital efficiency, and creates a new class of arbitrage strategies based on bringing external market information on-chain.
Solution
How It's Made: Technical Implementation & ArchitectureTechnology Stack:Solidity 0.8.25 with Foundry & Hardhat hybrid setupUniswap V4 (v4-core, v4-periphery) for hook infrastructureLayerZero Endpoint for cross-chain messagingFlare Data Connector (FDC) for verifiable off-chain dataViem for testing and deployment scriptsOpenZeppelin contracts for ERC20 standardsArchitecture Overview:Our system has three layers: (1) DisruptionOracle on Flare that verifies FDC attestation proofs, (2) OracleReceiver on Base that receives LayerZero cross-chain messages, and (3) NatGasDisruptionHook that consumes oracle prices to implement dynamic fees/bonuses in Uniswap V4 pools.Clever Hacks & Notable Technical Solutions:Token Direction Detection Without External State One of the trickiest problems was determining trade direction in the hook. Uniswap V4's SwapParams only tells you zeroForOne (true = selling currency0), but the hook doesn't inherently know which currency is NATGAS vs USDC. We solved this with a clever one-liner at line 117:bool isBuyingNatGas = params.zeroForOne == (Currency.unwrap(key.currency0) < Currency.unwrap(key.currency1));This exploits the fact that Uniswap V4 canonically orders currencies by address (lower address is currency0). We compare currency addresses, determine NATGAS's position, then XOR with zeroForOne to calculate the actual economic direction. This eliminates the need for external configuration or storage lookups.Self-Funding Treasury with Zero Protocol Changes Traditional AMM fee mechanisms require protocol-level changes to fee distribution. We implemented a self-funding bonus system that operates entirely within the hook's afterSwap callback without any modifications to Uniswap V4's core accounting:if (treasuryBalance[poolId] >= bonusAmount && bonusAmount > 0) { treasuryBalance[poolId] -= bonusAmount; emit BonusPaid(poolId, sender, bonusAmount); }The hook maintains a parallel accounting system (treasuryBalance mapping) that accumulates from fundTreasury() calls and depletes when paying bonuses. The beauty: if the treasury is empty, bonuses silently skip (graceful degradation), and the system self-heals as misaligned traders refill it. No complex withdrawal queues or protocol governance needed.Quadratic Fee Curves for Smooth Price Discovery We implemented quadratic fee scaling (FeeCurve library) that creates smooth incentive gradients:fee = baseFee + (deviation^2 * multiplier) / 100This is mathematically elegant: small deviations (1-5%) have modest fees, but large deviations (50%+) face exponential penalties. The quadratic nature means there's no "cliff" where traders suddenly face max fees—every basis point of deviation increases the penalty smoothly, creating continuous price discovery incentives rather than binary on/off behavior.CREATE2 Address Mining for Hook Permissions Uniswap V4 encodes hook permissions in the hook's deployed address—specific bit flags in the address prefix indicate which callbacks are enabled. We needed beforeSwap and afterSwap, which requires an address starting with 0x9000.... We wrote a brute-force miner (MineHookSalt.s.sol):while (true) { address predicted = predictDeterministicAddress(bytecode, salt, deployer); if (uint160(predicted) & FLAGS_MASK == REQUIRED_FLAGS) { return salt; } salt++; }This mines until we find a salt that produces a valid hook address. It's a clever use of CREATE2's deterministic deployment—we can predict addresses off-chain before deployment, enabling permission encoding directly in the address.Decimal-Agnostic Fee Calculations NATGAS has 18 decimals, USDC has 6 decimals, and oracle prices use 6 decimals. Rather than complex decimal scaling throughout the code, we designed all fee/bonus calculations in basis points (10000 = 100%):uint256 bonusAmount = (swapAmount * bonusRate) / 10000;This works regardless of token decimals because we're calculating percentages, not absolute values. The input (swapAmount) carries whatever decimals the token has, and the output maintains those same decimals. Clean, simple, and eliminates an entire class of rounding bugs.Minimal LayerZero Integration with Maximum Security Instead of inheriting the full OApp base contract (which includes endpoint delegates, configuration management, etc.), we implemented just the lzReceive interface with custom security:function lzReceive(uint32 _srcEid, bytes32, uint64, bytes calldata _message) external onlyLayerZero { require(_srcEid == sourceEid, "Invalid source"); (uint256 newPrice, uint256 timestamp) = abi.decode(_message, (uint256, uint256)); require(timestamp > lastUpdateTimestamp, "Stale update"); // ... }Three security layers in 10 lines: (1) onlyLayerZero modifier ensures caller is the endpoint, (2) _srcEid validation ensures messages only come from our Flare oracle, (3) monotonic timestamp enforcement prevents replay attacks. This lightweight approach gave us 90% of LayerZero's security with 10% of the code complexity.FDC Proof Verification with Flare's ContractRegistry Flare's FDC system uses a singleton ContractRegistry pattern where all protocol contracts are accessible via static calls. We leveraged this for trustless verification:return IFdcVerificationExtended(address(ContractRegistry.getFdcVerification())).verifyWeb2Json(proof);This is clever because ContractRegistry is a compile-time constant—it's deployed at the same address on every Flare network. We don't need to configure or store the verification contract address; it's always available via the registry. The verification contract itself uses threshold signatures from multiple attestation providers, giving us Byzantine fault tolerance for free.ABI Signature Helper Functions FDC attestation providers need to know the ABI structure of our data. Instead of external documentation, we embedded it directly in the contract:function abiSignaturePriceData(PriceData calldata data) external pure {} function abiSignatureWeatherData(WeatherData calldata data) external pure {}These functions serve zero runtime purpose—they exist purely so attestation providers can call eth_abi to extract the exact ABI encoding our contract expects. It's self-documenting code that prevents ABI mismatch bugs.Cached Oracle Price with Permissionless Updates To avoid cross-contract calls on every swap (gas optimization), we cache the oracle price in the hook:uint256 public cachedOraclePrice;function updatePriceFromOracle(uint256 price, uint256 timestamp) external { require(price > 0, "Invalid price"); cachedOraclePrice = price; emit PriceReceivedFromOracle(price, timestamp); }Anyone can call updatePriceFromOracle() to push updates from the LayerZero receiver to the hook. This is permissionless by design—there's no access control because the source of truth is the OracleReceiver (which has LayerZero authentication), not the caller. Keepers/bots can arbitrage the update process, and if they don't, traders will because stale prices create arbitrage opportunities.Hybrid Foundry/Hardhat Build System Uniswap V4 dependencies aren't on npm—they're git submodules. We created a hybrid setup:Foundry manages V4 dependenciesforge install uniswap/v4-core uniswap/v4-peripheryHardhat manages our contracts and testsnpx hardhat compile npx hardhat testThe remappings.txt file maps V4 imports to Foundry's lib/ directory, while Hardhat's hardhat.config.ts includes those same paths. This lets us use Foundry's dependency management with Hardhat's superior testing framework (Viem + TypeScript).Partner Technology Deep Dives:Flare FDC: The FDC integration was particularly clever because we're not just using it as an oracle—we're using it to bring data that doesn't exist in traditional blockchain oracles. Natural gas spot prices from NYMEX and EIA APIs aren't available on Chainlink or other oracle networks. FDC's Web2Json attestations let us prove "I fetched this exact JSON from this API at this timestamp," which is cryptographically verified by multiple attestation providers. This is fundamentally different from price feed oracles—it's provable API access.LayerZero: Our usage extends beyond simple message passing. We implemented staleness validation, source chain authentication, and monotonic timestamp enforcement to create a secure price relay. The key insight: LayerZero guarantees message delivery and ordering from the endpoint, but application-level security (preventing malicious messages, replay attacks, etc.) is our responsibility. Our three-layer validation (endpoint check, source chain check, timestamp check) creates defense in depth.Uniswap V4: The hook architecture enables something impossible in V2/V3: per-swap dynamic fees based on external state. V4's PoolManager calls hook.beforeSwap() and accepts a returned uint24 fee value. This happens inside the swap transaction, so we can read the current pool price, compare to oracle price, and adjust fees atomically. The afterSwap callback lets us implement bonuses by tracking balances in parallel to the PoolManager's accounting.The Composability Win:The real hack is how these three protocols compose. Flare FDC runs on Flare (where attestation providers operate). Uniswap V4 runs on Base (where liquidity exists). LayerZero bridges them. Each protocol operates in its optimal environment, and we tied them together with minimal glue code. The DisruptionOracle is ~200 lines, OracleReceiver is ~70 lines, and the hook is ~190 lines—under 500 lines of custom Solidity to create an entirely new DeFi primitive.What Makes This Novel:No existing AMM combines oracle-driven dynamic fees with asymmetric bonuses. Existing oracle AMMs (like Uniswap V3 TWAP-based range orders) use oracles for passive reference; we use them for active incentive design. The self-funding treasury that pays traders MORE than pool price to correct divergence is a new mechanism in DeFi—it's not just arbitrage, it's subsidized arbitrage that scales with deviation.This project proves that Flare's FDC (verifiable Web2 data) + LayerZero (omnichain messaging) + Uniswap V4 (dynamic hooks) can compose into something none of them could achieve alone: commodity DeFi markets with built-in oracle-driven price correction.
Hackathon
ETHGlobal Buenos Aires
2025
Prizes
- 🏆
BONUS TRACK: external data source or cross chain application
Flare Network
Contributors
- ben-harper27
15 contributions
- deapinkme
9 contributions