project screenshot 1
project screenshot 2
project screenshot 3
project screenshot 4
project screenshot 5

Super Order

Advanced DeFi trading: Stop-market execution, iceberg orders & OCO strategies for 1inch Protocol

Super Order

Created At

Unite Defi

Winner of

1inch

1inch - Expand Limit Order Protocol 1st place

Project Description

Advanced Trading Strategies for 1inch Limit Order Protocol

This 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 decentralized
operation, 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 gas
efficiency. Our implementation includes comprehensive security features, extensive testing coverage, and complete lifecycle demonstration scripts showing real-world
usage scenarios.

How it's Made

Technical Architecture & Implementation

Here's the technical breakdown:

Smart Contract Development (Solidity 0.8.23)

  • Built three core extensions using OpenZeppelin 5.1.0 security patterns
  • Implemented gas optimization with 1,000,000 runs using Shanghai EVM and viaIR
  • Used 1inch Solidity Utils 6.4.1 for protocol-specific integrations
  • Achieved extreme gas efficiency: ~80k gas per iceberg reveal, ~99k gas for stop loss execution

The 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 validation
  • Implemented TWAP protection against price manipulation attacks
  • Built custom oracle manager for multi-decimal token support (6, 8, 18 decimals)
  • Added configurable slippage protection up to 50% maximum
  • Hacky Solution: We discovered Chainlink oracles return 0 for heartbeats by default, so we built a custom heartbeat management system that tracks and validates oracle freshness

Keeper Automation (Chainlink Automation Compatible)

  • Developed three keeper contracts: StopLossKeeperV2, OCOKeeperV1, MockIcebergKeeper
  • Implemented checkUpkeep/performUpkeep pattern for Chainlink compatibility
  • Built gas-optimized batch operations for multiple order monitoring
  • Added 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:

  1. 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 entry
    points.

  2. 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; }

  3. 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 store
    the 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); } }

  4. 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);

  5. 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 tests
  • Gas benchmarking and optimization measurement tools
  • Complete lifecycle demonstration scripts showing real-world usage with actual transaction hashes
  • Deployed across multiple test networks for compatibility verification

Frontend (Next.js 15 + React 19)

  • Built static UI demonstration using cutting-edge React 19 and Tailwind CSS 4
  • Wagmi 2.16 + RainbowKit 2.2 integration ready for contract interaction
  • Responsive design with glassmorphism effects and dark theme
  • Three complete order interfaces with full form validation

Partner 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 execution
  • Chainlink: Oracle infrastructure enabled reliable price feeds and automation capabilities, though we had to build custom heartbeat management
  • OpenZeppelin: Security-audited patterns ensured enterprise-grade security without reinventing the wheel

Database Integration (PostgreSQL + Prisma)

  • Built complete order lifecycle tracking system
  • Stores extension data alongside core order information
  • Enables complex queries for order status and execution history
  • Clever Solution: We serialize complex order extension data into JSONB fields for flexible querying while maintaining type safety

Notable Technical Achievements:

  • First true stop-market implementation on 1inch protocol (vs existing stop-limit)
  • First comprehensive iceberg order implementation on 1inch protocol
  • Gas-optimized storage patterns reducing costs by 40% compared to naive implementations
  • Complete keeper infrastructure compatible with existing Chainlink node operators

The 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 contract
analysis 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 that
might sit unfilled while your position bleeds value.

background image mobile

Join the mailing list

Get the latest news and updates