← Back to home

1Twap

Onchain Adaptive TWAP built on 1inch — chunked execution, price protection, and auto-fills.

Problem Statement

CTWAP: Conditional Time-Weighted Average Price with Volatility Awareness What We Built CTWAP is a volatility-aware execution strategy for the 1inch Limit Order Protocol. It adds conditional logic to traditional TWAP orders, allowing trades to execute only when market volatility falls within user-specified ranges. The system reads real-time volatility from Chainlink price oracles or dedicated volatility feeds, calculates annualized volatility from recent price movements, and gates order execution based on these metrics. It's implemented as pre/post-interaction hooks that integrate seamlessly with 1inch's existing infrastructure. Why We Built It Traditional TWAP executes on a fixed schedule regardless of market conditions. This creates several problems:Execution during extreme volatility leads to poor fills and high slippage Trading in dead markets wastes gas on minimal price improvements No adaptation to market regime changes - same strategy whether markets are calm or chaoticWe observed that sophisticated traders manually pause their TWAP strategies during unfavorable conditions but resume when volatility normalizes. CTWAP automates this decision-making process. The Opportunity DeFi lacks sophisticated execution tools that institutional traders take for granted in traditional finance. While TradFi has volatility-targeted algorithms, conditional orders, and adaptive execution, DeFi users are limited to basic time-based strategies. The market opportunity includes:Treasury managers holding billions in stablecoins need better conversion strategies DAOs accumulating strategic positions want to avoid volatile periods Traders seeking to optimize entry/exit points based on market conditions Market makers requiring volatility-aware liquidity provisionTechnical Implementation Core Components:Volatility Calculation EngineFetches latest and historical prices from Chainlink oracles Calculates instant returns between price updates Annualizes volatility using standard deviation of returns Falls back to reasonable defaults when data is insufficientConditional Execution LogicUser sets min/max volatility thresholds (e.g., 20% - 80% annualized) Each chunk checks current volatility before execution Blocks execution outside specified ranges Maintains standard TWAP intervals when conditions are metState ManagementTracks executed chunks and remaining amounts Records volatility at each execution for analysis Handles order completion and partial fillsKey Parameters:minVolatility / maxVolatility: Execution bounds in basis points volatilityWindow: Lookback period for calculations adaptiveChunkSize: Optional scaling based on volatility continuousMode: Rapid execution when conditions are favorableBenefits to Users For Large Traders:Execute sizeable orders without monitoring markets constantly Avoid trading during flash crashes or extreme pumps Reduce overall execution costs through better timingFor DAOs and Treasuries:Implement policy-based trading (e.g., "only convert reserves during normal markets") Create audit trails showing execution happened within risk parameters Delegate execution to keepers while maintaining control over conditionsFor Retail Users:Access institutional-grade execution strategies Set-and-forget orders that respect market conditions Better average prices by avoiding extreme volatility periodsFor Market Makers:Provide liquidity only when spreads are favorable Reduce inventory risk during volatile periods Optimize capital efficiencyReal Usage Example A DAO wants to convert 1,000,000 USDC to ETH over 24 hours: Traditional TWAP: Buys 41,666 USDC worth every hour, regardless of conditions CTWAP Configuration:Total: 1,000,000 USDC → ETH Chunks: 24 (hourly) Volatility Range: 30% - 90% (typical ETH range) Duration: 24-48 hours (flexible based on conditions)Result: Executes only during favorable volatility, potentially completing in 30 hours but with better average pricing and reduced slippage. Technical AdvantagesNo Protocol Modifications: Works with existing 1inch infrastructure Gas Efficient: Volatility calculations use existing oracle data Composable: Can be combined with other 1inch features Chain Agnostic: Deployed on Base, works on any EVM chain with oraclesCTWAP solves a real problem in DeFi execution - the inability to condition trades on market state. By adding volatility awareness to TWAP, users get better execution without sacrificing the benefits of automated trading.This implementation enhances traditional TWAP logic by introducing:Volatility-aware chunk sizingGas-aware execution defermentChainlink oracle integrationsBatched multi-order execution support for relayersThe goal is to maximize execution efficiency, minimize slippage, and provide a safe and programmable experience for both users and resolvers.FeaturesTWAP Execution Logic.Volatility-Aware Chunk Sizing (via Chainlink).Gas-Aware DefermentBatched Multi-TWAP Execution

Solution

