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

# Bonding Phase

How buying and selling works during the bonding phase, fees, and thresholds.

## What is the Bonding Phase?

The bonding phase is the initial trading period where tokens are bought and sold directly from a smart contract using an algorithmic pricing curve. Think of it as a decentralized pre-sale with automatic market making.

```mermaid
stateDiagram-v2
    [*] --> Created: Token Deployed
    Created --> Bonding: Automatic
    Bonding --> Bonding: Buy/Sell Trades
    Bonding --> MigrationReady: Target Reached
    MigrationReady --> DEX: migrateToDex()
    DEX --> [*]: Fully Decentralized

    note right of Bonding
        Direct contract trading
        Algorithmic pricing
        5% trading fee
        Accumulates liquidity
    end note

    note right of DEX
        Uniswap v4 trading
        Market-driven price
        Standard LP fees
        No admin control
    end note
```

## How Bonding Works

### The Bonding Curve Mechanism

During bonding, the contract acts as the sole market maker:

1. **No Order Book**: Prices determined algorithmically
2. **Instant Liquidity**: Always able to buy or sell
3. **Path Independence**: Price depends only on supply, not history
4. **Automatic Pricing**: No manual price setting needed

## Trading Operations

### Buying Tokens

**How It Works**

**Process Flow:**
    1. User sends trading token (B3/ETH) to contract
    2. Contract calculates tokens based on curve
    3. 5% fee deducted and sent to recipient
    4. Tokens minted and sent to buyer
    5. Curve state updated

    **Code Example:**
    ```typescript
    // Get a quote first
    const quote = await token.getAmountOfTokensToBuy(
      parseEther("100") // 100 trading tokens
    );
    console.log(`Will receive: ${formatEther(quote)} tokens`);

    // Execute purchase with slippage protection
    const minTokens = quote * 0.95n; // 5% slippage
    await token.buy(parseEther("100"), minTokens);
    ```

  **Parameters**

| Parameter | Type | Description |
    |-----------|------|-------------|
    | `minTokensOut` | uint256 | Minimum tokens to receive (slippage protection) |
    | `tradingTokenAmount` | string/uint256 | Amount of trading token to spend |

    **Important Notes:**
    - Set `minTokensOut` to protect against front-running
    - Use 0 for `minTokensOut` only in low-activity periods
    - Transaction reverts if slippage exceeds tolerance

  **Edge Cases**

**Target Overflow:**
    - If purchase would exceed target, excess is refunded
    - Example: Target is 10 trading tokens, raised is 9.5 tokens
    - User sends 1 token → 0.5 tokens used, 0.5 tokens refunded

    **Insufficient Gas:**
    - Recommended gas limit: 200,000
    - Complex calculations may require more

    **Zero Amount:**
    - Transactions with 0 trading tokens will revert

### Selling Tokens

**How It Works**

**Process Flow:**
    1. User approves token spending
    2. User calls sell with token amount
    3. Contract calculates trading token amount based on curve
    4. 5% fee deducted from proceeds
    5. Trading token sent to seller, tokens burned
    6. Curve state updated (price decreases)

    **Code Example:**
    ```typescript
    // Check balance and get quote
    const balance = await token.balanceOf(userAddress);
    const sellAmount = balance / 2n; // Sell half

    const quote = await token.getAmountOfTradingTokensToSell(
      sellAmount
    );
    console.log(`Will receive: ${formatEther(quote)} trading tokens`);

    // Execute sale with slippage protection
    const minTradingTokenOut = quote * 0.95n; // 5% slippage
    await token.sell(sellAmount, minTradingTokenOut);
    ```

  **Parameters**

| Parameter | Type | Description |
    |-----------|------|-------------|
    | `tokenAmount` | uint256 | Amount of tokens to sell |
    | `minTradingTokenOut` | uint256 | Minimum trading token to receive (slippage protection) |

    **Important Notes:**
    - Requires token approval before selling
    - Price impact can be significant for large sells
    - Cannot sell more than circulating supply

  **Price Impact**

**Understanding Sell Impact:**

    Selling reduces the curve's raised amount, causing price to drop:

    | Sell Size | Price Impact | Recovery Needed |
    |-----------|--------------|-----------------|
    | 1% of supply | ~1-2% | Small |
    | 5% of supply | ~5-10% | Moderate |
    | 10% of supply | ~15-25% | Significant |
    | 20% of supply | ~30-50% | Major |

    *Actual impact depends on aggressiveness factor*

## Fee Structure

### How Fees Work

```mermaid
graph LR
    A[User Trade] -->|100%| B[Contract]
    B -->|95%| C[Curve/User]
    B -->|5%| D[Fee Recipient]

    style A fill:#e1f5fe
    style D fill:#c8e6c9
```

**Buy Fees**

**On a 1 trading token purchase:**
    - 0.95 trading tokens go to bonding curve
    - 0.05 trading tokens go to fee recipient
    - Tokens calculated on 0.95 trading token value

    **Example:**
    ```typescript
    // User sends 1 trading token
    // Fee: 0.05 trading token
    // Curve receives: 0.95 trading token
    // Tokens minted based on 0.95 trading token
    ```

  **Sell Fees**

**On selling for 1 trading token value:**
    - User receives 0.95 trading tokens
    - 0.05 trading tokens go to fee recipient
    - Curve reduced by full 1 trading token

    **Example:**
    ```typescript
    // Tokens worth 1 trading token on curve
    // Fee: 0.05 trading token
    // User receives: 0.95 trading tokens
    // Curve drops by 1 trading token
    ```

  **Fee Distribution**

