> 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/quickstart.md).

# Quickstart

Discover a pool, pin state, request a quote and prepare V4 router settlement.

Use the Market SDK for one selected pool. Start with read-only discovery; request wallet transactions only after the user reviews the amounts, recipient and limits. For LP operations, continue with [Providing Liquidity](https://docs.peach.ag/documentation/arc/adaptive-pools/core-features/providing-liquidity).

### Install and initialize

These examples follow SDK `1.0.1` and reviewed `main` commit `b5fc5ba`. Requirements: Node.js 20+, viem `>=2.45.0 <3`, and an Arc mainnet RPC (chain ID `5042`). Use the root package export.

```bash
pnpm add @masterpeach/market-sdk@1.0.1 'viem@^2.45.0'
```

Inject your application's existing viem clients. Omit `walletClient` for browsing.

```typescript
import {
  createMarketClient, marketArcMainnet,
  type MarketClient, type MarketPreparedTransaction, type MarketSwapQuoteParams,
} from "@masterpeach/market-sdk";
import type { Address, Hex, PublicClient, WalletClient } from "viem";

export async function initializeMarket(
  publicClient: PublicClient, walletClient?: WalletClient,
) {
  const client = createMarketClient({
    publicClient, walletClient, chain: marketArcMainnet, prepare: true,
  });
  await client.verifyDeployment();
  return client;
}
```

**Keep `prepare: true` for these transaction examples.** The SDK defaults to `false`, which encodes and sends without SDK live account/network, balance/allowance, freshness or transaction-simulation preflight. Checked mode does not implicitly verify deployment bytecode/bindings; `verifyDeployment()` above is separate and does not grant capabilities or guarantee execution.

Keep the same client through preparation, submission and receipt recovery. On account/network/deployment changes, create a new client and discard old quotes and prepared requests; retain the old client and transaction hash for pending receipts.

### Discover and review a swap

Use `listPools({ activeOnly: true })` and let the user choose a supported pool; obtain its complete `key` with `getPool(poolId)`. Continue pagination until `nextOffset === null`, even after an empty filtered page. Registration or an RWA `closed` session does not establish whether a swap can execute. The current preset's test-asset catalog is empty; do not hard-code a former test pool.

This helper prepares an exact-input swap for review. `input` contains the selected PoolKey, explicit direction, bigint token-base-unit `amountIn`, and the user's `slippageBps` (`50` means 0.5%).

```typescript
export async function reviewSwap(
  client: MarketClient, input: MarketSwapQuoteParams, owner: Address,
) {
  const quote = await client.quoteSwap(input);
  const spend = await client.getSwapSpendStatus({ ...input, owner, ...quote.block });
  if (!spend.data.sufficientBalance) throw new Error("Insufficient input balance");
  if (spend.data.needsTokenApproval || spend.data.needsRouterApproval)
    throw new Error("Confirm required approvals, then request a fresh quote");
  const prepared = await client.prepareSwap({
    key: input.key, zeroForOne: input.zeroForOne, amountIn: input.amountIn,
    minAmountOut: quote.data.minAmountOut, recipient: owner,
    deadline: quote.block.timestamp + 180n,
  });
  if (!prepared.context.preflight) throw new Error("Use prepare: true");
  if (prepared.request.account.toLowerCase() !== owner.toLowerCase())
    throw new Error("Wallet account changed; refresh and prepare again");
  return { quote, prepared };
}
```

`zeroForOne=true` means currency0 → currency1. Derive buy/sell with `getMarketSwapDirection(key, base, quote, side)`; symbols do not determine direction. Quotes already include trading fees. The 180-second on-chain deadline is an example validity window, not a promise that a quote remains fresh that long.

#### Confirm approvals before refreshing

For ERC-20 swaps there are **two separate allowances**:

| Spend-status flag     | Prepare only after user approval                                                                           |
| --------------------- | ---------------------------------------------------------------------------------------------------------- |
| `needsTokenApproval`  | `prepareSwapTokenApproval({ key, zeroForOne, amount })`: token → Permit2                                   |
| `needsRouterApproval` | `prepareSwapRouterApproval({ key, zeroForOne, amount, expiration })`: Permit2 → the configured swap Router |

Approve the full intended allowance, not the shortfall; `amount` replaces the old value. Use the reviewed input limit and a short explicit Permit2 expiration. Reset-required tokens need a separately confirmed zero approval first. Native input needs no token approval. LP and Zap approvals use different spenders; do not reuse this approval flow for them.

Confirm every approval receipt, then call `reviewSwap` again. Show the fresh quote, minimum output, recipient, maximum spend, deadline and gas cost before asking the user to confirm submission. A changed quote requires another review; never reduce a limit silently.

### Submit and confirm

Call this helper only from a user-confirmation handler. Persist the hash immediately using `onSent`; retain it if waiting fails.

```typescript
export async function submitConfirmed(
  client: MarketClient, prepared: MarketPreparedTransaction,
  onSent: (hash: Hex) => void | Promise<void>,
) {
  if (!prepared.context.preflight) throw new Error("Use prepare: true");
  const hash = await client.send(prepared);
  try { await onSent(hash); }
  catch (cause) {
    throw new Error(`Already sent: ${hash}; save it and resume tracking before retrying.`, { cause });
  }
  const result = await client.waitForTransaction(hash);
  if (result.status !== "confirmed") throw new Error("Transaction reverted");
  return result;
}
```

For a swap, display actual settled `result.swap` amounts rather than preview amounts. A reverted transaction can still consume gas. On timeout, resume receipt tracking for the same hash and client. If broadcasting is ambiguous, check wallet history and chain state before offering another submission; never automatically retry a funds operation.

### Other execution modes

For exact output, use `quoteSwapExactOutput` and `prepareSwapExactOutput`; check balance and both allowances against **`quote.data.maxAmountIn`**, enforce the user's hard input budget, and pass that maximum with `amountOut`, `recipient` and a fresh deadline. Do not reuse exact-input approval amounts.

Market SDK swaps use a selected PoolKey and the configured Quoter/Universal Router; they do not discover cross-pool routes. Native currency is address zero, distinct from its wrapped ERC-20; native spending must leave enough funds for gas. The Arc preset has no RampETH Hook. Never bypass an unsupported Hook, missing capability, paused operation or failed simulation by turning off preflight.

See [State Reads and Quoting](https://docs.peach.ag/documentation/arc/adaptive-pools/core-features/state-reads-and-quoting) for fixed-block reads and direct V4 details; [Contract Address](https://docs.peach.ag/documentation/arc/adaptive-pools/contract-address) owns deployment references. Source: [Market SDK at the reviewed main commit](https://git.techpilots.org/web/peach/peach-ts-sdk/-/tree/b5fc5bacdbee2364128044a4afe793682fa323f4/packages/market).

### Direct V4 integration reference

For direct V4 integrations on Arc, `PoolId = keccak256(abi.encode(currency0, currency1, uint24(fee), int24(tickSpacing), hooks))`. Use the complete ordered PoolKey from Contract Address. The Quoter below is the recorded reference-comparison endpoint, not a claim of current deployment or execution verification.

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. The Contract Address page provides all fields for both example PoolKeys.

Default and RWA Hooks reject native currencies during initialization. A v4 router must unlock PoolManager, call swap, settle negative currency deltas and take positive deltas. Use ERC20 allowance and settlement for ERC20 input.

`hookData` requires no authentication payload and can be empty. Route to PoolManager through a compatible router, not by calling the Hook's `beforeSwap` directly. That callback is restricted to PoolManager. At core level, negative `amountSpecified` is exact-input and positive is exact-output. The contract fee policy applies to both. At a 100% execution fee, exact-output is rejected by v4 core and exact-input cannot produce a useful positive-output quote.

| Chain    | Quoter used by the reference comparisons     |
| -------- | -------------------------------------------- |
| Arc 5042 | `0x8Dc178eFB8111BB0973Dd9d722ebeFF267c98F94` |


---

# 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/quickstart.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.