How We Built CTWAP: Technical Deep Dive Core Architecture We built CTWAP as an extension to the 1inch Limit Order Protocol using their pre/post-interaction hook system. The architecture consists of three main contracts:CTWAPStrategy.sol - The core contract that:Implements IPreInteraction and IPostInteraction interfaces Validates execution conditions before trades Updates state after successful fills Calculates volatility from price movementsIntegration Layer - Extensions that:Pack strategy addresses into 1inch order extensions Handle salt generation with extension hashes Route execution through the strategy contractVolatility Engine - The calculation module that:Normalizes prices from different decimal configurations Calculates returns between oracle updates Annualizes volatility using standard deviation Provides fallback values when data is insufficientTechnology Stack Smart Contracts:Solidity 0.8.13 OpenZeppelin for security primitives (Ownable, SafeERC20) Foundry for testing, deployment, and scriptingOracle Integration:Chainlink Price Feeds for price data Custom volatility calculation since Chainlink's volatility feeds aren't available on Base L2 sequencer uptime feeds for safety checks1inch Protocol:Limit Order Protocol V3 for order execution Extension system for pre/post hooks Bitwise traits for order configurationKey Implementation DetailsVolatility Calculation from Price Data Since Chainlink provides volatility feeds on Ethereum mainnet but not on Base, we calculate volatility from price movements: solidity// Get current and previous round data (uint80 currentRoundId, int256 currentPrice,, uint256 currentTime,) = AggregatorV3Interface(priceOracle).latestRoundData();// Calculate return between updates uint256 absReturn = (priceDiff * FIXED_POINT_DECIMALS) / normalizedPrev;// Annualize based on time between updates uint256 periodsPerYear = 365 days / timeDiff; uint256 annualizedVol = absReturn * _sqrt(periodsPerYear); We use the time between oracle updates and price changes to derive implied volatility. This works because Chainlink updates more frequently during volatile periods. 2. L2 Sequencer Protection Base, like other L2s, relies on a sequencer for transaction ordering. We integrated Chainlink's sequencer uptime feed to prevent execution during downtime: solidityfunction _checkSequencerUptime(address sequencerUptimeFeed) internal view { (, int256 answer, uint256 startedAt,,) = AggregatorV3Interface(sequencerUptimeFeed).latestRoundData();// answer == 0: sequencer is up // answer == 1: sequencer is down if (answer != 0) revert SequencerDown(); // Check if sequencer recently restarted if (block.timestamp - startedAt <= GRACE_PERIOD_TIME) { revert PriceFeedStale(block.timestamp - startedAt, GRACE_PERIOD_TIME); }} This prevents trades from executing:When the sequencer is down During the 1-hour grace period after sequencer recovery Protects against stale prices during outagesExtension System Integration 1inch orders use extensions to add custom logic. We developed a packing system: solidity// Hash extension and bind to order salt uint256 extHash160 = uint256(keccak256(extension)) & ((1 << 160) - 1); uint256 salt = (randomHighBits << 160) | extHash160; This ensures orders are bound to our strategy contract without modification to 1inch core.State Management Since 1inch orders are stateless, we maintain execution state on-chain: soliditystruct TWAPState { uint256 executedChunks; uint256 lastExecutionTime; uint256 totalMakingAmount; uint256 totalTakingAmount; } This allows us to track progress and enforce chunk intervals. Partner Technology Integration 1inch Limit Order Protocol Benefits:Gasless order creation through off-chain signing No capital lock-up until execution Built-in MEV protection Composable with other 1inch featuresChainlink Oracle Benefits:Reliable price feeds with known update frequencies Sequencer uptime monitoring for L2 safety Historical data access through getRoundData Consistent interfaces across chainsBase Network Considerations:Low gas costs make small chunks economical Fast block times (2 seconds) enable responsive execution Growing ecosystem but limited oracle options Required custom volatility calculation due to missing feedsNotable Technical DecisionsFallback Volatility Values When we can't calculate volatility (insufficient data, oracle issues), we use reasonable defaults: solidityif (priceDiff == 0 || timeDiff == 0) { return 6000; // 60% - typical crypto volatility } This ensures the system remains functional even with data gaps.Precision Handling We normalize all prices to 18 decimals for consistent calculations: solidityfunction _normalizePrice(uint256 price, uint8 decimals) internal pure returns (uint256) { if (decimals < 18) { return price * 10**(18 - decimals); } else { return price / 10**(decimals - 18); } }Gas Optimization We minimize storage writes by:Caching volatility calculations Using memory for intermediate values Packing struct fields efficientlyTesting Approach We used Foundry fork tests against Base mainnet to verify:Oracle integration works correctly Volatility calculations match expected ranges Sequencer checks function properly Orders execute as intendedDevelopment Challenges The main challenge was working around the lack of volatility oracles on Base. We solved this by:Building our own volatility calculation from price movements Using oracle update frequency as a volatility proxy Implementing multiple fallback mechanisms Adding configurable parameters for different asset typesThe sequencer protection was straightforward to implement thanks to Chainlink's uptime feeds, adding an important safety layer for L2 execution.

Hackathon

ETHGlobal Unite

2025

Contributors