> 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/aggregator/core-features/api-configuration-cancellation-and-errors.md).

# Client Configuration

Configure the SDK client, manage request lifecycles, and handle failures at the request, validation and transaction stages.

### Choose the network

The SDK sends `chain_id` in every request URL, including POST requests. `ArcClient` uses the configured chain ID; standalone `ApiClient` defaults to Arc Mainnet (5042). POST bodies are unchanged.

Configure the API, SDK, RPC and wallet for the same network. The SDK build used in these guides exports `arcTestnet` and `ARC_TESTNET_CONFIG`; it does not export a Mainnet preset.

| Setting                               | Arc Mainnet                                      | Arc Testnet                                  |
| ------------------------------------- | ------------------------------------------------ | -------------------------------------------- |
| Chain ID                              | `5042`                                           | `5042002`                                    |
| RPC URL                               | `https://rpc.arc-scan.org`                       | `https://rpc.testnet.arc.network`            |
| Execution Router proxy                | `0x2528F3190603B85A155D48C31946703d71f921ED`     | `0x5FF56925140D6f5912C8Ca6593f2C3BC28190607` |
| Aggregator API                        | `https://api.peach.ag/arc`                       | `https://api-arc.cipheron.org`               |
| SDK configuration                     | Explicit `ArcConfig`                             | `ARC_TESTNET_CONFIG`                         |
| Wrapped-native configuration (`weth`) | Supply the Mainnet deployment's verified address | Included in `ARC_TESTNET_CONFIG`             |

