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.5.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.
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)
});Provider constructor argument
RPC for metadata, allowance reads and simulation; BrowserProvider uses the wallet's RPC
config.chainId, config.weth
Required chain identity and wrapped native-token address used for plan validation and native-token mapping
config.rpcUrl
Required RPC URL; used to create a JsonRpcProvider only when the provider argument is omitted
api.baseUrl
Production endpoint, https://api.peach.ag (SDK default)
api.timeout
HTTP timeout through response-body parsing in milliseconds, default 10000
api.headers
Extra request headers appropriate for the application environment
api.apiKey
Optional query apikey on find-routes and allowance requests. Find-routes uses it for engine selection; allowance uses it only for server-whitelisted paths[].pool visibility. Missing/invalid allowance keys omit pool without blocking construction. Not sent to Permit2 prepare/build; appears in request URLs
config.executionRouterAddress
Optional pin for the Execution Router supplied by the API
config.routerAddress
Optional underlying PeachRouter pin/read-helper address; not the swap destination
The API key is not application access control.
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.
Account and network changes
Check the wallet's chain before authorization and submission. On accountsChanged or chainChanged, discard prepared quotes and 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.
The SDK has no per-call cancellation signal. Discarding a workflow cannot revoke a signature or cancel a sent transaction; inspect any wallet operation already in progress. See Transaction Safety for plan refresh rules.
Errors
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
No route
Token addresses and decimals, provider restrictions, liquidity and order size
Wrong spender
Prepared Direct spender or canonical Permit2, according to mode
Approval reverted
Token-specific reset requirements, gas balance, spender and network
Plan expired while approving
Keep confirmed allowance; prepare and review a fresh plan
Delegated signature rejected
Payer identity, typed-data support and authorization expiry
Build validation failed
Preserve the original artifact and signature; do not edit fields
Native-input failure
Direct mode, correct sentinel and sufficient BNB including gas
Prepared amount differs from the order
Compare prepared.amountIn with the requested exact-input amount and stop before signing/submitting
Minimum output differs from the confirmation
Review the signed transaction's amountOutMin, net expected output and intended slippage; prepare again after order edits
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 for public methods, parameters and return types.
Last updated
Was this helpful?