# Reference

Every public export of `@tontonfun/sdk`, grouped by module.

## Codec

### `buildLaunchToken(opts)`

Body for `LAUNCH_TOKEN` (`0x4c4e4348`) — call on the factory.

```ts
buildLaunchToken({
  queryId: bigint;
  content: Cell;         // from buildOffchainContent()
}): Cell
```

### `buildBuyTokens(queryId, minTokensOut)`

Body for `BUY_TOKENS` (`0x42555900`) — call on the curve.

```ts
buildBuyTokens(queryId: bigint, minTokensOut: bigint): Cell
```

### `buildSellTransfer(opts)`

Body for a sell — TEP-74 `JETTON_TRANSFER` (`0x0f8a7ea5`) targeted at the seller's jetton wallet, with the `SELL` op carried inline as `Slice as remaining`.

```ts
buildSellTransfer({
  queryId: bigint;
  sellAmount: bigint;
  curveAddress: Address;
  seller: Address;
  minTonOut: bigint;
  forwardTon?: bigint;   // default 0.1 TON (0.1 nano TON)
}): Cell
```

> **Do not modify** to add an Either-tag bit. The Tact-generated curve will refund.

### `buildGraduate(queryId)`

Permissionless idempotent graduation trigger. Send to the curve, value \~0.1 TON. Only needed if the buy that crossed the cap somehow failed to auto-graduate.

### `buildRetryMint(queryId)`

M1 recovery — re-trigger the curve's mint into the master. Send to the curve, value \~0.1 TON. Anyone can call.

### `buildRetryDeposit(queryId)`

M2 recovery — re-emit unsent halves of the LP provide. Send to the adapter, value \~0.5 TON. Creator-only.

### `buildOffchainContent(metadataUri)`

TEP-64 offchain content cell.

```ts
buildOffchainContent(metadataUri: string): Cell
```

### `parseOffchainContent(content)`

Returns the metadata URI string or `null` if the cell isn't a valid TEP-64 offchain wrapper.

### `ipfsToHttp(uri, gateway?)`

Converts `ipfs://CID/path` → `https://<gateway>/ipfs/CID/path`.

### Decoders

| Function                        | Returns                                         |
| ------------------------------- | ----------------------------------------------- |
| `tryDecodeLaunchToken(body)`    | `{ op, queryId, content, metadataUri } \| null` |
| `tryDecodeBuyTokens(body)`      | `{ op, queryId, minTokensOut } \| null`         |
| `tryDecodeJettonTransfer(body)` | full TEP-74 transfer struct or `null`           |
| `tryDecodeTransferNotify(body)` | TEP-74 notify struct or `null`                  |
| `peekOp(body)`                  | First 32-bit op as `number` or `null`           |

## Curve math

### `quoteBuyDetailed(tonGross, tokensSold, tonCollected)`

Full breakdown of a buy:

```ts
interface BuyQuote {
  jettonsOut: bigint;
  protocolFee: bigint;
  creatorFee: bigint;
  refund: bigint;        // non-zero only on cap-and-refund path
}
```

### `quoteBuyOffchain(tonGross, tokensSold, tonCollected)`

Just the headline number — equivalent to `quoteBuyDetailed(...).jettonsOut`.

### `quoteSellOffchain(jettonsIn, tokensSold, tonCollected)`

Returns the net TON the seller will receive (after both fees). Returns `0n` if `jettonsIn > tokensSold` (which would trip the contract's refund path).

### `curveProgress(tokensSold)`

`0 .. 1` fraction of `CURVE_ALLOC` already sold.

### `spotPriceNano(tokensSold, tonCollected)`

Spot price as `bigint` scaled by `1e18` (precision-preserving).

### `spotPriceTonPerToken(tokensSold, tonCollected)`

Same as above but as a JS `number`.

### Unit helpers

| Function                     | Behaviour                                           |
| ---------------------------- | --------------------------------------------------- |
| `tonToNano(ton)`             | `number \| string` → `bigint` nano-TON              |
| `nanoToTon(nano)`            | `bigint` → `number` TON                             |
| `jettonsToBaseUnits(amount)` | Same as `tonToNano` (jettons share 9 decimals).     |
| `baseUnitsToJettons(base)`   | Same as `nanoToTon`.                                |
| `withSlippage(quote, pct)`   | Multiplies by `(100 - pct) / 100` with BigInt math. |

## Get-methods

```ts
getCurveAddress(
  client: TonClient,
  factory: Address,
  creator: Address,
  content: Cell,
): Promise<Address>
```

```ts
interface CurveState {
  tokensSold: bigint;
  tonCollected: bigint;
  graduated: boolean;
  launched: boolean;
  initSettled: boolean;
  jettonMaster: Address;
}
getCurveState(client: TonClient, curve: Address): Promise<CurveState>
```

```ts
getJettonWalletAddress(
  client: TonClient,
  master: Address,
  owner: Address,
): Promise<Address>
```

```ts
getJettonWalletBalance(
  client: TonClient,
  wallet: Address,
): Promise<bigint>
```

`getJettonWalletBalance` returns `0n` if the wallet isn't deployed (which is the normal pre-first-transfer state for TEP-74 jetton wallets).

## Tx helpers

### `prepareBuyTx(opts)` / `prepareSellTx(opts)`

Wallet-agnostic envelope builders. See [Quickstart](broken://pages/62c84d56f6052f931acf805acc1dd0303d7da7c2).

```ts
interface TonEnvelope {
  to: string;            // friendly address (EQ/UQ)
  value: string;         // nano-TON as decimal string (TonConnect shape)
  body: Cell;            // pass through .toBoc().toString('base64') if needed
}
```

### `envelopeToTonConnect(env)`

```ts
envelopeToTonConnect(env: TonEnvelope): {
  address: string;
  amount: string;
  payload: string;       // base64 BoC
}
```

### `sendInternal(sender, opts)`

Build + send a single internal-message transfer.

```ts
sendInternal(
  send: SendTxFn,                                 // any send-tx-compatible function
  opts: {
    to: string;
    valueNano: bigint;
    body: Cell;
    validForSeconds?: number;                     // default 360s
  },
): Promise<{ boc: string }>
```

### `pollUntil(predicate, opts?)`

Polls every `intervalMs` (default 3000) until `predicate()` returns `true` or `timeoutMs` (default 60000) elapses. Returns `true` on success, `false` on timeout.

### `newRandomQueryId()`

64-bit pseudo-random `bigint`. Wallets dedupe on this — never reuse one across two simultaneous txs.

## Network helpers

| Function                      | Returns                                       |
| ----------------------------- | --------------------------------------------- |
| `tonViewerTxUrl(hash)`        | `https://tonviewer.com/transaction/<hash>`    |
| `tonViewerAddrUrl(addr)`      | `https://tonviewer.com/<addr>`                |
| `stonFiSwapUrl(jettonMaster)` | `https://app.ston.fi/swap?ft=TON&tt=<master>` |


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.tonton.fun/sdk/reference.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
