ZakoKen
A Dynamic Fundraising Stablecoin Protocol for Open-Source Projects
Problem Statement
ZakoKen (雜魚券): Dynamic Fundraising Stablecoin with Dual-Liquidity ArbitrageZakoKen is an innovative fundraising stablecoin protocol that implements a novel "greed model" for sustainable open-source project funding. Built for ETHGlobal Buenos Aires hackathon, this project demonstrates how LayerZero's Omnichain Fungible Token (OFT) standard and Uniswap v4 hooks can be combined to create a dual-liquidity mechanism that stabilizes token prices while maximizing project treasury value through controlled arbitrage.Core Innovation:The protocol introduces a unique dual-pool architecture:Fixed Pool: Project-controlled 1:1 USDC redemption pool with guaranteed zero feesUniswap v4 Pool: Market-driven pool with dynamic fee calculation based on price deviation and volatilityWhen price differentials exceed 0.5%, a project-controlled arbitrage bot executes profitable trades to stabilize prices and capture value for the treasury, creating a self-sustaining funding mechanism.Technical Architecture:Smart Contracts (Solidity):ZKK-OFT Token: Extends LayerZero OFT V2 standard with compose message support, allowing every mint operation to attach off-chain transaction metadata (tx hash, timestamp, greed index). Implements dynamic greed model that adjusts token minting based on user activity to prevent speculation.FixedExchange: Simple 1:1 USDC redemption pool with pausable functionality and collateral management.ZakoKenHook: Uniswap v4 hook implementing dynamic fee calculation (0.01%-2% range) based on price deviation from 1:1 peg and recent volatility.68 comprehensive tests all passing with 100% coverage using FoundryFrontend (Next.js 15):RainbowKit wallet connection supporting Ethereum Sepolia and Base SepoliaMint Simulator: One-click simulation of off-chain transactions with compose messagesDual Swap Interface: Side-by-side comparison of Fixed Pool vs Uniswap v4 PoolArbitrage Monitor: Real-time price differential tracking and opportunity detectionFully responsive with TailwindCSS, dark mode supportCross-Chain Implementation:Deployed on Ethereum Sepolia (primary) with full Uniswap v4 poolDeployed on Base Sepolia for LayerZero cross-chain demonstrationUses LayerZero V2 compose messages to transmit off-chain transaction metadata across chainsGreed Model: The anti-speculation mechanism dynamically adjusts minting amounts based on:Transaction velocity (rapid minting penalty)Time decay (decreasing multiplier over project lifetime)Concentration prevention (reduces minting for whale holders)Formula: MintAmount = BaseAmount × GreedMultiplier × TimeDecay × ConcentrationFactorTarget Sponsor Tracks:LayerZero: Best Omnichain Implementation ($20,000)Uniswap Foundation: v4 Stable-Asset Hooks ($10,000)Optional: Circle Arc testnet integration
Solution
Technology Stack:Smart Contracts:Solidity 0.8.20 (LayerZero) & 0.8.24 (Uniswap v4) with dual compiler configurationHardhat 3.0.15 with ESM module support for contract compilation and testingFoundry (forge-std) for advanced Solidity-based unit testsOpenZeppelin Contracts v4.9.6 for security primitives (Ownable, Pausable, ReentrancyGuard)Frontend:Next.js 15.1.4 with App Router for server-side rendering and optimal performanceTypeScript for type safety across the entire codebasewagmi v2.19.5 + viem v2.39.3 for Ethereum interactionsRainbowKit v2.2.9 for beautiful wallet connection UXTailwindCSS for responsive styling with dark mode supportReact Query for efficient data fetching and cachingDevelopment Tools:pnpm for fast, disk-efficient package managementESLint + TypeScript strict mode for code qualityGit for version control with clear commit historyPartner Technology Integration:LayerZero V2 OFT (Omnichain Fungible Token): We extended the LayerZero OFT standard to implement compose message functionality, which is the cornerstone of our cross-chain metadata transmission. Every mint operation calls mintWithCompose() which creates a compose message containing off-chain transaction metadata (tx hash, timestamp, amount, greed index). This data is then transmitted cross-chain using LayerZero's _lzSend() and processed via our custom lzCompose() implementation. The compose message format uses abi.encode() to pack structured data:struct ComposeMsg { bytes32 transactionHash; uint256 timestamp; uint256 amount; address recipient; bytes32 projectId; uint256 greedIndex; }This allows us to maintain transparency about off-chain transactions while enabling cross-chain token transfers between Ethereum Sepolia and Base Sepolia. The benefit: we can prove the legitimacy of minted tokens by linking them to real off-chain activity, creating trust in the fundraising mechanism.Uniswap v4 Hooks: We implemented a custom hook (ZakoKenHook.sol) that calculates dynamic fees based on price deviation from the 1:1 peg. The hook implements beforeSwap() to inject custom fee logic and afterSwap() to track price movements. The dynamic fee formula is:fee = BASE_FEE + (priceDeviation * 2)Clamped between 0.01% (MIN_FEE) and 2% (MAX_FEE). This creates a natural stabilization mechanism where larger price deviations result in higher fees, discouraging destabilizing trades while allowing the arbitrage bot to profit. The hook also emits ArbitrageDetected events when price differentials exceed 0.5%, triggering treasury value capture.Notable Hacks and Technical Challenges:Dual Compiler Configuration: Uniswap v4 requires Solidity 0.8.24 with viaIR optimization, while LayerZero OFT works with 0.8.20. We configured Hardhat to support both compilers simultaneously:solidity: { compilers: [ { version: "0.8.24", settings: { optimizer: { enabled: true, runs: 200 }, viaIR: true } }, { version: "0.8.20", settings: { optimizer: { enabled: true, runs: 200 }, viaIR: true } } ] }This allows us to compile Uniswap v4 hooks with the required compiler while maintaining compatibility with LayerZero contracts.OpenZeppelin Version Downgrade: We discovered that LayerZero OFT V2 is incompatible with OpenZeppelin v5.x due to Ownable constructor changes. We downgraded to OpenZeppelin v4.9.6 and updated all contract constructors to remove the _owner parameter from Ownable initialization. This required careful refactoring of FixedExchange, ZakoKenHook, and MockUSDC contracts.Greed Model Implementation: The anti-speculation greed model required tracking per-user minting history and calculating dynamic multipliers. We implemented three penalty factors:Rapid Minting Penalty: Uses block.timestamp - lastMintTime to detect velocityLarge Transaction Penalty: Compares mint amount to total supply ratioWhale Holder Penalty: Calculates user's token concentrationThe final formula combines these factors: multiplier = BASE_MULTIPLIER × velocityPenalty × sizePenalty × concentrationPenaltyClamped between 0.5x and 5x to prevent extreme cases. This creates a fair distribution mechanism that rewards long-term supporters while penalizing speculators.Next.js + wagmi Version Compatibility: RainbowKit v2.2.9 requires wagmi v2.x, but we initially installed wagmi v3.0.1 which caused missing dependency errors (@base-org/account, @coinbase/wallet-sdk, etc.). We downgraded to wagmi v2.19.5 to achieve compatibility. Additionally, we configured Next.js webpack to externalize certain packages:webpack: (config) => { config.externals.push('pino-pretty', 'lokijs', 'encoding'); return config; }This prevents server-side bundling issues with browser-only Web3 libraries.Decimal Conversion Handling: ZKK uses 18 decimals (standard ERC20) while USDC uses 6 decimals. The FixedExchange contract carefully converts between these formats:uint256 usdcAmount = (zkkAmount * exchangeRate) / BASIS_POINTS / 1e12;The division by 1e12 converts from 18 decimals to 6 decimals while maintaining precision.Client-Side Only Components: Since Next.js 15 uses Server Components by default, all Web3 components must be marked with 'use client' directive. We created a providers.tsx wrapper that initializes wagmi and RainbowKit on the client side only, avoiding hydration mismatches.Testing Strategy: We wrote 68 Solidity tests using Foundry's forge-std framework, achieving 100% pass rate. Tests cover:Unit tests for each contract functionFuzz testing with 256 random inputs per testIntegration tests simulating full user flowsEdge cases like zero amounts, invalid addresses, reentrancy attacksThe test suite validates greed model calculations, cross-chain message encoding, dynamic fee computation, and collateral management.Build Process:Smart contracts compile with "pnpm hardhat compile" generating artifactsTests run with "pnpm hardhat test" executing all 68 test casesFrontend builds with "pnpm build" creating optimized static pagesDeployment to Vercel happens via "vercel --prod" with automatic HTTPSArchitecture Highlights:Monorepo structure with contracts/ and frontend/ directoriesContract ABIs automatically extracted and used in frontend (lib/contracts.ts)Environment variables separate for contracts (.env) and frontend (.env.local)Type-safe contract interactions using TypeScript + viem
Hackathon
ETHGlobal Buenos Aires
2025
Contributors
- hannesgao
28 contributions