> 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/bsc/aggregator/editor/configuration-and-error-handling/sdk-reference.md).

# SDK Reference

Public SDK methods, parameters, execution types and constants.

This reference describes the public exports of `@masterpeach/aggregator-sdk` v0.3.0. Use `PeachClient` to quote, prepare, validate and submit swaps; use `ApiClient` only when you need raw service responses.

Token-pair inputs use `from` and `target`. The current signatures retain `amountIn` and nested `options` for `getQuote()`, while preparation uses `amount` and flat routing fields. Response and contract types retain their own names, such as `Quote.srcToken`, `Quote.dstToken` and `ExecutionPlan.tokenIn`; these are not input aliases.

### Constructor

`new PeachClient(config: PeachConfig, provider?: ethers.Provider, options?: PeachClientOptions)`

If omitted, the provider uses `config.rpcUrl`. `PeachConfig` requires `chainId`, `rpcUrl` and `weth`; optional `routerAddress` and `executionRouterAddress` pin the underlying and execution routers respectively. `PeachClientOptions.api` accepts `ApiClientConfig`. See [Client Configuration](https://docs.peach.ag/documentation/bsc/aggregator/editor/configuration-and-error-handling).

### Quotes and preparation

| Method                         | Parameters                                                                             | Return                                                                          |
| ------------------------------ | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| `getQuote(params)`             | `from`, `target`, `amountIn: bigint`, optional `options: QuoteOptions`                 | `Promise<Quote>`; display-only                                                  |
| `getAvailableProviders()`      | None                                                                                   | `Promise<string[]>`                                                             |
| `prepareDirectSwap(params)`    | `PrepareSwapParams`; payer must equal executor                                         | `Promise<PreparedDirectSwap>`                                                   |
| `prepareDelegatedSwap(params)` | `PrepareSwapParams` with required payer and recipient; payer must differ from executor | `Promise<PreparedDelegatedSwap>`                                                |
| `prepareSwap(params)`          | `PrepareSwapParams`                                                                    | `Promise<PreparedSwap>`; Direct when payer equals executor, otherwise Delegated |

Only exact-input quotes and swaps are supported: amounts use input-token base units as `bigint`. `byAmountIn` is not part of the public parameter types; passing `false` from JavaScript is rejected. See [Quotes and Routing](https://docs.peach.ag/documentation/bsc/aggregator/editor/quotes-and-routing).

#### QuoteOptions and Quote

<table><thead><tr><th width="246.93359375">Option</th><th width="127.72265625">Type</th><th>Behavior</th></tr></thead><tbody><tr><td><code>depth</code>, <code>splitCount</code></td><td><code>number?</code></td><td>Maximum hops and split count; defaults 3 and 20</td></tr><tr><td><code>providers</code></td><td><code>Provider[]?</code></td><td>Open string identifiers; omitted/empty means no explicit filter</td></tr><tr><td><code>includeResponseHeaders</code></td><td><code>boolean?</code></td><td>Defaults to false; includes route HTTP headers in <code>Quote.responseHeaders</code> when true</td></tr><tr><td><code>customFee</code></td><td><code>CustomFee?</code></td><td>Display projection with <code>feeAccount: string</code> and integer <code>feeBps</code> in <code>[1, MAX_FEE_BPS]</code>; also configure the execution fee during preparation</td></tr></tbody></table>

`Quote` contains `srcToken`, `dstToken`, `amountIn`, net `amountOut`, `priceImpact`, `route: SplitRoute` and `gasEstimate`. The gross output is `route.totalAmountOut`. Optional fields include router addresses, `srcNative`, `dstNative`, response headers and the custom-fee summary. Native requests use `config.weth` in the returned token addresses and route; use the native flags to render BNB. A quote contains no signed transaction or payer authorization.

`PeachClient.validateCustomFee(customFee?: CustomFee): void` is a public static helper. It accepts omission and throws `CustomFeeError` for invalid basis points, an invalid address or a zero fee account. `getQuote()` calls it before making a request.

### PrepareSwapParams

<table><thead><tr><th width="197.23828125">Field</th><th width="160.58203125">Type</th><th>Behavior</th></tr></thead><tbody><tr><td><code>from</code>, <code>target</code></td><td><code>string</code></td><td>Token address or native sentinel</td></tr><tr><td><code>amount</code></td><td><code>bigint</code></td><td>Positive exact-input amount in input-token base units</td></tr><tr><td><code>executor</code></td><td><code>string</code></td><td>Required nonzero address that calls the Execution Router</td></tr><tr><td><code>payer</code></td><td><code>string?</code></td><td>Defaults to executor</td></tr><tr><td><code>recipient</code></td><td><code>string?</code></td><td>Defaults to executor in Direct; mandatory in Delegated</td></tr><tr><td><code>depth</code>, <code>splitCount</code></td><td><code>number?</code></td><td>Route search controls; defaults 3 and 20</td></tr><tr><td><code>providers</code></td><td><code>Provider[]?</code></td><td>Open string identifiers; omitted/empty means no explicit filter</td></tr><tr><td><code>slippageBps</code></td><td><code>number?</code></td><td>Integer <code>[0, 10000]</code>; sent when supplied</td></tr><tr><td><code>deadlineSecs</code></td><td><code>number?</code></td><td>Relative seconds sent when supplied; use an explicit value</td></tr><tr><td><code>customFeeBps</code></td><td><code>number?</code></td><td>Defaults to zero; local range <code>[0, 10000]</code></td></tr><tr><td><code>customFeeReceiver</code></td><td><code>string?</code></td><td>Nonzero address required for positive fees</td></tr><tr><td><code>nativeIn</code>, <code>nativeOut</code></td><td><code>boolean?</code></td><td>Native-mode flags; the sentinel also enables the matching flag</td></tr></tbody></table>

Preparation validates token and role addresses, positive amount, slippage and fee ranges. Native input/output cannot both be enabled; Delegated native input is rejected. Native flags or the sentinel map the matching token to `config.weth`. `sender` is not accepted by the high-level preparation type. These checks do not establish route availability or deployed limits.

`slippageBps` and `deadlineSecs` are forwarded only when supplied; exported default constants are not injected. The service computes the net minimum with integer rounding: `floor(expectedAmountOut * (10000 - slippageBps) / 10000)`. The SDK checks the returned minimum against signed calldata; it does not recompute this formula. Review `prepared.amountIn`, `prepared.expectAmountOut` and the final `tx.amountOutMin` against the order before authorization. See [Slippage](https://docs.peach.ag/documentation/bsc/aggregator/editor/slippage) and [Transaction Safety](https://docs.peach.ag/documentation/bsc/aggregator/editor/validation-approvals-and-expiry).

### Approvals and execution

| Method                                                        | Return and behavior                                                                                                                                                                    |
| ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `buildDirectApprovalRequest(prepared, owner, options?)`       | `Promise<SwapApprovalRequest \| undefined>`; revalidates Direct preparation, checks owner and allowance, and otherwise builds unlimited ERC20 approval; native input needs no approval |
| `checkPermit2BaseAllowance({ payer, token, requiredAmount })` | `Promise<{ allowance: bigint; sufficient: boolean }>`; reads ERC20 allowance to canonical Permit2                                                                                      |
| `signPayerAuthorization(prepared, payerSigner)`               | `Promise<string>`; checks payer identity and signs validated typed data                                                                                                                |
| `buildDelegatedSwap(prepared, payerSignature)`                | `Promise<ReadyDelegatedSwap>`; accepts 64/65-byte signatures and validates the built transaction against the prepared artifact                                                         |
| `simulateSwap(ready, executorAddress?)`                       | `Promise<RouterExecutionReceipt>`; executor defaults from the ready object                                                                                                             |
| `executeSwap(ready, executorSigner, options?)`                | `Promise<ethers.TransactionResponse>`; validates then submits without waiting for mining                                                                                               |

Approval `owner` must equal the prepared payer. A `SwapApprovalRequest` contains `token`, `owner`, `spender`, `currentAllowance`, `requiredAmount`, `approveAmount` and `tx: SwapTxRequest`; building it does not prompt a wallet or submit it. `checkPermit2BaseAllowance()` only reads the ERC20 allowance to `PERMIT2_ADDRESS`; it does not approve or create a witness authorization.

`options` is `ExecuteSwapOptions`: optional `gasPrice?: bigint` and `gasLimit?: bigint`. It has no deadline, allowance-policy or timeout option. Server-provided `to`, `data` and `value` are preserved. `executeSwap()` verifies the executor address and submits directly to the Router; `simulateSwap()` simulates only that Router call with the prepared executor. Neither method builds or simulates an outer swap-plus-deposit transaction. Contract-executor composition and general ERC-1271 payer signatures are not verified workflows in this guide. Check the signer's network in the application before signing or submission.

### Execution types

<table><thead><tr><th width="271.46484375">Type</th><th>State and key fields</th></tr></thead><tbody><tr><td><code>PreparedDirectSwap</code></td><td><code>DIRECT_ALLOWANCE</code> / <code>TRANSACTION_READY</code>; <code>amountIn</code>, gross <code>amountOut</code>, net <code>expectAmountOut</code>, <code>approvalSpender</code>, <code>tx</code>, <code>execution</code>, <code>raw</code></td></tr><tr><td><code>PreparedDelegatedSwap</code></td><td><code>PERMIT2_WITNESS</code> / <code>PAYER_SIGNATURE_REQUIRED</code>; amounts, roles, <code>planHash</code>, <code>payerAuthorization</code>, <code>raw</code>; no transaction</td></tr><tr><td><code>ReadyDelegatedSwap</code></td><td><code>PERMIT2_WITNESS</code> / <code>TRANSACTION_READY</code>; <code>tx</code>, <code>execution</code>, <code>prepared</code>, <code>raw</code></td></tr><tr><td><code>PreparedSwap</code></td><td>Union of the two prepared types</td></tr><tr><td><code>ReadySwap</code></td><td>Union of Direct prepared and Delegated ready types</td></tr><tr><td><code>SwapTransaction</code></td><td><code>to</code>, <code>data</code>, <code>value: bigint</code>, <code>entrypoint: "executePlan"</code>, <code>amountOutMin: bigint</code></td></tr><tr><td><code>ExecutionPlan</code></td><td>Signed roles, token pair, amounts, deadline, nonce, fees and hash bindings</td></tr><tr><td><code>Permit2WitnessAuthorization</code></td><td>Owner, Permit2 contract, spender, token, amount, nonce, deadline, plan hash and typed data</td></tr><tr><td><code>RouterExecutionReceipt</code></td><td><code>planHash</code>, payer/executor/recipient, <code>tokenOut</code>, <code>requestedAmountIn</code>, <code>actualAmountIn</code>, <code>userAmountOut</code>; returned by simulation</td></tr></tbody></table>

Use `executionStatus` or `executionMode` to narrow union results. Submission returns an ethers transaction response; `wait()` returns an ethers transaction receipt. Neither is the simulation receipt.

### Read methods

| Method                                      | Return and behavior                                                                                                               |
| ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `getTokenInfo(tokenAddress, ownerAddress?)` | `Promise<{ symbol: string; decimals: number; balance?: bigint }>`; reads ERC20 metadata and optional owner balance in parallel    |
| `getBalance(tokenAddress, userAddress)`     | `Promise<bigint>`; ERC20 balance in base units                                                                                    |
| `getRouterConfig(routerAddress?)`           | `Promise<RouterConfig>`; underlying PeachRouter address, WETH, owner, pending owner, pause state, fee caps and protocol-fee split |
| `getProtocolFeeConfig(routerAddress?)`      | `Promise<ProtocolFeeConfig>`; `protocolFeeReceiver` and `protocolCutBps`, the protocol's share of the custom fee                  |

Token reads expect an ERC20 contract. Use `provider.getBalance(owner)` and 18 decimals for native BNB. Router reads require an explicit address or `config.routerAddress`; they do not automatically use an address from a previous quote. Router configuration fields are separate parallel reads and mutable values can change after reading.

### ApiClient

`new ApiClient(config?: ApiClientConfig)` creates a raw HTTP client. Its parameter types use `from`, `target` and `amount: bigint`; route controls are flat. It returns unwrapped API `data` with the service's snake\_case fields and string amounts. It does not perform the high-level native-sentinel mapping, role-based mode selection, signed-plan validation, allowance reads or wallet submission.

| Method                    | Parameters                                                                                                            | Return                                                                                                                                                   |
| ------------------------- | --------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `findRoutes(params)`      | `FindRoutesParams`: `from`, `target`, `amount`, optional `depth`, `splitCount`, `providers`, `includeResponseHeaders` | `Promise<ApiFindRouteData>`; with literal `includeResponseHeaders: true`, `Promise<{ data: ApiFindRouteData; responseHeaders: Record<string, string> }>` |
| `swap(params)`            | `ExecutionSwapParams` / `ApiExecutionSwapParams`; `executor` or low-level compatibility alias `sender` required       | `Promise<ApiSwapData>` from `GET /router/swap`                                                                                                           |
| `swapPrepare(params)`     | `DelegatedSwapParams` / `ApiDelegatedSwapParams`; required `payer`, `executor`, `recipient`                           | `Promise<ApiSwapPrepareData>` from `GET /router/swap/prepare`                                                                                            |
| `swapBuild(params)`       | `SwapBuildParams` / `ApiSwapBuildParams`: bytes32 `quoteId`, 64/65-byte `payerSignature`                              | `Promise<ApiSwapBuildData>` from `POST /router/swap/build`                                                                                               |
| `getStatus()`             | None                                                                                                                  | `Promise<ApiStatusData>`; provider identifiers, chainflow sync status and underlying router fee caps                                                     |
| `getAvailableProviders()` | None                                                                                                                  | `Promise<string[]>`; calls the status endpoint                                                                                                           |
| `setBaseUrl(url)`         | `string`                                                                                                              | `void`; changes the URL used for subsequent requests                                                                                                     |
| `getBaseUrl()`            | None                                                                                                                  | `string`; current API base URL                                                                                                                           |

`ApiExecutionSwapParams` uses the execution fields in the preparation table, with optional `executor` and the compatibility `sender` alias. `executor` takes precedence over `sender`. Low-level methods always request exact input. Empty provider arrays omit the filter. `swapBuild()` sends the signature only in the JSON body and redacts signature-shaped data from its error messages.

`ApiFindRouteData` contains route paths, gross input/output, deviation, contract metadata and gas estimate. `ApiSwapData` adds Direct roles, fee settlement, hashes, signatures and a ready transaction. `ApiSwapPrepareData` contains Delegated roles, amounts and Permit2 witness authorization; `ApiSwapBuildData` contains the built transaction bound to the quote. The exported `ApiResponse<T>` and `Api*Response` types describe wire envelopes; these methods return their `data` rather than the envelope.

### Execution validation and encoding helpers

These exports support integrations that consume raw API artifacts. Prefer `PeachClient`, which invokes the relevant validation before approval, signing, building, simulation and submission. Encoding and hash computation alone do not establish that an artifact is valid or authorized on-chain.

<table><thead><tr><th width="310.48828125">Helper</th><th>Signature and return</th></tr></thead><tbody><tr><td><code>validateDirectSwapResponse</code></td><td><code>(data: ApiSwapData, expected: ExpectedExecutionSwap): PreparedDirectSwap</code></td></tr><tr><td><code>validateDelegatedPrepareResponse</code></td><td><code>(data: ApiSwapPrepareData, expected: ExpectedExecutionSwap): PreparedDelegatedSwap</code></td></tr><tr><td><code>validateDelegatedBuildResponse</code></td><td><code>(data: ApiSwapBuildData, prepared: PreparedDelegatedSwap, payerSignature: string, chainId: number | bigint, executionRouter: string, nowSeconds?: bigint): ReadyDelegatedSwap</code></td></tr><tr><td><code>validatePayerSignature</code></td><td><code>(signature: string): void</code>; checks hex encoding and 64/65-byte length</td></tr><tr><td><code>encodeExecutionRouterCalldata</code></td><td><code>(value: ExecutionRouterCalldata): string</code>; encodes <code>executePlan</code></td></tr><tr><td><code>decodeExecutionRouterCalldata</code></td><td><code>(data: string): ExecutionRouterCalldata</code>; requires canonical <code>executePlan</code> calldata</td></tr><tr><td><code>decodeExecutionRouterReceipt</code></td><td><code>(returnData: string): RouterExecutionReceipt</code>; decodes <code>executePlan</code> return data, not transaction logs</td></tr><tr><td><code>computeExecutionRouteHash</code></td><td><code>(params: SwapParams, logicalPoolIds: string[], amountModes: number[]): string</code></td></tr><tr><td><code>computeSettlementPolicyHash</code></td><td><code>(policy: SettlementPolicy): string</code></td></tr><tr><td><code>computeExecutionPlanStructHash</code></td><td><code>(plan: ExecutionPlan): string</code>; EIP-712 struct hash</td></tr><tr><td><code>computeExecutionPlanDigest</code></td><td><code>(plan: ExecutionPlan): string</code>; EIP-712 digest including chain and execution-router domain</td></tr><tr><td><code>computePermit2WitnessDigest</code></td><td><code>(typedData: Permit2WitnessTypedData): string</code></td></tr></tbody></table>

`ExpectedExecutionSwap` requires `chainId`, `executionRouter`, `from`, `target`, `payer`, `executor` and `recipient`. Optional fields are `legacyRouter`, `nativeIn`, `nativeOut`, `customFeeBps`, `customFeeReceiver` and `nowSeconds`. Omitted `nowSeconds` uses the current Unix time in seconds. It has no requested-amount or requested-slippage field; consumers must also compare the prepared result with their order.

`PEACH_EXECUTION_ROUTER_ABI` exposes the `executePlan` entrypoint and return tuple. `ExecutionRouterCalldata` contains `plan`, `routerParams: SwapParams`, `logicalPoolIds`, `amountModes`, and payer/aggregator signatures. `ExecutionFundingMode` is `0` (Direct) or `1` (Permit2 Witness); `ExecutionNativeMode` is `0` (ERC20), `1` (native input) or `2` (native output). `SettlementPolicy` contains protocol receiver/cut and positive-output capture/cap fields used in the policy hash.

### Wallet timeout helper

`withWalletSendTimeout<T>(promise: Promise<T>, timeoutMs = DEFAULT_EXECUTE_TIMEOUT_MS): Promise<T>` bounds waiting on an existing wallet-send promise. A positive elapsed timeout throws `ExecuteTimeoutError` with `stage: "wallet_send"`; values at or below zero disable the timer. `executeSwap()` does not apply this helper automatically. Timeout does not cancel the wallet prompt or transaction; inspect the wallet before retrying. See [Client Configuration](https://docs.peach.ag/documentation/bsc/aggregator/editor/configuration-and-error-handling).

### Constants and shared types

<table><thead><tr><th width="272.44140625">Export</th><th>Value or purpose</th></tr></thead><tbody><tr><td><code>NATIVE_TOKEN_ADDRESS</code>, <code>isNativeTokenAddress()</code></td><td>Native BNB sentinel <code>0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE</code>; case-insensitive detection; not an ERC20 contract</td></tr><tr><td><code>PERMIT2_ADDRESS</code></td><td>Canonical ERC20 base-approval target for Delegated execution</td></tr><tr><td><code>MAX_FEE_BPS</code></td><td>Display custom-fee cap, 500 bps</td></tr><tr><td><code>BPS_DENOMINATOR</code></td><td><code>10000n</code>; integer basis-point denominator</td></tr><tr><td><code>DEFAULT_API_URL</code></td><td><code>https://api.peach.ag</code></td></tr><tr><td><code>API_DEFAULTS</code></td><td><code>depth: 3</code>, <code>splitCount: 20</code>, <code>clientVersion: 1001500</code></td></tr><tr><td><code>DEFAULT_SLIPPAGE_BPS</code></td><td><code>50</code>; 0.5%</td></tr><tr><td><code>DEFAULT_DEADLINE_SECONDS</code></td><td><code>1200</code>; 20 minutes</td></tr><tr><td><code>DEFAULT_EXECUTE_TIMEOUT_MS</code></td><td><code>60000</code>; optional wallet helper default</td></tr><tr><td><code>ERR_ZERO_AMOUNT_PATHS</code></td><td><code>4001</code>; quote paths are unusable after amount/provider filtering</td></tr><tr><td><code>BSC_MAINNET_CONFIG</code></td><td>Chain 56 preset; no mandatory router pins</td></tr><tr><td><code>BSC_TESTNET_CONFIG</code></td><td>Chain 97 provider/WBNB preset; selecting it does not switch the default API to a testnet service</td></tr></tbody></table>

`PoolInfo`, `RouteStep`, `Route`, `SplitRoute`, `SwapStep` and `SwapParams` describe route and contract data. `Provider` is an open string type so new service providers do not require a release; `ProtocolType` is an exported descriptive enum, not a restriction on provider identifiers. Use `getAvailableProviders()` for the current API set.

The current package does not export a local route-discovery client or the previous legacy swap-execution helpers. Use the methods above and preserve server-built transactions. See [Transaction Safety](https://docs.peach.ag/documentation/bsc/aggregator/editor/validation-approvals-and-expiry) for validation boundaries and [Client Configuration](https://docs.peach.ag/documentation/bsc/aggregator/editor/configuration-and-error-handling) for exported error classes.


---

# 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/bsc/aggregator/editor/configuration-and-error-handling/sdk-reference.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.
