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

# Client Configuration

Configure the production API and RPC, handle wallet changes and recover from errors.

For the mainnet workflows in this guide, use the production API with a BSC Mainnet provider and wallet signer (chain ID 56). Configuration and error handling below match SDK v0.3.0.

### Configure the client

Pass your RPC provider and API options directly to `PeachClient`. The production URL is shown explicitly here; you can omit `baseUrl` to use the same default.

```typescript
import { ethers } from "ethers";
import { BSC_MAINNET_CONFIG, PeachClient } from "@masterpeach/aggregator-sdk";

const provider = new ethers.JsonRpcProvider(BSC_MAINNET_CONFIG.rpcUrl);
const client = new PeachClient(BSC_MAINNET_CONFIG, provider, {
  api: { baseUrl: "https://api.peach.ag", timeout: 10_000 }, // Production API (SDK default)
});
```

<table><thead><tr><th width="269.79296875">Setting</th><th>Purpose</th></tr></thead><tbody><tr><td>Provider constructor argument</td><td>RPC for metadata, allowance reads and simulation; BrowserProvider uses the wallet's RPC</td></tr><tr><td><code>config.chainId</code>, <code>config.weth</code></td><td>Required chain identity and wrapped native-token address used for plan validation and native-token mapping</td></tr><tr><td><code>config.rpcUrl</code></td><td>Required RPC URL; used to create a JsonRpcProvider only when the provider argument is omitted</td></tr><tr><td><code>api.baseUrl</code></td><td>Production endpoint, <code>https://api.peach.ag</code> (SDK default)</td></tr><tr><td><code>api.timeout</code></td><td>HTTP timeout through response-body parsing in milliseconds, default 10000</td></tr><tr><td><code>api.headers</code></td><td>Extra request headers appropriate for the application environment</td></tr><tr><td><code>api.apiKey</code></td><td>Optional routing identifier for quote engine selection; sent in the quote URL, not an authorization secret</td></tr><tr><td><code>config.executionRouterAddress</code></td><td>Optional pin for the Execution Router supplied by the API</td></tr><tr><td><code>config.routerAddress</code></td><td>Optional underlying PeachRouter pin/read-helper address; not the swap destination</td></tr></tbody></table>

The API key is applied to display routing requests, not execution preparation/build requests. Do not use it as access control or assume it selects the execution engine.

Router pins are optional. To add one, pass `{ ...BSC_MAINNET_CONFIG, executionRouterAddress: verifiedRouterAddress }` as the first constructor argument. The SDK rejects responses that do not match the pin. Use an address verified for the production deployment. Without a pin, execution preparation uses the execution-router address advertised by the API and validates the returned artifact against it.

`BSC_TESTNET_CONFIG` selects chain 97 and testnet WBNB/RPC values. It does not select a different API: configure `api.baseUrl` for a service that supports your target chain. The SDK does not automatically switch API deployments when the wallet changes networks.

