Works with the AI Agents you already use

    Claude CodeClaude CodeCursorCursorCodex CLICodex CLIDeepSeekDeepSeekMuseMuse+22 more

    On-Chain Central Limit Order Book Matching Engine

    1

    Gas-safe on-chain matching engine using binary heaps, bounded match loops, and proportional margin settlement.

    Free

    Security scanned
    On-Chain Central Limit Order Book Matching Engine

    On-Chain Central Limit Order Book Matching Engine

    Example session with this skill installed

    Explain how to safely handle self-matching in the match loop and provide the margin release logic for a partial fill.

    • Read your context and instructions
    • Compiled the on-chain central limit

    The matching engine implements a bounded skip counter to prevent infinite loops when a trader crosses their own order. Margin is released proportionally based on the fill size relative to the original order size before state updates.

    On-Chain Matching and Margin Logic

    Self-Match Guard (Bounded)

    StrategyLogicOutcome
    Skip CounterTracks selfMatchSkips vs heap.lengthPrevents OOG DoS
    Placement RejectionReverts if new order crosses own restingKeeps book clean
    Cancel-on-CrossRemoves resting order before fillOptimal for traders

    Proportional Margin Release

    function settleFill(Order storage bid, Order storage ask, uint256 fillSize, uint256 fillPrice) internal {
        // 1. Calculate proportional margin to release
        uint256 bidFillMargin = (bid.margin * fillSize) / bid.size;
        uint256 askFillMargin = (ask.margin * fillSize) / ask.size;
    
        // 2. Release from vault to enable settlement
        marginVault.releaseMargin(bid.trader, bidFillMargin);
        marginVault.releaseMargin(ask.trader, askFillMargin);
    
        // 3. Update order state
        bid.margin -= bidFillMargin;
        bid.size -= fillSize;
        ask.margin -= askFillMargin;
        ask.size -= fillSize;
    
        // 4. Trigger settlement for the position
        marginVault.settlePosition(bid.trader, ask.trader, fillPrice, fillSize, bid.leverage, ask.leverage);
    }
    

    Next steps

    • Implement an orderIdToHeapIndex mapping to enable O(1) order cancellations.
    • Add a revert check in the placeOrder function to detect self-crosses before they reach the heap.
    • Write a property-based test to ensure the sum of orders.margin matches the marginVault balance.

    Connects securely to your tools. The creator never sees your data.

    About this skill

    Building a central limit order book on-chain presents significant challenges regarding gas limits, heap integrity, and self-match denial-of-service. This skill provides the architectural patterns and Solidity logic required to implement a gas-safe matching engine for spot or perpetual markets. It focuses on maintaining price-time priority while preventing the unbounded loop vulnerabilities that often brick decentralized exchanges.

    What it does

    • Heap-based matching implements max-heaps for bids and min-heaps for asks to achieve O(1) best price access.
    • Gas-bounded loops enforces strict limits on matching cycles to prevent transaction exhaustion during high volatility.
    • Self-match prevention provides logic to handle or reject trades where the same address is on both sides of a cross.
    • Margin management handles the proportional locking and releasing of collateral during partial or full order fills.
    • Heap integrity ensures correct O(log n) sifting during arbitrary order cancellations or removals.

    How it works

    1. Initialize the book by defining the order structs and binary heap storage structures for bids and asks.
    2. Execute match cycles using a bounded loop that respects a MAX_MATCHES_PER_CALL constant to ensure gas safety.
    3. Manage margin flow by releasing precise collateral amounts from the vault back to settlement upon fill completion.
    4. Maintain order priority using a comparator that breaks price ties with order timestamps.

    Frameworks & tools

    The skill is designed for Solidity development environments like Foundry or Hardhat. It assumes a separate vault or margin account contract for collateral custody.

    Why this beats prompting it yourself

    Writing an order book from scratch often leads to O(n) scan loops or heap corruption during cancellations. This skill provides specific, tested patterns for sifting heaps in both directions and managing self-match DoS vectors that generic prompts usually miss.

    Use cases

    • Building a high-performance spot DEX with limit order functionality.
    • Implementing an on-chain perpetuals exchange requiring precise margin settlement.
    • Developing a gas-optimized liquidity layer for DeFi protocols.

    Known limitations

    The provided O(1) cancel logic requires an additional mapping for index tracking which increases gas on placement. Depth views require off-chain sorting or temporary heap copies to display a proper price ladder.

    Find more skills like this on the Claude Skills Marketplace, the Codex Skills Marketplace and the Gemini Skills Marketplace, or browse Claude Skills for Web3 & Crypto.

    Requires an orderId to heapIndex map for O(1) cancels. Depth views are heap-ordered, not price-ordered, unless processed off-chain or via temporary pops.

    How to use

    1. 1

      Connect your agent to the Agensi MCP

      Copy the prompt and paste it into Claude, ChatGPT, Cursor or any agent that supports MCP. It sets up the connection for you. Manual setup

    2. 2

      Sign in to Agensi

      Your agent shows a sign-in link. Sign in and click Allow.

    3. 3

      Ask for what you need

      Your agent loads this skill and uses it on your task. It always asks before buying a skill.

    Reviews

    No reviews yet

    Be one of the first to try it. Every listed skill goes through the trust checks below.

    Security scanned

    Checked by our 8-point scan before listing

    Fresh listing

    Recently published to Agensi

    Free to use

    No account required to browse

    Trust & safety

    Security scan

    Security scan passed 19 days ago

    • Free with an Agensi account

    Permissions

    No special permissions declared or detected

    Listed19 days ago
    Updated17 days ago

    What's inside

    Frequently Asked Questions

    This skill solves the 'gas limit' problem by using bounded match loops and O(log n) heap operations, preventing the transaction failures and 'bricked' contracts common in naive on-chain order book designs.

    The purchase includes the core Solidity architecture, optimized binary heap logic for bid/ask management, and the specific state-handling patterns required for secure margin settlement and self-match prevention.

    Yes, while designed for EVM-compatible environments like Foundry and Hardhat, the architectural patterns can be adapted for any smart contract platform that supports stateful storage and binary logic.

    The engine assumes the existence of an external vault or margin account; it focuses strictly on the matching logic and collateral release signals, allowing you to plug it into your existing liquidity or custody layer.

    This skill is optimized for AI agents capable of generating and auditing Solidity code, providing them with the necessary constraints and heap-sifting logic to build high-performance DeFi protocols without manual debugging.

    New in Web3 & Crypto

    Free