> 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/launchpad/launchpad-classic/core-features/bonding-curve-trading.md).

# Bonding Curve Trading

Quote, buy and sell tokens with slippage protection; understand curve pricing and fees.

### Before you trade

Use the token’s BondingCurve while it is open. After `poolCreated`, trade through the V4 pool; see Graduation. Use `bigint` raw amounts, the actual recipient, a future `deadline` in Unix seconds and user-confirmed slippage.

### Get a buy quote

```ts
import { quoteLaunchpadBuy } from "@masterpeach/launchpad-sdk";

const quote = await quoteLaunchpadBuy(
  { publicClient, walletClient, deployment },
  { token, quoteInRaw, tokenRecipient },
);
// quote.tokenOut, quote.quoteSpent, quote.refund and quote.totalFee
```

Show the expected output, spending and fees. Approve the quote token to the curve and confirm the approval before preparing a buy. For sells, approve the launch token instead.

* [Approvals](https://docs.peach.ag/documentation/arc/launchpad/launchpad-classic/core-features/approvals.md) — Choose the required asset, amount and spender.

### Buy tokens

```ts
import { applySlippageToMinimumOut, mulDivUp } from "@masterpeach/launchpad-sdk";

const buy = await client.prepareBuy({
  token, quoteInRaw, tokenRecipient, partnerId,
  slippage: { bps: slippageBps },
  deadline,
});
const minimumTokenOut = applySlippageToMinimumOut(buy.preview.tokenOut, { bps: slippageBps });
const effectiveMinimum = mulDivUp(minimumTokenOut, buy.preview.quoteSpent, quoteInRaw);
// Show buy.preview and effectiveMinimum; send only after the user confirms.
const buyHash = await client.send(buy);
const result = await client.wait(buyHash, { confirmations: chain.confirmations });
if (result.status !== "confirmed") throw new Error("Buy reverted");
const fills = result.events.trades;
const graduation = await client.getGraduation(token);
```

`prepareBuy` refreshes the quote and simulates the transaction. The preview includes `tokenOut`, `quoteSpent`, `refund`, `baseFee`, `snipeTax` and `creatorTax`. Use confirmed trade events for actual fills and refunds.

### Sell tokens

```ts
const sell = await client.prepareSell({
  token, tokenIn, quoteRecipient, partnerId,
  slippage: { bps: slippageBps },
  deadline,
});
const minimumQuoteOut = applySlippageToMinimumOut(sell.preview.netQuoteOut, { bps: slippageBps });
// Show sell.preview.netQuoteOut, fees and minimumQuoteOut before confirmation.
const sellHash = await client.send(sell);
const sellResult = await client.wait(sellHash, { confirmations: chain.confirmations });
if (sellResult.status !== "confirmed") throw new Error("Sell reverted");
```

`tokenIn` is the launch-token amount in raw units. Sell output and the slippage minimum use net quote after fees. Sells have no snipe tax.

Sells return `LaunchpadInsufficientQuoteReserveError` if the payout exceeds the real quote reserve.

### Slippage and closing buys

Set `slippageBps` explicitly: `100` bps is 1%, an example rather than a default. Refresh stale quotes and deadlines before signing. On a slippage failure, re-quote and request confirmation; never increase tolerance automatically.

For a closing buy, the contract scales `minTokenOut` by actual spending and rounds up:

$$
m\_{\mathrm{eff}}=\left\lceil m\frac{q\_{\mathrm{spent}}}{q\_{\mathrm{in}}}\right\rceil
$$

m is `minTokenOut`. The quote amounts are actual spending (`quoteSpentRaw`) and submitted input (`quoteInRaw`). Round the effective minimum up to a whole raw token unit.

A larger refund reduces the effective minimum. For example, spending half the submitted input halves the minimum before rounding. Excessive input can make the slippage limit ineffective.

Quote first and submit the required amount. Use `simulateLaunchpadBuyExactIn` to preview the boundary calculation and avoid excessive input.

### Reserves and units

Use SDK quotes and `prepareBuy` / `prepareSell` to build trades. The formulas below explain pricing and rounding. Calculate in raw units with `bigint`; apply token decimals when formatting results.

* S — initial token supply (`initialSupply`).
* P — virtual quote reserve (`phantomQuote`).
* G — graduation target (`graduationThreshold`).
* T — tracked token reserve (`trackedTokens`).

The real quote reserve is `trackedQuote` minus `quoteFeeBalance` and `creatorTaxBalance`. Add the virtual reserve to obtain the pricing reserve Q:

$$
\begin{aligned}Q&=P+q\_{\mathrm{real}}\K&=QT\end{aligned}
$$

`P` is virtual liquidity and cannot be withdrawn or added to the V4 pool. `Q` excludes accrued fees. Use tracked reserves; direct token transfers do not update pricing state. Recompute `K = Q * T` from current reserves because integer rounding changes the product.

### Price curve

Scale the reserve ratio using the token and quote-asset decimal counts:

$$
p\_{\mathrm{spot}}=\frac{Q}{T},10^{d\_{\mathrm{token}}-d\_{\mathrm{quote}}}
$$

For the ideal continuous curve, ignoring integer rounding, x is net tokens sold rather than total trading volume:

$$
\begin{aligned}x&=S-T\K\_0&=PS\q\_{\mathrm{raised}}(x)&=\frac{Px}{S-x}\p(x)&=\frac{PS}{(S-x)^2},10^{d\_{\mathrm{token}}-d\_{\mathrm{quote}}}\end{aligned}
$$

Price is quote assets per whole launch token. Preserve the ratio’s precision until formatting; do not integer-divide `Q / T` first. Buys raise the marginal price; sells lower it. Use the swap formulas for execution quotes.

### Buy and sell quotes

Use `B = 10,000`, `f = curveFeeBps`, `c = creatorTaxBps` and `s = currentSnipeTaxBps(tokenRecipient)`. Round each fee down before summing. Exemptions set `s` to zero; base fees and Creator Tax still apply.

$$
\phi(g,s)=\left\lfloor\frac{gf}{B}\right\rfloor+\left\lfloor\frac{gs}{B}\right\rfloor+\left\lfloor\frac{gc}{B}\right\rfloor
$$

For a buy, g is gross quote input and φ is the total fee. Price the net input to obtain the candidate token output:

$$
\begin{aligned}q\_{\mathrm{net}}&=g-\phi(g,s)\t\_{\mathrm{candidate}}&=\left\lfloor\frac{q\_{\mathrm{net}}T}{Q+q\_{\mathrm{net}}}\right\rfloor\end{aligned}
$$

For a sell, a is the raw token input. Deduct fees from the gross quote output:

$$
\begin{aligned}q\_{\mathrm{gross}}&=\left\lfloor\frac{aQ}{T+a}\right\rfloor\q\_{\mathrm{out}}&=q\_{\mathrm{gross}}-\phi(q\_{\mathrm{gross}},0)\end{aligned}
$$

Deduct fees from buy input before pricing and from sell output afterward. Sells have no snipe tax. Inputs and reserves must be positive. Fees must be lower than the gross amount, and sell payouts cannot exceed `realQuote`.

The net quote required to buy y raw tokens is:

$$
q\_{\mathrm{required}}=\left\lceil\frac{Qy}{T-y}\right\rceil
$$

Require 0 < y < T and y ≤ `sellableTokens`. Add fees to obtain the gross input.

Outputs round down; required inputs round up. `quoteBuyNet` takes net quote and caps output at the sellable reserve. `quoteSellGross` returns quote before fees. `quoteNetRequiredToBuy` returns net input. Include fees and slippage in the transaction preview.

### Graduation and closing buys

$$
\begin{aligned}R&=\left\lfloor\frac{SP}{P+G}\right\rfloor\A&=\max(T-R,0)\end{aligned}
$$

R is `reservedTokens`; A is `sellableTokens`. An initialized curve that has not graduated is ready for Graduation when A = 0.

Read S, P, G and R from each curve. When the candidate output reaches A, the contract fills only the remaining sellable tokens. The combined fee rate F must be below B:

$$
\begin{aligned}t\_{\mathrm{out}}&=A\q\_{\mathrm{required}}&=\left\lceil\frac{QA}{T-A}\right\rceil\F&=f+s+c\q\_{\mathrm{calculated}}&=\left\lceil\frac{q\_{\mathrm{required}}B}{B-F}\right\rceil\q\_{\mathrm{spent}}&=\min(q\_{\mathrm{calculated}},g)\q\_{\mathrm{refund}}&=g-q\_{\mathrm{spent}}\q\_{\mathrm{actual}}&=q\_{\mathrm{spent}}-\phi(q\_{\mathrm{spent}},s)\end{aligned}
$$

Recalculate fees from actual spending (`quoteSpent`). Fee rounding can make the actual net input slightly exceed the required net input. Unused quote is refunded in the same transaction. See “Slippage and closing buys” for the adjusted minimum output.

### Worked example

Example: `S = 1,000,000,000` tokens, `P = 2,500` quote and `G = 10,000` quote, with 18 token decimals and 6 quote decimals. Read each launch’s parameters instead of hard-coding these values.

$$
\begin{aligned}p\_{\mathrm{open}}&=\frac{2{,}500}{1{,}000{,}000{,}000}=0.0000025\R&=200{,}000{,}000\A&=800{,}000{,}000\p\_{\mathrm{end}}&=\frac{2{,}500+10{,}000}{200{,}000{,}000}=0.0000625\\\frac{p\_{\mathrm{end}}}{p\_{\mathrm{open}}}&=25\end{aligned}
$$

Prices are quote assets per token; R and A are whole-token amounts. Terminal values are ideal values before integer rounding.

For a closing buy from the initial state with `f = 100` (1%), `s = 0` and `c = 0`, required net quote is 10,000.000000. A sufficient offer spends 10,101.010102, pays 101.010101 in fees and adds 10,000.000001 net quote. The extra raw unit results from rounding. The 25x ratio compares ideal marginal prices, not trade returns.

### V4 opening price

V4 receives only real quote. To preserve the curve’s terminal price, the executor adjusts the target token allocation:

Let U be `sweptTokens` and V be `sweptQuote`. The target pool allocation L and excess tokens E are:

$$
\begin{aligned}L&=\left\lfloor\frac{UV}{V+P}\right\rfloor\E&=U-L\end{aligned}
$$

The terminal curve price and initial pool price, both in raw units, are:

$$
\begin{aligned}p\_{\mathrm{curve}}^{\mathrm{raw}}&=\frac{V+P}{U}\p\_{\mathrm{pool}}^{\mathrm{raw}}&=\frac{V}{L}\end{aligned}
$$

Integer and V4 liquidity rounding make these prices approximately equal. In this example, 10,000 quote and a target of 160,000,000 tokens give 0.0000625 quote per token. Actual liquidity may use less than the target. The LP position and unused launch tokens are permanently locked.

### Fees

Each fee uses the same gross amount and rounds down separately:

<table><thead><tr><th width="126">Component</th><th width="136">Applies to</th><th>Notes</th></tr></thead><tbody><tr><td>Curve fee</td><td>buys and sells</td><td>The base protocol fee</td></tr><tr><td>Snipe tax</td><td><strong>buys only</strong></td><td>Decays with time from launch</td></tr><tr><td>Creator tax</td><td>buys and sells</td><td>Set at creation, bypasses all platform splits</td></tr></tbody></table>

Split base fees and snipe tax into platform and creator shares separately. Partners receive a share of the base platform fee only. Creator Tax goes directly to the creator allocation.

### Snipe tax

Let s₀ be the starting rate in basis points, D the duration in seconds, and t the elapsed seconds. For a non-exempt recipient:

$$
s(t)=\begin{cases}\left\lfloor\dfrac{s\_0}{2^{\lfloor14t/D\rfloor}}\right\rfloor,&0\le t\<D\0,&\text{otherwise}\end{cases}
$$

This is the integer right-shift decay used by the contract. The rate is zero for exempt recipients or a zero starting rate, and may round to zero before the window ends. A zero duration returns zero without division.

Snipe tax depends on the token recipient’s exemption status. Pass the actual `tokenRecipient`, including when a router or paymaster pays.

If omitted, `tokenRecipient` defaults to the connected account. This can produce incorrect fee and minimum-output estimates for another recipient.

The creator, creator fee recipient and initial-buy recipient are exempt automatically. Check other addresses with `client.isTaxExempt({ curve, account })`.

#### Read the snipe tax parameters

Factory settings apply to future launches. For an existing token, read its own BondingCurve snapshot and use the actual token recipient.

| Contract getter                            | Returned value and meaning                                                         |
| ------------------------------------------ | ---------------------------------------------------------------------------------- |
| `Factory.snipeTaxConfig()`                 | `uint16 startBps` and `uint32 durationSeconds`: configuration for future tokens.   |
| `Curve.snipeTaxConfigSnapshot()`           | The token's launch-time configuration: `s₀ = startBps` and `D = durationSeconds`.  |
| `Curve.launchedAt()`                       | `uint256` launch timestamp in Unix seconds; `t = block.timestamp - launchedAt()`.  |
| `Curve.isLaunchTaxExempt(account)`         | `bool` exemption status; SDK equivalent: `client.isTaxExempt({ curve, account })`. |
| `Curve.currentSnipeTaxBps(tokenRecipient)` | `uint256` current rate in bps, including the recipient's exemption.                |

Read the current Snipe Tax policy from Factory before quoting opening buys.

The following read-only example uses configured `client` and `publicClient` on the same network, a known launch `token` and the intended `tokenRecipient`. All reads use the same block.

```typescript
import { bondingCurveAbi } from "@masterpeach/launchpad-sdk/abi";

const block = await publicClient.getBlock();
const options = { blockNumber: block.number };
const curve = await client.getCurveAddress(token, options);
const { snipeTax, launchedAt } = await client.getCurveState({ curve }, options);
const currentSnipeTaxBps = await publicClient.readContract({
  address: curve,
  abi: bondingCurveAbi,
  functionName: "currentSnipeTaxBps",
  args: [tokenRecipient],
  ...options,
});
const elapsedSeconds = block.timestamp - launchedAt;
// s0 = snipeTax.startBps; D = snipeTax.durationSeconds; t = elapsedSeconds.
// currentSnipeTaxBps already accounts for this recipient's exemption.
```

When the protection window ends, only Snipe Tax becomes zero. The base fee and any configured Creator Tax continue to apply. The rate above is a block snapshot; refresh the quote before preparing a trade.

### Direct contract calls

SDK equivalents: prepareBuy and prepareSell. The same per-token curve exposes the following external entry points.

Always resolve the curve from `Factory.curveFor(token)`. Buy allowance is **quote token → curve**; sell allowance is **launch token → curve**. These trades pull funds from the caller, while the recipient arguments select where the output goes.

```
buyExactIn(
  uint256 quoteInRaw, address tokenRecipient, uint256 minTokenOut,
  uint256 deadline, bytes32 partnerId
) payable returns (uint256 tokenOut, uint256 quoteSpentRaw)

sellExactIn(
  uint256 tokenIn, address quoteRecipient, uint256 minQuoteOutRaw,
  uint256 deadline, bytes32 partnerId
) returns (uint256 quoteOutRaw)
```

Buy input includes trading fees and any applicable anti-snipe tax; sell output is net quote received. Both also have a four-argument overload without `partnerId`. Use zero bytes32 for no Partner; an unknown nonzero ID reverts. Read `PartnerRegistry.partner(partnerId)` before attributing a Partner.

`quoteBuyNet(uint256 netQuoteIn)` returns token output for quote input *after* fees. `quoteNetRequiredToBuy(uint256 tokenOut)` returns the required net quote. `quoteSellGross(uint256 tokenIn)` returns quote output *before* fees. These are curve-math helpers, not final wallet quotes. Combine the curve snapshots with `currentSnipeTaxBps(address account)` and simulate the exact caller, recipient, Partner and amounts.

A buy reaching the graduation boundary can consume only part of the requested input. Unused quote returns to the caller; the minimum output is scaled as `ceil(minTokenOut × quoteSpentRaw / quoteInRaw)`. Use actual spent/output amounts from the receipt. A `TradeFeeConsumesInput` revert can occur during anti-snipe protection; refresh the tax and quote instead of removing the output bound.

#### Direct call example (viem only)

This fragment assumes configured clients and a verified Factory/token pair. First submit `quoteToken.approve(curve, quoteInRaw)` if needed and wait for its successful receipt. The minimum below comes from the user's accepted fee-aware quote; simulation does not replace that limit.

```typescript
import { parseAbi, erc20Abi, zeroAddress, zeroHash } from "viem";

const factoryAbi = parseAbi([
  "function curveFor(address token) view returns (address)",
]);
const curveAbi = parseAbi([
  "function buyExactIn(uint256 quoteInRaw,address tokenRecipient,uint256 minTokenOut,uint256 deadline,bytes32 partnerId) payable returns (uint256 tokenOut,uint256 quoteSpentRaw)",
]);

// publicClient, walletClient, account, factory, token and quoteToken
// are configured for the same deployment. Amounts are bigint raw units.
// minTokenOut is a positive, user-approved bound from a fresh fee-aware quote.
if (await publicClient.getChainId() !== 5042 ||
    await walletClient.getChainId() !== 5042) throw new Error("Use Arc Mainnet");
if (quoteInRaw <= 0n || minTokenOut <= 0n) throw new Error("Invalid trade bounds");
const curve = await publicClient.readContract({
  address: factory, abi: factoryAbi, functionName: "curveFor", args: [token],
});
if (curve === zeroAddress) throw new Error("Unknown launch token");
const allowance = await publicClient.readContract({
  address: quoteToken, abi: erc20Abi, functionName: "allowance",
  args: [account.address, curve],
});
if (allowance < quoteInRaw) throw new Error("Approve quoteToken to curve first");
const deadline = (await publicClient.getBlock()).timestamp + 300n;
const { request, result } = await publicClient.simulateContract({
  account, address: curve, abi: curveAbi, functionName: "buyExactIn",
  args: [quoteInRaw, account.address, minTokenOut, deadline, zeroHash], value: 0n,
});
// result = [tokenOut, quoteSpentRaw] for this simulation.
const hash = await walletClient.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") throw new Error("Buy reverted");
// Read actual trade amounts and graduation events from receipt.logs.
```

For a sell, approve the launch token to the same curve, call `sellExactIn` with the desired quote recipient and a positive minimum net quote, and follow the same simulation/send/receipt sequence.


---

# 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/launchpad/launchpad-classic/core-features/bonding-curve-trading.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.