For raw HTTP integrations, `new ApiClient(config?)` accepts the same `ApiClientConfig`. `setBaseUrl(url)` and `getBaseUrl()` apply to that instance. Raw responses still need execution validation before they are signed or submitted; see [SDK Reference](https://docs.peach.ag/documentation/bsc/aggregator/editor/configuration-and-error-handling/sdk-reference).

### Account and network changes

Check the wallet's chain before authorization and submission. On `accountsChanged` or `chainChanged`, discard previews and prepared plans, refresh the signer, and prepare again. A signer can retain an old address. Track wallet events and order edits so stale confirmation actions cannot submit.

Ignore stale quote responses and disable duplicate confirmations during a trade. The SDK has no public per-call cancellation signal. Discarding a workflow cannot revoke a signature or cancel a sent transaction; check any wallet operation already in progress.

### Errors

| Error                            | Interpretation                                                                  | Response                                                                      |
| -------------------------------- | ------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| `ApiError`                       | Service, HTTP or transport failure; inspect `code` and `message`                | Bounded quote retry; investigate preparation/build failures before restarting |
| `CustomFeeError`                 | Invalid display custom fee                                                      | Correct local fee settings                                                    |
| `ExecutionRouterValidationError` | Invalid input, identity mismatch, expired or inconsistent artifact              | Stop the plan; resolve the cause before repreparing                           |
| `ExecuteTimeoutError`            | Optional wallet-send helper elapsed; inspect `stage`, currently `"wallet_send"` | Inspect the wallet and any submitted transaction before retrying              |
| Missing-router `Error`           | A router read has no explicit address and no configured `routerAddress`         | Supply the underlying PeachRouter address to the read helper or configuration |
| ethers wallet rejection          | User declined approval, signature or submission                                 | Return control to the user; do not automatically reprompt                     |
| Simulation revert                | Current state cannot execute the transaction                                    | Check balance, allowance, expiry, network and route state                     |
| Receipt/replacement error        | Mining, replacement or execution outcome needs inspection                       | Follow the submitted/replacement hash and final status                        |

`ApiError`, `CustomFeeError`, `ExecutionRouterValidationError` and `ExecuteTimeoutError` are exported `Error` subclasses. `ApiError.code` can represent an HTTP status, a service code, `408` for timeout or `0` for a transport/body-parsing failure. A `404` can also mean an empty route response; `4001` can mean unusable route paths after amount/provider filtering. Passing `byAmountIn: false` from JavaScript raises `ApiError` for quotes/raw requests and `ExecutionRouterValidationError` for high-level preparation. Inspect the failing stage, `code` and `message` when classifying failures.

RPC calls and wallet operations can throw ethers errors directly. Execution decoding, malformed numeric data and token-specific contract behavior can also fail outside the exported SDK error classes; keep a fallback error path rather than relying on an exhaustive class list.

### Timeouts and retries

The API timeout covers each HTTP request through response-body reading and JSON parsing. It aborts stalled requests with `ApiError.code = 408`, and the timer is cleared on completion or failure. Requests have no automatic retry. Wallet prompts, RPC calls and mining require separate deadlines.

`executeSwap()` delegates to `signer.sendTransaction()` and does not apply `withWalletSendTimeout()` automatically. `withWalletSendTimeout(promise, timeoutMs?)` defaults to 60000 milliseconds; a positive elapsed timeout throws `ExecuteTimeoutError`, while zero or negative values disable the timer. The utility stops waiting; it cannot cancel the wallet request or prove that nothing was submitted. The transaction `gasPrice` and `gasLimit` options do not configure a timeout.

Save the hash as soon as a `TransactionResponse` is returned. If `wait()` throws, inspect receipt/replacement information and wallet history. If no hash was returned, inspect the wallet and executor nonce before allowing another trade. A failed mined receipt is not a successful swap.

### Troubleshooting

<table><thead><tr><th width="374.53515625">Symptom</th><th>Check</th></tr></thead><tbody><tr><td>No route</td><td>Token addresses and decimals, provider restrictions, liquidity and order size</td></tr><tr><td>Wrong spender</td><td>Prepared Direct spender or canonical Permit2, according to mode</td></tr><tr><td>Approval reverted</td><td>Token-specific reset requirements, gas balance, spender and network</td></tr><tr><td>Plan expired while approving</td><td>Keep confirmed allowance; prepare and review a fresh plan</td></tr><tr><td>Delegated signature rejected</td><td>Payer identity, typed-data support and authorization expiry</td></tr><tr><td>Build validation failed</td><td>Preserve the original artifact and signature; do not edit fields</td></tr><tr><td>Native-input failure</td><td>Direct mode, correct sentinel and sufficient BNB including gas</td></tr><tr><td>Prepared amount differs from the order</td><td>Compare <code>prepared.amountIn</code> with the requested exact-input amount and stop before signing/submitting</td></tr><tr><td>Minimum output differs from the confirmation</td><td>Review the signed transaction's <code>amountOutMin</code>, net expected output and intended slippage; prepare again after order edits</td></tr></tbody></table>

For support, record SDK version, environment, chain ID, failing stage, quote ID or plan hash, transaction hash if available, and error code/message. Redact payer signatures and authorization payloads.

See [SDK Reference](https://docs.peach.ag/documentation/bsc/aggregator/editor/configuration-and-error-handling/sdk-reference) for public methods, parameters and return types.


---

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