- Home
- Skills
- Web3 & Crypto
- On-Chain Central Limit Order Book Matching Engine
Works with the AI Agents you already use
On-Chain Central Limit Order Book Matching Engine
Gas-safe on-chain matching engine using binary heaps, bounded match loops, and proportional margin settlement.
Free
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)
| Strategy | Logic | Outcome |
|---|---|---|
| Skip Counter | Tracks selfMatchSkips vs heap.length | Prevents OOG DoS |
| Placement Rejection | Reverts if new order crosses own resting | Keeps book clean |
| Cancel-on-Cross | Removes resting order before fill | Optimal 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
orderIdToHeapIndexmapping to enable O(1) order cancellations. - Add a
revertcheck in theplaceOrderfunction to detect self-crosses before they reach the heap. - Write a property-based test to ensure the sum of
orders.marginmatches themarginVaultbalance.
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
- Initialize the book by defining the order structs and binary heap storage structures for bids and asks.
- Execute match cycles using a bounded loop that respects a
MAX_MATCHES_PER_CALLconstant to ensure gas safety. - Manage margin flow by releasing precise collateral amounts from the vault back to settlement upon fill completion.
- 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.
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
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
Sign in to Agensi
Your agent shows a sign-in link. Sign in and click Allow.
- 3
Ask for what you need
Your agent loads this skill and uses it on your task. It always asks before any payment.
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 forever
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