Super Order
Advanced DeFi trading: Stop-market execution, iceberg orders & OCO strategies for 1inch Protocol
Problem Statement
Advanced Trading Strategies for 1inch Limit Order ProtocolThis project extends the 1inch Limit Order Protocol v4.3.2 with three sophisticated trading strategies that bring institutional-grade functionality to decentralized finance. We've built a comprehensive suite of advanced trading extensions that demonstrate the full potential of the 1inch protocol, implementing strategies typically found only in centralized exchanges.🛡️ Stop Loss Market Orders - TRUE STOP-MARKET EXECUTION - This is a critical advancement over existing 1inch stop loss functionality. While the current 1inch protocol only supports stop-limit orders (which create new limit orders when triggered), our StopLossMarketOrderV2 implements true stop-market execution that executes at market price immediately when triggered. This fills a major gap by providing a mechanism to trigger market execution rather than just placing another limit order that might not fill in volatile conditions.🧊 Iceberg Orders - Progressive order revelation for large institutional trades that minimize market impact. Implements four distinct reveal strategies: FIXED_SIZE for consistent chunks, PERCENTAGE for dynamic sizing based on remaining amount, ADAPTIVE for market-responsive adjustments, and TIME_BASED for increasing urgency over time. Each strategy is gas-optimized at ~80k gas per reveal with Chainlink Automation compatibility.⚖️ OCO Orders (One Cancels Other) - Advanced trading strategies with automatic order cancellation. Supports three trading strategies: BRACKET for take profit + stop loss execution, BREAKOUT for momentum-based trading, and RANGE for support/resistance trading. Features automatic cancellation when paired orders execute, keeper network automation for decentralizedoperation, and MEV protection with gas price limits.Each extension integrates seamlessly with the 1inch protocol through the IAmountGetter interface, providing native compatibility while maintaining the protocol's flexibility and gasefficiency. Our implementation includes comprehensive security features, extensive testing coverage, and complete lifecycle demonstration scripts showing real-worldusage scenarios.
Solution
Technical Architecture & ImplementationHere's the technical breakdown:Smart Contract Development (Solidity 0.8.23)Built three core extensions using OpenZeppelin 5.1.0 security patternsImplemented gas optimization with 1,000,000 runs using Shanghai EVM and viaIRUsed 1inch Solidity Utils 6.4.1 for protocol-specific integrationsAchieved extreme gas efficiency: ~80k gas per iceberg reveal, ~99k gas for stop loss executionThe Stop-Market Innovation - Solving 1inch's Missing Piece The most significant technical challenge was implementing TRUE stop-market execution. The existing 1inch protocol only supports stop-limit orders that create new limit orders when triggered. We solved this by:// Our breakthrough: Direct market execution instead of limit order creation function executeStopLoss(bytes32 orderHash) external { // Validate trigger conditions via Chainlink oracle require(isPriceTriggered(orderHash), "Price not triggered");// Execute immediately at market price through 1inch swap // Instead of creating another limit order that might not fill _executeMarketOrder(orderHash);}Oracle Integration (Chainlink)Integrated Chainlink price feeds with staleness protection and heartbeat validationImplemented TWAP protection against price manipulation attacksBuilt custom oracle manager for multi-decimal token support (6, 8, 18 decimals)Added configurable slippage protection up to 50% maximumHacky Solution: We discovered Chainlink oracles return 0 for heartbeats by default, so we built a custom heartbeat management system that tracks and validates oracle freshnessKeeper Automation (Chainlink Automation Compatible)Developed three keeper contracts: StopLossKeeperV2, OCOKeeperV1, MockIcebergKeeperImplemented checkUpkeep/performUpkeep pattern for Chainlink compatibilityBuilt gas-optimized batch operations for multiple order monitoringAdded emergency controls and access management for production safety// Each extension implements dynamic pricing function getMakingAmount(Order calldata order, bytes calldata extension, uint256 takingAmount) external view returns (uint256 makingAmount, bytes calldata postInteractionData)Particularly Hacky/Notable Implementations:Stop-Market vs Stop-Limit Breakthrough: We reverse-engineered how 1inch handles order execution to bypass the standard limit order creation. Instead of triggering a new limit order(which might not fill), we directly invoke the swap execution path with slippage protection. This required deep diving into 1inch's internal execution flow and finding the right entrypoints.Iceberg Chunk Calculation Algorithm: We developed a sophisticated algorithm that dynamically calculates chunk sizes based on four different strategies: // ADAPTIVE strategy analyzes fill velocity if (strategy == Strategy.ADAPTIVE) { uint256 fillVelocity = (block.timestamp - lastFillTime); chunkSize = fillVelocity < FAST_FILL_THRESHOLD ? baseChunkSize * 150 / 100 : baseChunkSize * 75 / 100; }OCO Automatic Cancellation Hack: We built a PreInteraction hook system that detects when one order in an OCO pair executes and automatically cancels the other. The hack: we storethe paired order hash in the order's extension data and use a callback mechanism that triggers during order execution: // Embedded in the order execution flow function preInteraction(Order calldata order, bytes calldata extension) external { bytes32 pairedOrderHash = abi.decode(extension, (bytes32)); if (pairedOrderHash != bytes32(0)) { _cancelPairedOrder(pairedOrderHash); } }Gas Optimization Tricks: We used packed structs and bit manipulation to reduce storage costs by 40%. For example, storing multiple boolean flags in a single uint256: // Pack multiple flags into single storage slot uint256 packed = (uint256(isActive) << 255) | (uint256(strategy) << 252) | (baseChunkSize);Multi-Oracle Price Aggregation: For stop loss orders, we implemented a fallback oracle system that aggregates prices from multiple Chainlink feeds with automatic switching: // If primary oracle is stale, switch to backup function getReliablePrice() internal view returns (uint256) { (uint256 price1, bool isStale1) = _getPriceWithStalenessCheck(primaryOracle); if (!isStale1) return price1;(uint256 price2, bool isStale2) = _getPriceWithStalenessCheck(backupOracle); require(!isStale2, "All oracles stale"); return price2; }Development & Testing (Hardhat 2.19.4)Comprehensive testing suite covering unit, integration, and security testsGas benchmarking and optimization measurement toolsComplete lifecycle demonstration scripts showing real-world usage with actual transaction hashesDeployed across multiple test networks for compatibility verificationFrontend (Next.js 15 + React 19)Built static UI demonstration using cutting-edge React 19 and Tailwind CSS 4Wagmi 2.16 + RainbowKit 2.2 integration ready for contract interactionResponsive design with glassmorphism effects and dark themeThree complete order interfaces with full form validationPartner Technology Benefits:1inch Protocol: Provided the robust foundation and extension system, but we had to innovate beyond their current stop-limit implementation to achieve true stop-market executionChainlink: Oracle infrastructure enabled reliable price feeds and automation capabilities, though we had to build custom heartbeat managementOpenZeppelin: Security-audited patterns ensured enterprise-grade security without reinventing the wheelDatabase Integration (PostgreSQL + Prisma)Built complete order lifecycle tracking systemStores extension data alongside core order informationEnables complex queries for order status and execution historyClever Solution: We serialize complex order extension data into JSONB fields for flexible querying while maintaining type safetyNotable Technical Achievements:First true stop-market implementation on 1inch protocol (vs existing stop-limit)First comprehensive iceberg order implementation on 1inch protocolGas-optimized storage patterns reducing costs by 40% compared to naive implementationsComplete keeper infrastructure compatible with existing Chainlink node operatorsThe Most Challenging Problem: The biggest technical hurdle was achieving true market execution for stop losses. The 1inch protocol is designed around limit orders, so triggering immediate market execution required us to essentially "hack" the execution flow to bypass the standard limit order queue and directly invoke swap execution. This took days of contractanalysis and multiple iterations to get right while maintaining gas efficiency and security.The result is institutional-grade functionality that actually works in volatile markets - when your stop loss triggers, it executes immediately rather than creating another order thatmight sit unfilled while your position bleeds value.
Hackathon
ETHGlobal Unite
2025
Prizes
- 🏆
Expand Limit Order Protocol1st place
1inch
Contributors
- ZumZoom
830 contributions
- k06a
252 contributions
- zZoMROT
165 contributions
- galekseev
81 contributions
- SevenSwen
63 contributions
- byshape
37 contributions
- artall64
34 contributions
- umershaikh123
28 contributions
- typicalbuster
26 contributions
- Pzixel
21 contributions
- krboktv
8 contributions
- shoom3301
8 contributions
- pavelkurmacheff
4 contributions
- tradersnow222
2 contributions
- romashka-btc
1 contributions
- dependabot[bot]
1 contributions
- dedyshkaPexto
1 contributions