> ## Documentation Index
> Fetch the complete documentation index at: https://docs.rekthub.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Libraries

> Utility libraries for bonding curve math and calculations

## Overview

RektHub uses optimized libraries for bonding curve calculations. These utilities handle the constant product math that powers price discovery and trading.

<Info>
  **For Integrators:** You typically don't need to use these libraries
  directly—the BondingCurve contract handles all calculations. This reference is
  useful if you're building off-chain quoters, simulators, or custom trading
  algorithms.
</Info>

***

## BondingCurveMath

The core library for constant product (x × y = k) bonding curve calculations.

**Location:** `contracts/libraries/BondingCurveMath.sol`

### Purpose

* Calculate token outputs for buy orders
* Calculate native outputs for sell orders
* Calculate fees as percentages (basis points)
* Pure functions—no state modifications

***

## Functions

### calculateBuyReturn

Calculate how many tokens a buyer will receive for a given native token input.

```solidity theme={null}
function calculateBuyReturn(
    uint256 nativeAmount,
    uint256 virtualNativeReserves,
    uint256 virtualTokenReserves
) internal pure returns (uint256 tokensOut);
```

**Parameters:**

* `nativeAmount` (uint256): Amount of native tokens to spend (after fees)
* `virtualNativeReserves` (uint256): Current virtual native reserves in the curve
* `virtualTokenReserves` (uint256): Current virtual token reserves in the curve

**Returns:**

* `tokensOut`: Amount of tokens the buyer will receive

**Formula:**

```
tokensOut = (nativeAmount * virtualTokenReserves) / (virtualNativeReserves + nativeAmount)
```

This implements the constant product formula: `x * y = k`

**Example Usage:**

```javascript theme={null}
// Off-chain calculation (JavaScript)
function calculateBuyReturn(
	nativeAmount,
	virtualNativeReserves,
	virtualTokenReserves
) {
	return (
		(nativeAmount * virtualTokenReserves) / (virtualNativeReserves + nativeAmount)
	);
}

// Example
const nativeIn = ethers.parseEther('0.1');
const virtualNative = ethers.parseEther('30');
const virtualTokens = ethers.parseEther('1073000000');

const tokensOut = calculateBuyReturn(nativeIn, virtualNative, virtualTokens);
console.log('Will receive:', ethers.formatEther(tokensOut), 'tokens');
```

<Note>
  **Important:** This calculates the raw output before considering real reserve
  limits. The BondingCurve contract takes the minimum of this calculation and
  available real tokens.
</Note>

***

### calculateSellReturn

Calculate how many native tokens a seller will receive for selling tokens.

```solidity theme={null}
function calculateSellReturn(
    uint256 tokenAmount,
    uint256 virtualNativeReserves,
    uint256 virtualTokenReserves
) internal pure returns (uint256 nativeOut);
```

**Parameters:**

* `tokenAmount` (uint256): Amount of tokens to sell
* `virtualNativeReserves` (uint256): Current virtual native reserves in the curve
* `virtualTokenReserves` (uint256): Current virtual token reserves in the curve

**Returns:**

* `nativeOut`: Amount of native tokens the seller will receive (before fees)

**Formula:**

```
nativeOut = (tokenAmount * virtualNativeReserves) / (virtualTokenReserves + tokenAmount)
```

**Example Usage:**

```javascript theme={null}
// Off-chain calculation (JavaScript)
function calculateSellReturn(
	tokenAmount,
	virtualNativeReserves,
	virtualTokenReserves
) {
	return (
		(tokenAmount * virtualNativeReserves) / (virtualTokenReserves + tokenAmount)
	);
}

// Example
const tokensToSell = ethers.parseEther('1000000');
const virtualNative = ethers.parseEther('30');
const virtualTokens = ethers.parseEther('1073000000');

const grossNativeOut = calculateSellReturn(
	tokensToSell,
	virtualNative,
	virtualTokens
);
console.log('Gross output:', ethers.formatEther(grossNativeOut));

// Apply 1% fee
const fee = (grossNativeOut * 100n) / 10000n;
const netNativeOut = grossNativeOut - fee;
console.log('Net after fees:', ethers.formatEther(netNativeOut));
```

<Warning>
  **Fee Deduction:** `calculateSellReturn` returns the gross amount before fees.
  Always subtract the protocol fee (1%) to get the net amount users receive.
</Warning>

***

### calculateFee

Calculate a fee as a percentage using basis points.

```solidity theme={null}
function calculateFee(
    uint256 amount,
    uint256 feeBasisPoints
) internal pure returns (uint256 fee);
```

**Parameters:**

* `amount` (uint256): Amount to calculate fee on
* `feeBasisPoints` (uint256): Fee in basis points (100 = 1%, 10000 = 100%)

**Returns:**

* `fee`: Calculated fee amount

**Formula:**

```
fee = (amount * feeBasisPoints) / 10000
```

**Example Usage:**

```javascript theme={null}
// Off-chain calculation
function calculateFee(amount, bps) {
	return (amount * bps) / 10000n;
}

// Examples
const amount = ethers.parseEther('100');
const onePercent = calculateFee(amount, 100);
console.log('1% fee:', ethers.formatEther(onePercent));

const thirtyPercent = calculateFee(onePercent, 3000);
console.log('30% of fee:', ethers.formatEther(thirtyPercent));
```

<Tip>
  **Basis Points:** 1 basis point = 0.01%. Common values: 1% = 100 bps, 5% = 500
  bps, 10% = 1000 bps, 100% = 10000 bps
</Tip>

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Bonding Curves Explained" icon="chart-line" href="/getting-started/bonding-curves">
    Understand the economics
  </Card>

  <Card title="Bonding Curve Contract" icon="code" href="/evm/contracts/bonding-curve">
    See how it's implemented
  </Card>

  <Card title="Events Reference" icon="bell" href="/evm/reference/events">
    Track trades with events
  </Card>

  <Card title="Interfaces" icon="plug" href="/evm/reference/interfaces">
    Contract interfaces and ABIs
  </Card>
</CardGroup>
