> For the complete documentation index, see [llms.txt](https://docs.peach.ag/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.peach.ag/documentation/arc/adaptive-pools/core-features/mid-block-policy-and-observations.md).

# Mid-block Policy and Observations

Mid-block policy is an optional surcharge for swaps that move the price back toward the opening reference of the same execution block. It is evaluated from the **pre-swap** price, so it depends on transaction ordering as well as the ordinary fee.

### When the surcharge applies

| Situation                                                                    | Result                                               |
| ---------------------------------------------------------------------------- | ---------------------------------------------------- |
| Policy disabled, capture fraction zero or cap zero                           | No surcharge.                                        |
| First successful swap of a new block                                         | Seeds the opening reference and pays no surcharge.   |
| Later swap moves away from the reference, or displacement is below threshold | No surcharge.                                        |
| Later swap moves toward the reference and displacement meets the threshold   | Apply the calculated extra, then the final pool cap. |

The selected fee applies to the whole swap; crossing the reference during tick traversal does not reprice it. The following is the complete calculation and simulator reference.

### Exact calculation

The configuration is `(enabled, midThresholdPips, captureFractionE6, midCap)`. It is disabled by default, including the all-zero unconfigured tuple. An explicit setter requires threshold 1..1,000,000, fraction 0..1,000,000, and midCap no greater than the deployment absolute cap. Fraction or cap zero produces no surcharge even if enabled.

Let `S0` be the block's stored opening sqrtPriceX96 and `S` the current **pre-swap** sqrtPriceX96. Use integer square prices with at least 320-bit square precision (and sufficient intermediate multiplication precision), or arbitrary-precision integers:

```
dev = floor(abs(S*S - S0*S0) * 1_000_000 / (S0*S0))
returning = (S > S0 and zeroForOne) or (S < S0 and not zeroForOne)
extra = 0
if S0 != 0 and S != S0 and returning and dev >= midThresholdPips:
    extra = min(floor(dev*captureFractionE6/1_000_000), midCap)
executionFee = min(ordinary + extra, poolCap)
```

For `S0=10000`, `S=10100`, dev=20,100 pips. With threshold=1000 and fraction=500000, extra=10,050 before caps. The return direction is 0→1; the opposite direction pays no extra. With ordinary=450 and poolCap=6000, executionFee=6000. The raw currency1/currency0 price is `S² / 2^192`; its human-unit price multiplies this by `10^(decimals0-decimals1)`. Q96 scale and token decimal factors cancel in relative displacement; do not apply decimal scaling inside this formula. Threshold equality qualifies; each integer division floors separately. Tick differences or a rounded sqrt ratio are not substitutes.

The deployed pure helper uses a capped binary search over full-width products; the formula above gives the same capped fee without computing a bounded displacement approximation. `executionFee` calls it with a 200,000 gas allowance and a fixed 32-byte result buffer. If the helper fails, returns a size other than 32 bytes, or yields extra > midCap, execution falls back to the **ordinary** fee. Other Hook errors, including pause/configuration, are not swallowed.

When enabled, `beforeSwap` seeds `S0` from PoolManager's pre-swap price if the stored block differs from `block.number` or its opening price is zero. This first successful swap has zero surcharge because its current price equals its new reference. Every subsequent successful swap in that block retains that reference and uses its own pre-swap price. Crossing the reference inside a swap does not split/reprice that swap: the chosen fee applies to its entire tick-stepping calculation.

### State transition contract for a local simulator

Key observations by `(chainId, PoolManager, PoolId)` and execution block. Keep price/tick/liquidity and Hook observations together for each route branch.

```
quote(state, swap):
    check configuration and pause at the chosen execution timestamp
    candidate = state observation
    if enabled and observation absent/stale/zero:
        candidate = (executionBlock, preSwapSqrtPrice)
    calculate ordinary and Mid-block fee using candidate
    run standard v4 swap math -> deltas, remaining input, next pool state
    return result + candidate state, without mutating shared state

accept(result): commit the result's pool state and observation
failed swap / reverted transaction: discard all of its state effects
clone branch: isolate every mutable pool/Hook state object
new execution block: old observation does not apply
setMidBlockConfig: clears the stored observation, even in the same block
```

Changing ordinary pool fee/asymmetry/keeper settings does not itself clear the Mid-block observation. Only `setMidBlockConfig` explicitly does so in this version; do not reset a historical replay merely because a generic fee event occurred. When Mid-block is disabled, swaps do not seed a new observation.

Two supported modeling contexts must be kept distinct:

* **Historical/current-block replay:** import the actual `midBlockState` and the target block number, price and timestamp. Apply the exact on-chain block comparison. A Quoter `eth_call` at block B runs in B's context and can see B's observation; it is not automatically a B+1 quote.
* **New-block route simulation:** start with no observation. The first accepted swap seeds its pre-price; later accepted swaps in the same branch/block reuse it. This is an explicit execution-order assumption, not an assertion about real ordering.

An external swap earlier in the actual execution block can create/change the reference and current price. Neither a sampled getter nor this convention predicts transaction order. Re-quote when needed and enforce router-level minimum output/maximum input and deadlines.

### SDK quoting boundary

`getCurrentFees` and `getFeeBreakdown().data.finalFeePips` exclude this surcharge. Use the selected PoolKey with `quoteSwap` / `quoteSwapExactOutput`, then the checked preparation and user-confirmed submission flow in [Quickstart](https://docs.peach.ag/documentation/arc/adaptive-pools/quickstart). Never add a separately estimated surcharge to an already fee-aware quote.

A Quoter call at block B uses B's state and observation; it does not guarantee ordering in the block where the transaction lands. Keep user-approved `minAmountOut` / `maxAmountIn` and a fresh deadline. Quoter `gasEstimate` covers the inner swap, not the complete Router transaction.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.peach.ag/documentation/arc/adaptive-pools/core-features/mid-block-policy-and-observations.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
