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

# Quickstart

Initialize the SDK, preview a quote, then prepare and submit a confirmed swap.

This Direct swap uses your application's existing signer to supply tokens, submit the transaction and receive the output. For separate payer and executor accounts, see [Delegated Swaps](https://docs.peach.ag/documentation/bsc/aggregator/editor/delegated-execution-with-permit2-witness).

Use two separate application actions: preview prices while the order changes, then prepare and submit only when the user chooses to trade.

### Install and initialize

```bash
npm install @masterpeach/aggregator-sdk@0.3.0 ethers@^6
```

Initialize the client with BSC Mainnet defaults and use an existing ethers v6 `signer` on chain ID 56. See [Overview](https://docs.peach.ag/documentation/bsc/aggregator/readme) for production configuration and service compatibility.

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

const client = new PeachClient(BSC_MAINNET_CONFIG);
```

This guide uses the v0.3.0 public methods. Quote and preparation inputs both use `from` for the input token and `target` for the output token. Quotes take `amountIn`; preparation takes `amount`. Both are exact input amounts in input-token base units.

| Action                               | SDK method               | Returned state                           |
| ------------------------------------ | ------------------------ | ---------------------------------------- |
| Preview                              | `getQuote()`             | Display quote; no transaction            |
| Prepare with one payer/executor      | `prepareDirectSwap()`    | `TRANSACTION_READY`                      |
| Prepare with separate payer/executor | `prepareDelegatedSwap()` | `PAYER_SIGNATURE_REQUIRED`               |
| Submit an accepted ready plan        | `executeSwap()`          | Transaction response; mining is separate |

`prepareSwap()` selects Direct or Delegated mode from the payer and executor addresses. The mode-specific helpers in this guide make each flow explicit.

### 1. Preview a quote

The snippets reuse your application's `tokenIn` and `tokenOut` addresses, input `amount` and `outputDecimals`. Convert the user's decimal amount with `ethers.parseUnits(value, inputDecimals)` after checking it is positive and within the input token's precision. `amount` is a `bigint` in base units; obtain `outputDecimals` from the output token's metadata. Native BNB uses 18 decimals.

Call this while displaying or editing an order. Format `quote.amountOut` with `ethers.formatUnits(quote.amountOut, outputDecimals)`.

```typescript
const quote = await client.getQuote({
  from: tokenIn,
  target: tokenOut,
  amountIn: amount,
});
```

Quoting requires no approval and sends no transaction. When preparing, keep the same token pair, amount and any routing options from the preview.

Quote routing controls belong in `options`; the same `providers`, `depth` and `splitCount` fields belong at the top level of preparation inputs. See [Quotes and Routing](https://docs.peach.ag/documentation/bsc/aggregator/editor/quotes-and-routing) for this mapping.

### 2. Confirm and swap

Run this action when the user chooses to trade, never during price refresh. Reuse the client and order inputs from step 1.

#### Prepare and review

`prepareDirectSwap()` requests fresh transaction data and a signed execution plan from the Peach API. The SDK validates them; your `signer` later signs and submits the transaction.

```typescript
const executor = await signer.getAddress();
const prepared = await client.prepareDirectSwap({
  from: tokenIn, 
  target: tokenOut, 
  amount, 
  executor,
  slippageBps: 50, // 0.5%; 100 bps = 1%
  deadlineSecs: 300,
});
if (prepared.amountIn !== amount) throw new Error("Prepared input differs from the order");
console.log("Expected output:", ethers.formatUnits(prepared.expectAmountOut, outputDecimals));
console.log("Minimum received:", ethers.formatUnits(prepared.tx.amountOutMin, outputDecimals));
```

Render the logged expected output and minimum received in your confirmation view. **Wait for the user to accept these fresh terms before approval or submission.** Logging them alone is not confirmation.

<table><thead><tr><th width="233.48828125">Setting or value</th><th>Meaning</th></tr></thead><tbody><tr><td><code>slippageBps: 50</code></td><td>0.5% tolerance; 100 bps = 1%. Use the user's chosen setting.</td></tr><tr><td><code>prepared.expectAmountOut</code></td><td>Expected recipient output from this fresh preparation, after any custom fee</td></tr><tr><td><code>prepared.tx.amountOutMin</code></td><td>Signed minimum received; execution reverts if it cannot satisfy the minimum</td></tr><tr><td><code>deadlineSecs: 300</code></td><td>Request five minutes of validity; the returned signed deadline is authoritative</td></tr></tbody></table>

Slippage applies to the fresh preparation and does not lock the preview price. Review the new expected output and minimum even if `slippageBps` is unchanged. Display the returned minimum directly; do not deduct slippage again or automatically raise tolerance after a failure.

#### Approve and execute

Run this step only for the prepared plan the user accepted.

```typescript
const approval = await client.buildDirectApprovalRequest(prepared, await signer.getAddress());
if (approval) {
  const approvalTx = await signer.sendTransaction(approval.tx);
  if ((await approvalTx.wait())?.status !== 1) throw new Error("Approval failed");
}
if (prepared.execution.plan.deadline <= BigInt(Math.floor(Date.now() / 1000))) {
  throw new Error("Plan expired; prepare and review a new swap");
}
const tx = await client.executeSwap(prepared, signer);
console.log("Transaction hash:", tx.hash); // Save this before waiting for confirmation.
const receipt = await tx.wait();
if (receipt?.status !== 1) throw new Error("Swap failed");
```

The approval helper skips native BNB and sufficient existing allowance. For ERC20 approval, the helper requests **unlimited allowance** to the validated Execution Router; disclose this in the wallet flow. Wait for approval confirmation before sending the swap.

Optional simulation fits after approval and before `executeSwap()`: call `client.simulateSwap(prepared, prepared.executor)`. Its `userAmountOut` is a current-state estimate, not the final settled amount. See [Direct Swaps](https://docs.peach.ag/documentation/bsc/aggregator/editor/direct-allowance).

### When to prepare again

If amount, tokens, wallet, network, recipient, routing, fees or slippage change, discard the prepared plan. If approval consumes its validity, keep the confirmed allowance and prepare and review fresh terms. Never edit the signed deadline, minimum or transaction fields.

Disable duplicate submissions while the trade is active.

### Common failures

* **No route:** check token addresses, available providers and liquidity; change the amount only with the user's agreement.
* **Approval or simulation failed:** stop before submission and inspect balance, allowance, deadline and trade terms.
* **Swap reverted:** a failed receipt is not a completed swap. Inspect the cause before preparing again.
* **Send timed out:** check the saved transaction hash or wallet nonce before retrying. A timeout does not prove that no swap was sent.

### Next steps

See [Quotes and Routing](https://docs.peach.ag/documentation/bsc/aggregator/editor/quotes-and-routing) for price refresh, [Slippage](https://docs.peach.ag/documentation/bsc/aggregator/editor/slippage) and [Fees](https://docs.peach.ag/documentation/bsc/aggregator/editor/fees-slippage-and-settlement) for trade settings, and [Transaction Safety](https://docs.peach.ag/documentation/bsc/aggregator/editor/validation-approvals-and-expiry) for validation and expiry. [Client Configuration](https://docs.peach.ag/documentation/bsc/aggregator/editor/configuration-and-error-handling) covers wallet changes and recovery.


---

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