For the complete documentation index, see llms.txt. This page is also available as Markdown.

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

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 — Choose the required asset, amount and spender.

Buy tokens

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

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:

meff=⌈mqspentqin⌉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:

Q=P+qrealK=QT\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:

pspot=QT 10dtoken−dquotep_{\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:

x=S−TK0=PSqraised(x)=PxS−xp(x)=PS(S−x)2 10dtoken−dquote\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.

ϕ(g,s)=⌊gfB⌋+⌊gsB⌋+⌊gcB⌋\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:

qnet=g−ϕ(g,s)tcandidate=⌊qnetTQ+qnet⌋\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:

qgross=⌊aQT+a⌋qout=qgross−ϕ(qgross,0)\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:

qrequired=⌈QyT−y⌉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

R=⌊SPP+G⌋A=max⁡(T−R,0)\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:

tout=Aqrequired=⌈QAT−A⌉F=f+s+cqcalculated=⌈qrequiredBB−F⌉qspent=min⁡(qcalculated,g)qrefund=g−qspentqactual=qspent−ϕ(qspent,s)\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.

popen=2,5001,000,000,000=0.0000025R=200,000,000A=800,000,000pend=2,500+10,000200,000,000=0.0000625pendpopen=25\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:

L=⌊UVV+P⌋E=U−L\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:

pcurveraw=V+PUppoolraw=VL\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:

Component
Applies to
Notes

Curve fee

buys and sells

The base protocol fee

Snipe tax

buys only

Decays with time from launch

Creator tax

buys and sells

Set at creation, bypasses all platform splits

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)={⌊s02⌊14t/D⌋⌋,0≤t<D0,otherwises(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.

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.

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.

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.

Last updated

Was this helpful?