> ## Documentation Index
> Fetch the complete documentation index at: https://pons-labs-llc.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Trading on the curve

> Buy, sell and quote a v2 token on its bonding curve, handle partial fills, and finish a graduation.

Until it graduates, a v2 token trades directly against its own curve, not
through a router. Resolve the curve from
[`getLaunchedToken`](https://pons-labs-llc.mintlify.site/developers/reading-state#the-launch-record).

## Buying and selling

```ts theme={null}
const curveAbi = parseAbi([
  "function buy(uint256 quoteIn, uint256 minTokensOut, address recipient) payable returns (uint256 tokensOut)",
  "function sell(uint256 tokensIn, uint256 minQuoteOut, address recipient) returns (uint256 quoteOut)",
]);
const erc20 = parseAbi(["function approve(address spender, uint256 amount) returns (bool)"]);

// ETH launch: quoteIn must equal the value sent.
await wallet.writeContract({ address: curve, abi: curveAbi, functionName: "buy", args: [quoteIn, minTokensOut, recipient], value: quoteIn });

// ERC-20 launch: approve the curve for the quote asset, send no value.
await wallet.writeContract({ address: pairToken, abi: erc20, functionName: "approve", args: [curve, quoteIn] });
await wallet.writeContract({ address: curve, abi: curveAbi, functionName: "buy", args: [quoteIn, minTokensOut, recipient] });

// Selling: approve the curve for the launch token first.
await wallet.writeContract({ address: token, abi: erc20, functionName: "approve", args: [curve, tokensIn] });
await wallet.writeContract({ address: curve, abi: curveAbi, functionName: "sell", args: [tokensIn, minQuoteOut, recipient] });
```

* Value sent to an ERC-20 launch reverts with `UnexpectedNativeValue`; the wrong
  value on an ETH launch reverts with `NativeValueMismatch`.
* A buy larger than what is left fills what remains and refunds the rest in the
  same transaction (`CurveBuyRefunded`). Read `tokensOut` from the return value or
  the `CurveBuy` event.
* `minTokensOut` bounds the price, not the quantity. A partial fill at your rate
  or better succeeds. Size it from the rate you quoted.

## Quoting

The curve has no quote function. Pricing is constant product with fees outside
the curve step, so you can reproduce it exactly from four reads. This is the
curve's own integer arithmetic, in its own order.

```ts theme={null}
const curveAbi = parseAbi([
  "function getReserves() view returns (uint256 quoteReserve, uint256 tokenReserve)",
  "function sellableTokens() view returns (uint256)",
  "function feeBps() view returns (uint256)",
  "function creatorTaxBps() view returns (uint256)",
  "function currentSnipeTaxBps(address recipient) view returns (uint256)",
]);

const BPS = 10_000n;
const ceilDiv = (a, b) => (a + b - 1n) / b;
const amountOut = (inAmt, rIn, rOut) => (inAmt * rOut) / (rIn + inAmt);
const amountIn = (outAmt, rIn, rOut) => (outAmt * rIn) / (rOut - outAmt) + 1n;

/** Quote asset in, launch token out. */
async function quoteBuy(curve, quoteIn, recipient) {
  const read = (functionName, args) => client.readContract({ address: curve, abi: curveAbi, functionName, args });
  const [[quoteReserve, tokenReserve], sellable, feeBps, creatorTaxBps, rawSnipeBps] = await Promise.all([
    read("getReserves"),
    read("sellableTokens"),
    read("feeBps"),
    read("creatorTaxBps"),
    // Curves from the archived stack have no snipe tax and no such function.
    read("currentSnipeTaxBps", [recipient]).catch(() => 0n),
  ]);

  // The snipe tax is capped so the buyer always nets at least 1% of spend.
  let snipeBps = rawSnipeBps;
  const maxSnipeBps = BPS - feeBps - creatorTaxBps - 100n;
  if (snipeBps > maxSnipeBps) snipeBps = maxSnipeBps;

  // A buy pays every fee off the input before the curve prices it.
  let spent = quoteIn;
  const fees = (spent * feeBps) / BPS + (spent * creatorTaxBps) / BPS + (spent * snipeBps) / BPS;
  let tokensOut = amountOut(spent - fees, quoteReserve, tokenReserve);

  // Past the sellable allocation: fill to the edge, reprice, refund the rest.
  if (tokensOut > sellable) {
    tokensOut = sellable;
    const net = amountIn(sellable, quoteReserve, tokenReserve);
    const grossed = ceilDiv(net * BPS, BPS - feeBps - creatorTaxBps - snipeBps);
    spent = grossed < quoteIn ? grossed : quoteIn;
  }
  return { tokensOut, spent, refund: quoteIn - spent };
}

/** Launch token in, quote asset out. No snipe tax on sells. */
async function quoteSell(curve, tokensIn) {
  const read = (functionName) => client.readContract({ address: curve, abi: curveAbi, functionName });
  const [[quoteReserve, tokenReserve], feeBps, creatorTaxBps] = await Promise.all([
    read("getReserves"), read("feeBps"), read("creatorTaxBps"),
  ]);
  // A sell is priced first; the fees come off the output.
  const gross = amountOut(tokensIn, tokenReserve, quoteReserve);
  return gross - (gross * feeBps) / BPS - (gross * creatorTaxBps) / BPS;
}
```

* Price against `getReserves()`. It includes the virtual opening reserve and
  excludes fees waiting to be swept. `realQuoteReserve()` is what the curve
  holds, and the wrong input for a quote.
* The snipe tax applies to buys only and is keyed on the **recipient**, so ask
  about the wallet you are buying for. See [snipe protection](https://pons-labs-llc.mintlify.site/protocol/snipe-protection.md).
* Quoting a sell as a mirrored buy overstates the proceeds.

## When the curve closes

Buys close when `sellableTokens()` reaches zero. Sells close at the same moment:
once `readyToGraduate()` is true, `sell` reverts with `CurveGraduated`, even
though the pool may not exist yet. Gate on `readyToGraduate()`, not `graduated`.

## Graduation

Graduation takes two transactions' worth of work, and only the first can happen
inside a buy.

**1. Sweep**

The buy that finishes the curve calls the factory's `graduate(token)`. The
curve hands over its reserves, the launch moves to phase `1` (Swept) and the
factory emits `LaunchSwept`.

**2. Create the pool**

`createGraduatedPool(token)` on the factory seeds the Uniswap v4 pool, locks
the position and moves the launch to phase `2`. It is a separate call, open to
anyone, and safe to retry. On a launch not in phase `1` it reverts with
`WrongGraduationPhase`.

Bundling contracts often run both steps in one transaction. Otherwise Pons runs
a keeper that creates the pool, usually within a few dozen blocks.

If the sweep inside the finishing buy fails, usually for gas, the curve emits
`AutoGraduationFailed` and the launch **stays in phase `0`** with
`readyToGraduate()` true. Anyone can then call `graduate(token)` followed by
`createGraduatedPool(token)`. `graduate` on a curve that is not finished reverts
with `NotReadyToGraduate`.

After phase `2`, route trades to the [Uniswap v4 pool](https://pons-labs-llc.mintlify.site/developers/uniswap-v4.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.