SDK Reference
Public SDK methods, parameters, execution types and constants.
This reference describes the SDK 0.5.0 public exports of @masterpeach/aggregator-sdk. 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.
Recommended swap methods
Use swapAllowance(), swapPermit2() and swapPermit2Build() for new integrations. They include quoting; do not call getQuote() or findRoutes() first. See Migration Guide.
Quotes and preparation
getQuote(params)
from, target, amountIn: bigint, optional options: QuoteOptions
Promise<Quote>; display-only
getAvailableProviders()
None
Promise<string[]>
swapAllowance(params)
PrepareSwapParams; payer must equal executor
Promise<PreparedDirectSwap>
swapPermit2(params)
PrepareSwapParams with required payer and recipient; payer must differ from executor
Promise<PreparedDelegatedSwap>
swap(params)
PrepareSwapParams
Promise<PreparedSwap>; Direct when payer equals executor, otherwise Delegated
swap(), swapAllowance(), swapPermit2() and swapPermit2Build() obtain and validate service artifacts; they do not broadcast. swapPermit2Build(prepared, payerSignature) returns the final Permit2 transaction after the payer signs. executeSwap() is the explicit wallet submission step. The request and result type names (PrepareSwapParams, PreparedDirectSwap, PreparedDelegatedSwap, ReadyDelegatedSwap) are unchanged.
PeachClient compatibility aliases
prepareSwap(params)
swap(params)
prepareDirectSwap(params)
swapAllowance(params)
prepareDelegatedSwap(params)
swapPermit2(params)
buildDelegatedSwap(prepared, payerSignature)
swapPermit2Build(prepared, payerSignature)
Each alias delegates to its canonical method with the same parameters and return type. It preserves validation and issues no extra HTTP request or runtime deprecation warning.
Compared with 0.4.0, PeachClient.swap() now selects either execution mode and returns PreparedSwap. Use swapAllowance() when a PreparedDirectSwap is required. ProtocolType is removed; use service-defined provider strings from getAvailableProviders().
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.
Legacy QuoteOptions and Quote
find_routes remains available and is planned for future deprecation; no removal date is announced. getQuote() and ApiClient.findRoutes() retain this compatibility contract.
depth, splitCount
number?
Maximum hops and split count; defaults 3 and 20
providers
Provider[]?
Open string identifiers; omitted/empty means no explicit filter
includeResponseHeaders
boolean?
Defaults to false; includes route HTTP headers in Quote.responseHeaders when true
customFee
CustomFee?
Display projection with feeAccount: string and integer feeBps in [1, MAX_FEE_BPS]; also configure the execution fee during preparation
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
from, target
string
Token address or native sentinel
amount
bigint
Positive exact-input amount in input-token base units
executor
string
Required nonzero address that calls the Execution Router
payer
string?
Defaults to executor
recipient
string?
Defaults to executor in Direct; mandatory in Delegated
depth, splitCount
number?
Route search controls; defaults 3 and 20
providers
Provider[]?
Open string identifiers; omitted/empty means no explicit filter
slippageBps
number?
Integer [0, 10000]; sent when supplied
deadlineSecs
number?
Relative seconds sent when supplied; use an explicit value
customFeeBps
number?
Defaults to zero; local range [0, 10000]
customFeeReceiver
string?
Nonzero address required for positive fees
nativeIn, nativeOut
boolean?
Native-mode flags; the sentinel also enables the matching flag
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 and Transaction Safety.
Approvals and execution
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
swapPermit2Build(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
PreparedDirectSwap
DIRECT_ALLOWANCE / TRANSACTION_READY; amountIn, gross amountOut, net expectAmountOut, approvalSpender, tx, execution, raw
PreparedDelegatedSwap
PERMIT2_WITNESS / PAYER_SIGNATURE_REQUIRED; amounts, roles, planHash, payerAuthorization, raw; no transaction
ReadyDelegatedSwap
PERMIT2_WITNESS / TRANSACTION_READY; tx, execution, prepared, raw
PreparedSwap
Union of the two prepared types
ReadySwap
Union of Direct prepared and Delegated ready types
SwapTransaction
to, data, value: bigint, entrypoint: "executePlan", amountOutMin: bigint
ExecutionPlan
Signed roles, token pair, amounts, deadline, nonce, fees and hash bindings
Permit2WitnessAuthorization
Owner, Permit2 contract, spender, token, amount, nonce, deadline, plan hash and typed data
RouterExecutionReceipt
planHash, payer/executor/recipient, tokenOut, requestedAmountIn, actualAmountIn, userAmountOut; returned by simulation
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
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. Ordinary frontend integrations need only PeachClient, which holds its HTTP client internally. Unlike PeachClient.swap(), the deprecated ApiClient.swap() alias always requests allowance; it does not select by role. 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.
findRoutes(params)
FindRoutesParams: from, target, amount, optional depth, splitCount, providers, includeResponseHeaders
Promise<ApiFindRouteData>; with literal includeResponseHeaders: true, Promise<{ data: ApiFindRouteData; responseHeaders: Record<string, string> }>
swapAllowance(params)
ExecutionSwapParams / ApiExecutionSwapParams; executor or low-level compatibility alias sender required
Promise<ApiSwapData> from GET /router/swap/allowance
swapPermit2(params)
DelegatedSwapParams / ApiDelegatedSwapParams; required payer, executor, recipient
Promise<ApiSwapPrepareData> from GET /router/swap/permit2
swapPermit2Build(params)
SwapBuildParams / ApiSwapBuildParams: bytes32 quoteId, 64/65-byte payerSignature
Promise<ApiSwapBuildData> from POST /router/swap/permit2/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
ApiClient.swap(), ApiClient.swapPrepare() and ApiClient.swapBuild() remain deprecated compatibility aliases for swapAllowance(), swapPermit2() and swapPermit2Build(). They use the new HTTP addresses, preserve their existing parameter/return types and issue one request without fallback to old addresses. PeachClient.swap() chooses allowance when normalized payer and executor match (payer defaults to executor), otherwise Permit2; the explicit methods are swapAllowance() and swapPermit2(), followed by swapPermit2Build() for Permit2.
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. swapPermit2Build() (and its alias 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 paths: ApiSwapRoutePath[], 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.
ApiSwapRoutePath contains provider, adapter, token_in, token_out, direction, fee_rate, amount_in, amount_out, optional extra_data and optional pool. Amounts and fee rates remain strings. High-level Direct preparation exposes these display paths at prepared.raw.paths; it does not add a top-level paths field or rebuild the transaction from them. Quote paths remain ApiRoutePath[] with required pool.
ApiClientConfig.apiKey is sent as query apikey on findRoutes() and swapAllowance() (including swap()). On allowance, only a server-whitelisted key reveals paths[].pool; missing or invalid keys do not prevent building the transaction. It is not added to Permit2 prepare/build requests.
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.
validateDirectSwapResponse
(data: ApiSwapData, expected: ExpectedExecutionSwap): PreparedDirectSwap
validateDelegatedPrepareResponse
(data: ApiSwapPrepareData, expected: ExpectedExecutionSwap): PreparedDelegatedSwap
validateDelegatedBuildResponse
(data: ApiSwapBuildData, prepared: PreparedDelegatedSwap, payerSignature: string, chainId: number | bigint, executionRouter: string, nowSeconds?: bigint): ReadyDelegatedSwap
validatePayerSignature
(signature: string): void; checks hex encoding and 64/65-byte length
encodeExecutionRouterCalldata
(value: ExecutionRouterCalldata): string; encodes executePlan
decodeExecutionRouterCalldata
(data: string): ExecutionRouterCalldata; requires canonical executePlan calldata
decodeExecutionRouterReceipt
(returnData: string): RouterExecutionReceipt; decodes executePlan return data, not transaction logs
computeExecutionRouteHash
(params: SwapParams, logicalPoolIds: string[], amountModes: number[]): string
computeSettlementPolicyHash
(policy: SettlementPolicy): string
computeExecutionPlanStructHash
(plan: ExecutionPlan): string; EIP-712 struct hash
computeExecutionPlanDigest
(plan: ExecutionPlan): string; EIP-712 digest including chain and execution-router domain
computePermit2WitnessDigest
(typedData: Permit2WitnessTypedData): string
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.
Constants and shared types
NATIVE_TOKEN_ADDRESS, isNativeTokenAddress()
Native BNB sentinel 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; case-insensitive detection; not an ERC20 contract
PERMIT2_ADDRESS
Canonical ERC20 base-approval target for Delegated execution
MAX_FEE_BPS
Display custom-fee cap, 500 bps
BPS_DENOMINATOR
10000n; integer basis-point denominator
DEFAULT_API_URL
https://api.peach.ag
API_DEFAULTS
depth: 3, splitCount: 20, clientVersion: 1001500
DEFAULT_SLIPPAGE_BPS
50; 0.5%
DEFAULT_DEADLINE_SECONDS
1200; 20 minutes
DEFAULT_EXECUTE_TIMEOUT_MS
60000; optional wallet helper default
ERR_ZERO_AMOUNT_PATHS
4001; quote paths are unusable after amount/provider filtering
BSC_MAINNET_CONFIG
Chain 56 preset; no mandatory router pins
BSC_TESTNET_CONFIG
Chain 97 provider/WBNB preset; selecting it does not switch the default API to a testnet service
PoolInfo, RouteStep, Route, SplitRoute, SwapStep and SwapParams describe route and contract data. Provider is an alias for string; provider filters and route responses accept service-defined identifiers without an SDK update. The SDK does not export a DEX enum. Use getAvailableProviders() for the current API set and pass those strings unchanged.
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 for validation boundaries and Client Configuration for exported error classes.
Last updated
Was this helpful?