Advanced TWAP, DCA, grid trading & vesting with 1inch LOP – gasless execution & smart automation
Enhanced TWAP Limit Order Protocol with 1inch Integration
Overview We're thrilled to present our Enhanced TWAP Limit Order Protocol, a sophisticated extension to the 1inch Limit Order Protocol that pushes the boundaries of on-chain trading strategies. Our solution not only meets but exceeds the hackathon requirements by delivering:
Full on-chain execution of complex trading strategies
Custom limit order implementation that operates independently of the official 1inch API
Deep integration with 1inch's powerful protocol capabilities
Key Innovations
Configurable execution intervals (from 1 minute to 365 days)
Dynamic price limits and slippage tolerance
MEV protection mechanisms
Gas optimization features
Strategy Type Key Features TWAP Time-based execution with price averaging Grid Trading Multi-level price grid execution Vesting Payouts Cliff and linear vesting schedules Gas Station Gasless transaction facilitation Stop-Loss/Trailing Advanced risk management Conditional Orders Oracle-based triggers
Custom LimitOrderData structures that mirror 1inch's format
Direct interaction with 1inch's aggregation router
Dynamic amount calculation hooks compatible with 1inch's system
Pre/post interaction callbacks for extended functionality
Technical Implementation Highlights On-Chain Execution Architecture We've designed a fully autonomous execution system that:
Processes orders entirely on-chain
Supports permissionless execution by authorized parties
Implements non-reentrant security patterns
Tracks detailed execution analytics
1inch-Compatible Extensions
struct LimitOrderData { address salt; // For unique order identification address makerAsset; // Token to sell address takerAsset; // Token to buy bytes makerAssetData; // Maker asset suffix data bytes takerAssetData; // Taker asset suffix data bytes getMakingAmountData; // Dynamic making amount calculation bytes getTakingAmountData; // Dynamic taking amount calculation bytes predicate; // Conditional execution logic bytes permit; // Gasless approvals bytes preInteraction; // Pre-execution hooks bytes postInteraction; // Post-execution hooks }
Innovative Features Gas Station Orders: Enable users to pay for gas in tokens
Batch Execution: Process multiple orders in a single transaction
Vesting-as-a-Service: Transform vesting schedules into executable limit orders
Grid Trading Automation: Execute multi-level trading strategies autonomously
Why This Stands Out Completeness: A full-featured protocol rather than a single strategy
Extensibility: Designed for easy addition of new strategy types
Production-Ready: Includes admin controls, emergency functions, and comprehensive analytics
1inch Synergy: Deep integration while maintaining independence from the official API
We're particularly excited about the potential to build upon 1inch's Limit Order Protocol, as our architecture demonstrates how the protocol can serve as a foundation for sophisticated financial primitives while maintaining compatibility with the broader 1inch ecosystem.
This submission represents not just a hackathon project, but a vision for how advanced trading strategies can be brought entirely on-chain while leveraging 1inch's battle-tested infrastructure. We look forward to continuing to develop and extend this protocol in collaboration with the 1inch team.
How We Built the Enhanced TWAP Limit Order Protocol: A Deep Dive
Core Technologies & Architecture
Our Enhanced TWAP Limit Order Protocol is built as a highly modular, gas-efficient, and extensible smart contract system that integrates deeply with 1inch’s Limit Order Protocol (LOP) while introducing novel DeFi trading strategies. Here’s how we engineered it:
OpenZeppelin Contracts – Leveraged for:
Ownable (admin controls)
ReentrancyGuard (security)
SafeERC20 (secure token transfers)
EIP712 (typed structured data hashing)
1inch Aggregation Router & Limit Order Protocol – Directly integrated for:
Optimal swap execution
Dynamic order filling
Gas-efficient trading
TWAP Engine: Splits large orders into time-weighted chunks. Innovation: Prevents market impact and MEV exploitation.
Grid Trading Module: Executes multi-level buy/sell orders. Innovation: Automates range-bound strategies.
Vesting Payout System: Converts vesting schedules into limit orders. Innovation: Enables token unlocks with price conditions.
Gas Station: Pays for gas in tokens via 1inch swaps. Innovation: Enables gasless user experience.
Conditional Orders: Oracle-triggered executions. Innovation: Supports stop-loss, take-profit, and TWAP triggers.
⚙️ How It All Fits Together
Example: Creating a TWAP Order
solidity function createTWAPOrder( address makerAsset, address takerAsset, uint256 totalAmount, uint256 intervalAmount, uint256 intervalDuration, uint256 priceLimit, uint256 deadline, uint256 slippageTolerance, bytes calldata predicateData, bytes calldata preInteractionData, bytes calldata postInteractionData ) external nonReentrant returns (bytes32 orderId); Dynamic 1inch LOP Integration: Each order generates a LimitOrderData struct that 1inch’s protocol can interpret, enabling cross-compatibility.
Gas Optimization: We minimize storage writes by batching executions and using transient storage patterns.
🔄 Phase 1: Pre-Execution Checks Time-based (TWAP): Verifies if block.timestamp ≥ lastExecution + intervalDuration.
Price-based (Grid/Conditional): Queries oracles (Chainlink, Uniswap V3 TWAP) to check if conditions are met.
Slippage Control: Uses 1inch’s getTakingAmount to ensure minimal price impact.
💸 Phase 2: 1inch Swap Execution We interact directly with 1inch Aggregation Router for optimal swaps:
solidity function _execute1inchSwap( address tokenIn, address tokenOut, uint256 amountIn, bytes memory swapData, uint256 minAmountOut ) internal returns (uint256 amountOut) { IERC20(tokenIn).approve(ONEINCH_AGGREGATION_ROUTER, amountIn); (bool success, ) = ONEINCH_AGGREGATION_ROUTER.call(swapData); require(success, "1inch swap failed"); // Handle ETH/token outputs } Dynamic Calldata Handling: The swapData is generated off-chain via 1inch API but executed fully on-chain.
Gas Refund System: For gas station orders, we swap user tokens → ETH to pay for gas.
📊 Phase 3: Post-Execution Updates State Updates: Adjusts remainingMakingAmount, executedAmount, and lastExecution.
Analytics Logging: Tracks averageExecutionPrice, realizedPnL, and totalGasUsed.
Funds Distribution: Sends proceeds to the maker.
🚀 Key Technical Innovations
Batched Order Execution: The batchExecuteOrders() function processes up to 10 orders in one TX, reducing gas costs per order.
Transient Storage for Predicates: Instead of storing condition checks, we compute them on the fly during execution.
Time-Locked Orders: TWAP intervals prevent front-running by enforcing minimum delays.
Private Order Matching: Orders are not exposed to public mempools until execution.
Dynamic Amount Getters: getTWAPMakingAmount() and getTWAPTakingAmount() allow 1inch to pull real-time order data.
Predicate & Permit Support: Enables conditional fills (e.g., "only execute if ETH > $3K").
Pre/Post Interaction Hooks: Allows custom logic before/after swaps (e.g., auto-compounding yields).
Partner Tech Stack & Benefits
1inch Aggregation Router: Best-price swaps with low slippage. Why It’s Powerful: Better execution than direct AMM swaps.
Chainlink Oracles: Price feeds for conditional orders. Why It’s Powerful: Secure, decentralized data.
EIP-712 Signed Orders: Gasless order creation. Why It’s Powerful: Better UX with meta-transactions.
OpenZeppelin Defender: Keeper automation for execution. Why It’s Powerful: Reliable order processing.
💡 What Makes This Stand Out? Beyond Basic TWAP: We built 8+ advanced strategies (Grid, Vesting, Gas Station, etc.) in one unified contract.
Full On-Chain Execution: Unlike other solutions relying on off-chain APIs, everything runs in a single TX.
1inch LOP Extensions: We didn’t just use 1inch—we extended it with dynamic order types.
Gas Efficiency: Optimized for low-cost execution, even with complex strategies.
🚀 Future Extensions Flash Loan Integration: For self-repaying orders.
NFT Limit Orders: Trading NFTs with TWAP strategies.
Cross-Chain Execution: Using LayerZero or CCIP.