Set `api.baseUrl` to `https://api.peach.ag/arc`. The SDK appends the endpoint path automatically. For contract addresses and deployment details, see [Contract Address](https://docs.peach.ag/documentation/arc/aggregator/contract-address#arc-mainnet-configuration).

### Testnet configuration

```ts
import { createPublicClient, http } from "viem";
import { ArcClient, arcTestnet, ARC_TESTNET_CONFIG } from "@masterpeach/arc-aggregator-sdk";

const publicClient = createPublicClient({
  chain: arcTestnet,
  transport: http(ARC_TESTNET_CONFIG.rpcUrl),
});

const arc = new ArcClient(ARC_TESTNET_CONFIG, publicClient, {
  api: { baseUrl: "https://api-arc.cipheron.org" },
});
```

No custom request headers are required. The HTTP timeout defaults to 10,000 ms; set `api.timeout` only when you need a different value.

### Mainnet configuration

Configure the Mainnet RPC and API explicitly. Supply your Mainnet deployment's wrapped-native address as `mainnetWrappedNativeAddress`; the SDK requires `weth` even for ERC-20 swaps.

```ts
import { createPublicClient, http, type Address } from "viem";
import { ArcClient, type ArcConfig } from "@masterpeach/arc-aggregator-sdk";

export function createMainnetClient(mainnetWrappedNativeAddress: Address) {
  const config = {
    chainId: 5042,
    rpcUrl: "https://rpc.arc-scan.org",
    executionRouterAddress: "0x2528F3190603B85A155D48C31946703d71f921ED",
    weth: mainnetWrappedNativeAddress,
  } satisfies ArcConfig;

  const publicClient = createPublicClient({
    transport: http(config.rpcUrl),
  });

  return new ArcClient(config, publicClient, {
    api: { baseUrl: "https://api.peach.ag/arc" },
  });
}
```

Connect the wallet to Arc Mainnet (`5042`) before submission. Use `new ApiClient({ baseUrl: "https://api.peach.ag/arc" }).getStatus()` to check the API's chain and Execution Router. Arc swaps use ERC-20 input and output.

### Client options

Import public methods, types, constants, ABIs and errors from the package root. The `./chains` subpath exports chain defaults; there is no legacy `./actions` entry point.

| Configuration            | Type / default                      | Purpose                                                                                     |
| ------------------------ | ----------------------------------- | ------------------------------------------------------------------------------------------- |
| `ArcConfig.chainId`      | number, required                    | Expected execution chain                                                                    |
| `rpcUrl`                 | string, required in config          | Deployment RPC URL; construct your PublicClient with the intended transport                 |
| `executionRouterAddress` | Address, required                   | Pinned execution and Direct approval target                                                 |
| `routerAddress`          | optional Address                    | Optional underlying-router pin; current default leaves it unset                             |
| `weth`                   | Address, required                   | Wrapped-native configuration used by generic SDK encoding; does not enable native Arc swaps |
| `api.baseUrl`            | string, defaults to the Testnet API | Set the API for the selected deployment; Mainnet requires an explicit URL                   |
| `api.timeout`            | number, default 10000 ms            | Positive finite timeout, at most 2147483647 ms                                              |
| `api.apiKey`             | optional string                     | Sent as query parameter `apikey`; use private credentials only in a backend                 |
| `api.fetch`              | optional fetch implementation       | Injectable HTTP transport                                                                   |

`ARC_TESTNET_CONFIG` and `arcTestnet` are Testnet-only defaults. Do not use them for Mainnet. Optional `apiKey` is sent as the `apikey` query parameter; keep private API credentials in a backend and redact them from logs.

Use `new ArcClient(config, publicClient, { api: apiOptions })` for validated execution. `new ApiClient(apiOptions)` exposes the raw HTTP client; its methods validate the response envelope and shape, while raw monetary values remain integer strings. See the [HTTP API](https://docs.peach.ag/api-reference/arc-aggregator) for endpoint-specific fields.

### Cancellation

Pass `signal: controller.signal` to `swap` or prepare methods. `getAvailableProviders(signal)` and `buildDelegatedSwap(prepared, signature, signal)` also accept an AbortSignal. Calling `controller.abort()` cancels the HTTP request, including response-body reading. It does not dismiss a wallet prompt, revoke a signature or cancel a submitted chain transaction.

The timeout covers HTTP only. Use separate UI states for fetching a quote, waiting for wallet approval and confirming a transaction. Ignore stale results after the user changes the order or switches networks.

On input, account, recipient, routing-setting, fee, slippage or network changes, cancel the previous request and invalidate its result and confirmation. Ignore late responses. Fetch the quote and transaction with one `swap()` call, then confirm that result before approval or submission. A replacement result needs new acceptance; do not silently widen slippage. Disable repeated submissions while a trade is pending.

### Request and wallet states

Use distinct states for requesting the quote and transaction, awaiting confirmation of that result, awaiting wallet approval/signature, submitting, and waiting for a receipt. An aborted swap request returns to the current order; a submission timeout remains unresolved until the transaction status is known.

### Error surfaces

| Surface                          | What to inspect                                                 |
| -------------------------------- | --------------------------------------------------------------- |
| `ArcApiError`                    | Numeric `code`, message and optional HTTP `status`              |
| `ExecutionRouterValidationError` | Which requested term or execution invariant failed              |
| Wallet / RPC errors              | viem cause chain, rejection reason or decoded contract revert   |
| Transaction receipt              | `status === "success"`; a hash or receipt alone is insufficient |

HTTP 200 is not the application's success code. Successful envelopes contain `code: 200`. The API can return the following application codes, which are not HTTP status numbers:

| Code   | Meaning                                  | Recovery                                                           |
| ------ | ---------------------------------------- | ------------------------------------------------------------------ |
| `4000` | Invalid request                          | Correct parameters or role relationships                           |
| `4030` | Forbidden                                | Check the rejection reason and integration access                  |
| `4040` | Token risk / honeypot rejection          | Stop the trade and investigate the token                           |
| `5000` | Internal error                           | Retry conservatively if appropriate; provide request ID to support |
| `5010` | No usable route / insufficient liquidity | Inspect pair, provider filters, amount, pool state and indexing    |
| `5030` | Service unavailable                      | Back off and refresh service availability                          |
| `5040` | Unsupported API version                  | Use documented version `v=1001500`                                 |

Malformed framework requests, proxies and network failures may instead produce HTTP errors or non-JSON bodies. The SDK also uses local codes such as `408` for cancellation/timeout and `0` for malformed responses or other transport errors. Always retain both fields rather than collapsing all failures into one code.

### Troubleshooting by symptom

| Symptom                         | Likely cause                                                      | Check                                                            | Action                                                               |
| ------------------------------- | ----------------------------------------------------------------- | ---------------------------------------------------------------- | -------------------------------------------------------------------- |
| Token balance too low           | Wrong decimals, amount or account                                 | `decimals`, `balanceOf(payer)`, chain ID                         | Correct the input; fund the payer before executing                   |
| Approval exists but swap fails  | Allowance granted to the wrong contract                           | Token, owner, spender and required input                         | Approve the correct spender for this flow                            |
| Wallet cannot sign Witness      | Wrong payer or unsupported signing account                        | Connected address and typed-data support                         | Connect the payer; do not substitute another address                 |
| Artifact expired                | Approval/signing took too long                                    | Witness deadline and server error                                | Prepare again and obtain a fresh signature                           |
| Minimum output failed           | Price moved or liquidity changed                                  | Fresh quote, slippage and final pool state                       | Requote; let the user decide any slippage change                     |
| `5010` on a graduated token     | LAUNCHPAD-only filter, pool not created/indexed, or low liquidity | Providers, graduation state, official PoolKey and indexer cursor | Allow V4, wait for transition/indexing, or explain missing liquidity |
| `native_in/native_out` rejected | Current Arc endpoint is ERC-20-only                               | Input/output addresses and flags                                 | Use the USDC ERC-20 interface; omit native flags                     |
| Full-plan validation fails      | Inconsistent response, configuration or changed prepared data     | Router, request, plan hash and SDK version                       | Stop; investigate rather than bypassing validation                   |
| HTTP request aborted            | User input changed or timeout elapsed                             | AbortSignal and elapsed time                                     | Refresh only the current order                                       |
| Send timed out                  | Transaction may have been accepted                                | Known hash, receipt and executor nonce                           | Resolve the first submission before sending another                  |
| Receipt is reverted             | On-chain failure                                                  | Receipt and decoded revert / simulation                          | Show failure; a mined hash is not success                            |

### Support information

Include the chain ID, SDK version, endpoint, timestamp, request/quote ID when available, token pair, amount, provider filter, application code and HTTP status. For an already submitted trade include its transaction hash. Exclude credentials, wallet private keys and payer signatures. Do not send a signed build body or unredacted raw request logs.


---

# 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/aggregator/core-features/api-configuration-cancellation-and-errors.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.