**Where fees go:**
    - 100% to designated `feeRecipient` address
    - Can be project treasury, developer, or DAO
    - Set at token creation, cannot be changed

    **Claiming fees:**
    - Automatic - no claiming needed
    - Sent directly on each trade
    - No accumulation in contract

### Fee Economics

| Daily Volume | Fee Income | Monthly Income |
|-------------|------------|----------------|
| 10 trading tokens | 0.5 trading tokens | ~15 trading tokens |
| 50 trading tokens | 2.5 trading tokens | ~75 trading tokens |
| 100 trading tokens | 5 trading tokens | ~150 trading tokens |
| 500 trading tokens | 25 trading tokens | ~750 trading tokens |

## Target Mechanics

### Understanding the Target

The target is the amount of trading token that must be accumulated before migration:

**Target Purpose:**
  - Ensures sufficient liquidity for Uniswap v4
  - Creates a clear goal for the community
  - Prevents premature migration
  - Builds momentum during bonding

### Approaching the Target

```typescript
// Monitor progress toward target
async function trackProgress(token: BondkitToken) {
  const progress = await token.getBondingProgress();

  if (progress.progress < 0.5) {
    console.log("🌱 Early stage - best prices available");
  } else if (progress.progress < 0.8) {
    console.log("🚀 Momentum building - consider buying");
  } else if (progress.progress < 1.0) {
    console.log("🔥 Almost there - migration imminent");
  } else {
    console.log("✅ Target reached - ready to migrate!");
  }

  const remaining = progress.threshold - progress.raised;
  console.log(`Need ${formatEther(remaining)} more trading token`);
}
```

### Overflow Handling

When a purchase would exceed the target:

1. **Partial Fill**: Only the amount needed is accepted
2. **Automatic Refund**: Excess returned in same transaction
3. **Fair Completion**: No one can overpay at the end

**Example Scenario:**
```
Target: 100 trading tokens
Current: 99.5 trading tokens
User sends: 2 trading tokens

Result:
- 0.5 trading tokens accepted (reaches exactly 100)
- 1.5 trading tokens refunded
- User gets tokens for 0.5 trading tokens
- Migration now available
```

## Events & Monitoring

### Contract Events

**Buy Event**

```solidity
    event BondingCurveBuy(
        address indexed payer,
        address indexed recipient,
        uint256 tradingTokenIn,
        uint256 tokensOut,
        uint256 fee,
        uint256 totalRaisedBonding
    );
    ```

    **Listening in SDK:**
    ```typescript
    token.onBuy((event) => {
      console.log({
        buyer: event.payer,
        ethSpent: formatEther(event.tradingTokenIn),
        tokensReceived: formatEther(event.tokensOut),
        feePaid: formatEther(event.fee),
        totalRaised: formatEther(event.totalRaisedBonding)
      });
    });
    ```

  **Sell Event**

```solidity
    event BondingCurveSell(
        address indexed seller,
        uint256 tokensIn,
        uint256 tradingTokenOut,
        uint256 fee,
        uint256 totalRaisedBonding
    );
    ```

    **Listening in SDK:**
    ```typescript
    token.onSell((event) => {
      console.log({
        seller: event.seller,
        tokensSold: formatEther(event.tokensIn),
        ethReceived: formatEther(event.tradingTokenOut),
        feePaid: formatEther(event.fee),
        totalRaised: formatEther(event.totalRaisedBonding)
      });
    });
    ```

### Real-Time Monitoring

```typescript
// Complete monitoring setup
class BondingMonitor {
  constructor(private token: BondkitToken) {}

  async start() {
    // Initial state
    const progress = await this.token.getBondingProgress();
    console.log(`Starting at ${(progress.progress * 100).toFixed(2)}%`);

    // Monitor buys
    this.token.onBuy(async (event) => {
      const newProgress = await this.token.getBondingProgress();
      console.log(`BUY: ${formatEther(event.tokensOut)} tokens`);
      console.log(`Progress: ${(newProgress.progress * 100).toFixed(2)}%`);

      if (newProgress.progress >= 1.0) {
        console.log("🎆 TARGET REACHED! Migration available.");
      }
    });

    // Monitor sells
    this.token.onSell(async (event) => {
      const newProgress = await this.token.getBondingProgress();
      console.log(`SELL: ${formatEther(event.tokensIn)} tokens`);
      console.log(`Progress: ${(newProgress.progress * 100).toFixed(2)}%`);
    });
  }
}

// Usage
const monitor = new BondingMonitor(token);
await monitor.start();
```

## Bonding Phase Strategies

### For Token Creators

**Build Momentum**

- Start with lower aggressiveness (30-50)
    - Set achievable targets
    - Engage community early
    - Provide clear roadmap

  **Maximize Success**

- Seed initial liquidity yourself
    - Create buying incentives
    - Time announcements well
    - Plan for post-migration

### For Traders

**Entry Strategy**

- Buy early for best prices
    - Use DCA for large amounts
    - Monitor aggressiveness factor
    - Check target progress

  **Risk Management**

- Always use slippage protection
    - Understand price impact
    - Don't FOMO near target
    - Plan exit strategy

## Post-Bonding Transition

**Critical: After Migration**

  Once `migrateToDex()` is called:
  - ❌ Bonding curve trading permanently disabled
  - ❌ No more buy() or sell() functions
  - ✅ All trading moves to Uniswap v4
  - ✅ Standard AMM mechanics apply
  - ✅ Anyone can provide liquidity
  - ✅ Fully decentralized trading

## Next Steps

**[Pricing Guide](/bondkit/concepts/pricing)**

Understand price mechanics
  **[Target Setting](/bondkit/concepts/targets)**

Choose the right target
  **[Token Lifecycle](/bondkit/guides/token-lifecycle)**

Learn about DEX transition