> 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/state-reads-and-quoting.md).

# State Reads and Quoting

Use one explicit block context for identity, fee, AMM and account reads. This page owns the direct V4 discovery and quotation reference; LP ledger interpretation is covered in [Providing Liquidity](https://docs.peach.ag/documentation/arc/adaptive-pools/core-features/providing-liquidity) and [Fees & Claims](https://docs.peach.ag/documentation/arc/adaptive-pools/core-features/fees-and-claims).

### SDK reads and selected-pool quotes

Use the client initialized in [Quickstart](https://docs.peach.ag/documentation/arc/adaptive-pools/quickstart). SDK discovery uses its configured Registry; direct PoolManager event discovery below is a separate path. All SDK reads return `{ block, data }`.

```typescript
import type { MarketClient } from "@masterpeach/market-sdk";
import type { Hex } from "viem";

export async function readPool(client: MarketClient, poolId: Hex) {
  const pool = await client.getPool(poolId);
  if (pool.data.hookKind === null) throw new Error("Unsupported Hook");
  const [state, fees, session] = await Promise.all([
    client.getPoolState(poolId, pool.block),
    client.getCurrentFees(poolId, pool.block),
    client.getSession(poolId, pool.block),
  ]);
  return { block: pool.block, pool: pool.data, state: state.data,
    fees: fees.data, session: session.data };
}
```

`getPoolState` needs a configured StateView or extsload layout; the Arc preset supplies extsload. `activeLiquidity` is not TVL, and `storedLpFeePips` is not the directional execution fee. `getCurrentFees` and Reader-based `getFeeBreakdown` exclude the Mid-block surcharge. Use `quoteSwap` / `quoteSwapExactOutput` for actual selected-pool amount estimates, followed by the checked prepare/submit flow in Quickstart. `gasEstimate` is Quoter swap gas, not the complete transaction gas limit.

Pin related reads to the returned block. For a new refresh, start from latest rather than mixing snapshots; RPC errors, missing state and reorgs are errors, not zero-valued pool data. The SDK reuses fixed-block view reads, but does not poll. Cache by chain, deployment and business key; refresh visible queries after relevant receipts/configuration changes and re-quote at confirmation. Do not poll every field on every block.

The direct ABI/storage/simulator reference below is pinned to contract source `314ed215`. Use the SDK's `/abi` exports and configured deployment for SDK 1.0.1; do not substitute a minimal ABI from another source version.

### Discovery and admission

Read `Initialize(bytes32,address,address,uint24,int24,address,uint160,int24)` logs from the canonical PoolManager, filtering by supported Hook. Preserve numeric currency order and compute:

```
PoolId = keccak256(abi.encode(currency0, currency1, uint24(fee), int24(tickSpacing), hooks))
```

Use Ethereum Keccak-256, not NIST SHA3-256. This is normal ABI encoding: five 32-byte words, with a sign-extended int24. It is not packed encoding. `cast abi-encode 'f(address,address,uint24,int24,address)' ...` followed by `cast keccak` reproduces it. [Contract Address](https://docs.peach.ag/documentation/arc/adaptive-pools/contract-address) provides the fields for the two Arc example PoolKeys.

Check chain ID, Hook code, `hook.poolManager()`, dynamic fee mode, configured pool and initialized state. A matching address suffix alone is not sufficient admission. `pokeFloor`, `maxFee` and `currentFee` revert `PoolNotConfigured` for an unset Hook configuration; treat this as unavailable, not zero fee. Configuration can exist before PoolManager initialization; conversely, do not infer tradability merely from a discovered address or event. Initialization validates configuration in this pinned Hook version.

Peach Registry registration is a front-end/indexing concern. It is not checked by this swap path. Enumerate liquidity from normal v4 state: current sqrt-price, tick, active liquidity, tick bitmap and initialized tick liquidity deltas. Zero current liquidity alone need not rule out reachable liquidity across ticks; run the normal v4 stepping algorithm or Quoter rather than treating ERC20 balances or LP shares as reserves.

### Hook execution interface

The pinned Ramp, RampETH and RwaRamp enable only beforeInitialize and beforeSwap, permission bits 0x2080. They return zero custom before-swap delta and have no afterSwap callback. beforeSwap returns executionFee | 0x400000 as the LP fee override; strip the override flag before passing the rate to swap math. Callbacks are restricted to PoolManager and hookData can be empty. Full router settlement is introduced in [Quickstart](https://docs.peach.ag/documentation/arc/adaptive-pools/quickstart).

### Read interfaces

The signatures below are sufficient to construct a minimal ABI. All Hook reads are `view`; tuple components must retain the stated order. A pool identifier is `bytes32`.

```solidity
poolManager() returns (address)
ABSOLUTE_MAX_FEE() returns (uint24)
autonomousFee(bytes32 poolId, bool zeroForOne) returns (uint256)
currentFee(bytes32 poolId, bool zeroForOne) returns (uint24)
executionFee(bytes32 poolId, bool zeroForOne) returns (uint24)
flatFee(bytes32 poolId) returns (uint24)
pokeFloor(bytes32 poolId) returns (uint24)
maxFee(bytes32 poolId) returns (uint24)
pokeOf(bytes32 poolId) returns (uint24 fee0For1, uint24 fee1For0, uint40 expiry)
pausedUntil() returns (uint256)
pausedUntilOf(bytes32 poolId) returns (uint256)
poolAsymmetry(bytes32 poolId) returns (uint24 premiumPips, bool premiumZeroForOne)
midBlockConfig(bytes32 poolId) returns
    (bool enabled, uint24 midThresholdPips, uint24 captureFractionE6, uint24 midCap)
midBlockState(bytes32 poolId) returns (uint160 sqrtPriceX96, uint96 blockNumber)
```

Additional RWA reads:

```solidity
marketCalendar() returns (address)
openSec(bytes32 poolId) returns (uint32)
closeSec(bytes32 poolId) returns (uint32)
dstMode(bytes32 poolId) returns (uint8) // AUTO=0, FIXED_EST=1, FIXED_EDT=2
sessionAt(bytes32 poolId, uint256 timestamp) returns (uint8) // OPEN=0, OVERNIGHT=1, CLOSED=2
dayOverride(bytes32 poolId, uint256 year, uint256 month, uint256 day) returns (uint8)
earlyClose(bytes32 poolId, uint256 year, uint256 month, uint256 day) returns (uint32)
floorConfig(bytes32 poolId) returns (FloorConfig)
// FloorConfig tuple: uint24 openFloor, uint24 overnightFloor, uint24 closedFloor,
// uint8 spikeMult, uint24 closedSpike, uint32 descentWindow,
// uint24 closeFloor, uint32 closeBefore, uint32 closeAfter.
```

These are ABI signature summaries, not a compilable Solidity interface declaration. For JSON ABIs, compile the corresponding contracts at the pinned source version.

### Minimum state acquisition

All reads in a refresh must use one explicit block number/hash. Obtain its timestamp from the block header or Multicall's clock; do not mix local wall time with historical getter results. Apply the same state overrides to every dependent `eth_call`. Where supported, use block-hash pinning; otherwise pin the number, check its hash before/after, and discard a reorganized snapshot.

| State                  | Read/source                                                                  | Purpose                                                    |
| ---------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------- |
| Identity               | chain ID, bytecode, `poolManager()`; Initialize PoolKey                      | Scope and pool identity                                    |
| Ordinary fees          | both directions of `currentFee`, `autonomousFee`                             | Fee snapshot and consistency check                         |
| Boundaries             | `pokeFloor`, `maxFee`, `ABSOLUTE_MAX_FEE`                                    | Keeper resolution and final cap                            |
| Keeper                 | `pokeOf`                                                                     | Both sides and exclusive expiry                            |
| Pause                  | `pausedUntil`, `pausedUntilOf`                                               | Refuse swaps while timestamp is below either deadline      |
| Mid-block              | `midBlockConfig`, and `midBlockState` for current-block replay               | Policy, reference price and observation block              |
| AMM                    | PoolManager slot0, liquidity, bitmap and initialized ticks                   | Standard v4 price movement and liquidity crossing          |
| RWA local reproduction | `floorConfig`, `openSec`, `closeSec`, `dstMode`, `dayOverride`, `earlyClose` | Calendar for relevant dates, including previous local date |

Fee snapshots sampled from `autonomousFee` already include the directional premium. Do **not** add it again. If reproducing raw policy, read `poolAsymmetry` and calendar configuration instead; read `flatFee(poolId)` for the stored flat base used by Ramp/RampETH; RwaRamp instead derives its autonomous base from the calendar configuration. `currentFee` must agree with resolving the sampled autonomous and keeper values at the same timestamp. Required-call failures invalidate a new snapshot; never overwrite a good snapshot with fabricated zero values. An unusably stale snapshot should not continue to generate executable quotes.

### PoolManager storage reads

Use the exact pinned v4 `StateLibrary`, or a correctly deployed StateView. PoolManager does not expose a direct `getSlot0(poolId)` ABI method. Use `extsload(bytes32) returns (bytes32)`:

```
stateSlot = keccak256(abi.encode(poolId, uint256(6)))
word = PoolManager.extsload(stateSlot)
sqrtPriceX96 = word & (2^160 - 1)
tick = signExtend24((word >> 160) & 0xffffff)
protocolFee = (word >> 184) & 0xffffff
storedLPFee = (word >> 208) & 0xffffff
activeLiquidity = extsload(stateSlot + 3) & (2^128 - 1)
```

Ticks and bitmap mappings begin at offsets 4 and 5 respectively; use StateLibrary's signed-key encoding and traversal. Stored slot0 LP fee is not a replacement for the dynamic Hook override. This quotation reference assumes zero PoolManager protocol fees. Read the actual protocolFee field and implement nonzero protocol-fee composition before supporting pools that use it.

### Refresh scheduling

Invalidate/update on PoolManager Initialize/Swap/ModifyLiquidity and reorgs; use swaps to keep price/tick/liquidity current. Hook events include `PoolConfigured` (different overload for RWA), `PoolAsymmetrySet`, `FeePoked`, `PokeCleared`, `MidBlockConfigSet`, `PausedSet`, `PoolPausedSet`, plus RWA `SessionHoursSet`, `DstModeSet`, `DayOverridesSet`, `EarlyCloseSet`. Use these events from the pinned contract ABI. Use originating Hook events for calendar writes; the immutable calendar is controlled by that Hook.

Time changes fees without events. SDK reads do not start polling. Refresh visible displays as needed and obtain a fresh amount quote before user confirmation; for a maintained local RWA quoting engine, update time-sensitive policy at the next second or earlier relevant expiry. Keep its block/timestamp assumptions explicit. Recomputing a keeper from a previously sampled autonomous value cannot predict later calendar/configuration changes, and no polling frequency guarantees execution parity.

### Chain simulation path

Chain Quoter addresses are maintained in [Contract Address](https://docs.peach.ag/documentation/arc/adaptive-pools/contract-address#quoter-addresses).

The Quoter ABI uses one tuple argument:

```
quoteExactInputSingle(((address,address,uint24,int24,address),bool,uint128,bytes))
quoteExactOutputSingle(((address,address,uint24,int24,address),bool,uint128,bytes))
```

Tuple order: `(PoolKey, zeroForOne, exactAmount, hookData)`; PoolKey order is `(currency0, currency1, fee, tickSpacing, hooks)`. Return values are `(uint256 amountOut, uint256 gasEstimate)` for exact-input and `(uint256 amountIn, uint256 gasEstimate)` for exact-output.

Call the verified chain's canonical Quoter with the PoolKey, direction, `uint128 exactAmount` and empty hookData. Both `quoteExactInputSingle` and `quoteExactOutputSingle` are non-view functions intended here to be invoked through **`eth_call`**; do not send a transaction just to request a quote. Quoter state writes occur in the temporary simulation and do not persist.

The exact-input response is `(amountOut, gasEstimate)`; exact-output is `(amountIn, gasEstimate)`. Quoter simulation includes real Hook callbacks and the target block's state. Independent calls do not share accepted mutations; simulating a multi-leg same-pool sequence requires one coherent simulated execution or a local simulator, not a series of independent eth\_calls.

### Local amount calculation and rounding

After selecting the Hook LP fee once for a swap, run the pinned Uniswap v4 `Pool`, `SwapMath`, `SqrtPriceMath`, `TickMath`, `FullMath` and tick traversal behavior. Preserve input/output integer rounding, price limits, liquidity-net sign when crossing ticks and unspent input. No separate Peach pricing curve changes the AMM deltas.

For a normal exact-input step with remaining input `R` and fee `f < 1e6`:

```
availableForPriceMovement = floor(R * (1e6-f) / 1e6)
if this reaches the step's target price:
    stepFee = ceil(stepAmountIn * f / (1e6-f))
else:
    stepAmountIn = availableForPriceMovement
    stepFee = R - stepAmountIn
```

Exact-output also rounds input/fee upward and caps output to remaining requested output. These expressions describe the fee portion of each step; they do not replace sqrt-price calculations, output rounding or tick crossing. In particular `amountOut = amountIn * (1-fee)` is not a swap quote.

Reject zero-output quotes for routing, even if EVM simulation returns a successful zero delta. Canonical Quoter insists on the full specified fill and can revert `NotEnoughLiquidity(bytes32)`. A local engine may expose a partial fill, but must return the actual consumed input and nonzero remaining input explicitly; never label it a full fill. Do not convert arbitrary reverts into “insufficient liquidity”: distinguish pause, missing configuration, invalid price/limits, RPC errors and actual liquidity exhaustion.

Source: [BaseHook read methods](https://github.com/peachbuild/adaptive-pools/blob/314ed2151367d3edb6f9045f05f5eb18567f5aa6/src/hooks/BaseHook.sol). Match the exact ABI and target deployment; the SDK has its own versioned ABI provenance.


---

# 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/state-reads-and-quoting.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.
