Onchain Adaptive TWAP built on 1inch — chunked execution, price protection, and auto-fills.
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 chaotic
We 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 provision
Technical Implementation Core Components:
Volatility Calculation Engine
Fetches 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 insufficient
Conditional Execution Logic
User 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 met
State Management
Tracks executed chunks and remaining amounts Records volatility at each execution for analysis Handles order completion and partial fills
Key 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 favorable
Benefits 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 timing
For 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 conditions
For Retail Users:
Access institutional-grade execution strategies Set-and-forget orders that respect market conditions Better average prices by avoiding extreme volatility periods
For Market Makers:
Provide liquidity only when spreads are favorable Reduce inventory risk during volatile periods Optimize capital efficiency
Real 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 Advantages
No 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 oracles
CTWAP 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 sizing
Gas-aware execution deferment
Chainlink oracle integrations
Batched multi-order execution support for relayers
The goal is to maximize execution efficiency, minimize slippage, and provide a safe and programmable experience for both users and resolvers.
Features
TWAP Execution Logic.
Volatility-Aware Chunk Sizing (via Chainlink).
Gas-Aware Deferment
Batched Multi-TWAP Execution
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:
Implements IPreInteraction and IPostInteraction interfaces Validates execution conditions before trades Updates state after successful fills Calculates volatility from price movements
Pack strategy addresses into 1inch order extensions Handle salt generation with extension hashes Route execution through the strategy contract
Normalizes prices from different decimal configurations Calculates returns between oracle updates Annualizes volatility using standard deviation Provides fallback values when data is insufficient
Technology Stack Smart Contracts:
Solidity 0.8.13 OpenZeppelin for security primitives (Ownable, SafeERC20) Foundry for testing, deployment, and scripting
Oracle 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 checks
1inch Protocol:
Limit Order Protocol V3 for order execution Extension system for pre/post hooks Bitwise traits for order configuration
Key Implementation Details
// 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 outages
Gasless order creation through off-chain signing No capital lock-up until execution Built-in MEV protection Composable with other 1inch features
Chainlink Oracle Benefits:
Reliable price feeds with known update frequencies Sequencer uptime monitoring for L2 safety Historical data access through getRoundData Consistent interfaces across chains
Base 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 feeds
Notable Technical Decisions
Caching volatility calculations Using memory for intermediate values Packing struct fields efficiently
Oracle integration works correctly Volatility calculations match expected ranges Sequencer checks function properly Orders execute as intended
Development 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 types
The sequencer protection was straightforward to implement thanks to Chainlink's uptime feeds, adding an important safety layer for L2 execution.