# Match Limits

## Overview

The OrderBook contract implements sophisticated order execution controls including match limits to manage gas consumption and various execution types to meet different trading strategies.

## Match Limits

OrderBook now supports limiting the number of matches per transaction to manage gas consumption and provide more control over order execution:

```solidity
function buyLimit(
    uint256 baseAmount,
    uint256 price,
    bool postOnly,
    ExecutionType executionType,
    MatchLimitBehavior behavior,
    uint256 maxMatches // Maximum number of maker orders to match against
) external
```

### Why Match Limits?

* **Gas Management**: Prevents transactions from failing due to gas limits when matching against many small orders
* **Predictable Costs**: Traders can estimate maximum gas costs for their transactions
* **MEV Protection**: Limits the complexity of sandwich attacks
* **Fair Execution**: Ensures large orders don't monopolize block space

### Match Limit Behaviors

When the match limit is reached, the order behaves according to the specified `MatchLimitBehavior`:

#### Cancel

* Cancels the remainder and refunds collateral
* Emits `OrderCancelled`

#### PlaceAtLast

* Places the remaining unfilled portion at the last checked price level
* Useful for completing partial fills without moving to worse prices
* The order joins the queue at that specific price level

### Match Counting

Each successful match against a maker order counts as one match:

* A match that fully fills a maker order = 1 match
* A match that partially fills a maker order = 1 match
* Skipped orders (due to STP or other reasons) don't count

## Execution Types

OrderBook supports three execution types that determine how unfilled portions of orders are handled:

### Standard Execution

```solidity
ExecutionType.Standard
```

* Order remains on the book if not fully filled
* Becomes a maker order at the specified limit price
* Most common type for limit orders

### Immediate-Or-Cancel (IOC)

```solidity
ExecutionType.IOC
```

* Executes immediately against available liquidity
* Any unfilled portion is automatically cancelled
* Never becomes a maker order
* Useful for avoiding maker fees or ensuring immediate execution

### Fill-Or-Kill (FOK)

```solidity
ExecutionType.FOK
```

* Must be completely filled or the entire transaction reverts
* No partial fills allowed
* Guarantees complete execution at specified price or better
* Common for large trades that need full execution

## Usage Examples

### Example 1: Large Buy Order with Gas Limit

```solidity
// Buy 1000 tokens, match with max 10 orders, place remainder at best bid
buyLimit(
    1000e18,           // baseAmount
    150e18,            // price (max 150 per token)
    false,             // not postOnly
    ExecutionType.Standard,
    MatchLimitBehavior.PlaceAtBest,
    10                 // maxMatches
);
```

### Example 2: IOC Order with Match Limit

```solidity
// Sell tokens with immediate execution only, max 5 matches
sellLimit(
    500e18,            // baseAmount
    140e18,            // price (min 140 per token)
    false,             // not postOnly
    ExecutionType.IOC,
    MatchLimitBehavior.RevertOnLimit,
    5                  // maxMatches
);
```

### Example 3: FOK Order for Exact Fill

```solidity
// Buy exactly 100 tokens or revert
buyLimit(
    100e18,            // baseAmount
    155e18,            // price
    false,             // not postOnly
    ExecutionType.FOK,
    MatchLimitBehavior.RevertOnLimit,
    20                 // maxMatches (high limit for FOK)
);
```

## Self-Trade Prevention Integration

Match limits work seamlessly with STP modes:

* **EXPIRE\_MAKER**: Expired orders count toward match limit
* **SKIP**: Skipped orders do NOT count toward match limit
* **NONE**: All matches count normally

## Gas Optimization

Recommended `maxMatches` values:

* **Small orders**: 5-10 matches
* **Medium orders**: 10-20 matches
* **Large orders**: 20-50 matches
* **FOK orders**: Higher limits (50+) to ensure completion

## Events

The OrderBook emits events related to match limits:

```solidity
event MatchLimitReached(
    uint64 indexed orderId,
    uint256 matchesUsed
);
```

This event is emitted when an order reaches its match limit, helping track partial executions.

## Best Practices

1. **Set Reasonable Limits**: Balance between execution completeness and gas costs
2. **Use PlaceAtBest**: For orders that should become makers after partial fills
3. **Use RevertOnLimit with FOK**: For guaranteed full execution within limits
4. **Monitor Events**: Track MatchLimitReached events for partial fills
5. **Consider Market Depth**: Set limits based on typical order book depth

## Technical Implementation

The match limit system is implemented in the core matching engine:

1. **Match Counter**: Tracks matches during order execution
2. **Early Termination**: Stops matching when limit is reached
3. **Behavior Handling**: Applies specified behavior for remaining amount
4. **State Updates**: Properly updates order state and book structure
5. **Event Emission**: Notifies about limit-related outcomes


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://world-book.gitbook.io/worldbook/technical-documentation/orderbook-contract/match-limits.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
