# Technical Integration Guide

## Protocol Overview

The Panda factory Protocol implements a novel token launch mechanism using bonding curves with automatic liquidity provision. This guide will help you understand and integrate with the protocol's smart contracts.

#### Core Architecture

The protocol is built on three primary components that work together to provide token launch and trading functionality:

**1. PandaFactory**

The factory contract is the main entry point for deploying new tokens and pools. It:

* Manages protocol configurations
* Controls implementation versions
* Handles deployment permissions
* Manages protocol fees and incentives

> ⚠️ **Important**
>
> Always check if your implementation contract is approved by the factory using `isImplementationAllowed()` before attempting deployment.

**2. PandaToken**

Extends standard ERC20 functionality with bonding curve mechanics. Key features:

* ERC20 compliance with permit functionality
* Integrated bonding curve trading
* Automatic graduation to DEX trading
* Transfer restrictions pre-graduation

> 💡 **Note on Transfers**
>
> Transfers to the DEX pair address are blocked until graduation to maintain price curve integrity.

**3. PandaPool**

Implements the core bonding curve mechanics:

* Single-sided liquidity provisioning
* Price discovery mechanism
* Trading functionality
* Graduation handling

#### Protocol Mechanics

**Bonding Curve Mechanism**

The protocol uses a square root price model similar to Kodiak V3, but simplified for single-sided liquidity provision. The curve is defined by:

1. **Price Range**
   * `sqrtPa`: Lower bound of price range
   * `sqrtPb`: Upper bound of price range
   * Current price moves between these bounds

<img src="/files/8SQ8OrdR3eEyd0gC0MDW" alt="" class="gitbook-drawing">

2. **Token Distribution**
   * `tokensInPool`: Tokens available for bonding curve
   * `tokensForLp`: Tokens reserved for DEX liquidity
   * Distribution must satisfy pool share constraints

> ℹ️ **Mathematical Model**
>
> The price calculation follows: P = (sqrtP)² where sqrtP ranges from sqrtPa to sqrtPb Liquidity (L) remains constant: L = tokensInPool \* (sqrtPa \* sqrtPb) / (sqrtPb - sqrtPa)

**Graduation Process**

Graduation is the automatic transition from bonding curve to DEX trading. This occurs when:

1. Remaining tokens in pool ≤ 0.25% of initial pool tokens
2. Final price is used to set DEX pool ratio
3. Remaining tokens plus LP tokens are added to DEX

> ⚠️ **Critical**
>
> After graduation:
>
> * Trading switches to DEX pair
> * Bonding curve functions are disabled
> * Transfer restrictions are lifted

### Getting Started

#### Prerequisites

Before integrating with the protocol, ensure you have:

1. **Development Environment**
   * Solidity compiler v0.8.19
   * Web3 provider
   * Access to Berachain RPC
2. **Required Permissions**
   * Access to approved implementation contracts
   * Sufficient base tokens for deployment
   * Required approvals for trading
3. **Base Token Requirements**

   ```solidity
   interface IERC20 {
       function approve(address spender, uint256 amount) external returns (bool);
       function transfer(address to, uint256 amount) external returns (bool);
       function transferFrom(address from, address to, uint256 amount) external returns (bool);
   }
   ```

   Base tokens must:

   * Be ERC20 compliant
   * Return boolean for transfers/approvals
   * Have sufficient decimals (18 recommended)

> ⚠️ **Base Token Warning**
>
> Non-standard ERC20 tokens (e.g., fee-on-transfer, rebasing) are not supported and may cause unexpected behavior.

#### Network Requirements

| Requirement | Description               |
| ----------- | ------------------------- |
| Gas Limit   | Standard EVM operations   |
| Chain ID    | Berachain Mainnet/Testnet |
| RPC Support | Standard Web3 endpoints   |

### Key Concepts

#### Price Configuration

The protocol enforces strict bounds on price ranges to ensure proper functioning.

**Price Range Requirements**

```solidity
MIN_SQRTP_MULTIPLE = 11_000    // 1.1x minimum range
MAX_SQRTP_MULTIPLE = 100_000   // 10x maximum range
```

These translate to:

* Minimum price range: 1.21x (1.1² x)
* Maximum price range: 100x (10² x)

> 💡 **Price Range Tip**
>
> Choose price ranges that make sense for your token's economics. Wider ranges allow more price discovery but require more capital to complete.

**Example Price Calculations**

```javascript
// Convert display price to sqrt price
function displayToSqrtPrice(displayPrice) {
    return Math.sqrt(displayPrice * 1e18);
}

// Example price range setup
const minPrice = 1;   // 1 BASE per TOKEN
const maxPrice = 10;  // 10 BASE per TOKEN

const sqrtPa = displayToSqrtPrice(minPrice);
const sqrtPb = displayToSqrtPrice(maxPrice);

// Verify range is valid
const multiple = (sqrtPb * 10000) / sqrtPa;
if (multiple < MIN_SQRTP_MULTIPLE || multiple > MAX_SQRTP_MULTIPLE) {
    throw new Error('Invalid price range');
}
```

#### Token Distribution Parameters

The protocol enforces constraints on token distribution to ensure proper liquidity.

**Pool Share Requirements**

```solidity
MIN_TOKENSINPOOL_SHARE = 5000  // 50% minimum in pool
MAX_TOKENSINPOOL_SHARE = 9000  // 90% maximum in pool
```

Distribution visualization:

```
Total Supply (1B tokens)
|-------------------------------------------|
|    Pool Tokens     |     LP Tokens        |
|    (50-90%)       |     (10-50%)         |
|-------------------------------------------|
```

> ℹ️ **Pool Share Information**
>
> * Pool tokens: Available for bonding curve trading
> * LP tokens: Reserved for DEX liquidity after graduation
> * Ratios affect final DEX liquidity depth

#### Fee Structure

The protocol implements a comprehensive fee structure:

```solidity
struct PandaFees {
    uint16 buyFee;           // Fee on buy operations
    uint16 sellFee;          // Fee on sell operations
    uint16 graduationFee;    // Fee at graduation
    uint16 deployerFeeShare; // Share of fees to deployer
}
```

Fee considerations:

1. **Buy/Sell Fees**
   * Taken in base token
   * Calculated on input amount
   * Sent to treasury
2. **Graduation Fee**
   * Taken from final base token balance
   * Split between treasury and deployer
   * Affects final DEX liquidity

> 💡 **Fee Calculation Tip**
>
> When calculating required inputs, account for fees:
>
> ```javascript
> const totalInput = desiredAmount * (1 + buyFee / 10000);
> ```

### Integration Guide

#### 1. Token Deployment

Deploying a new token requires careful preparation and parameter selection.

**Pre-Deployment Checklist**

* [ ] Verify implementation is allowed
* [ ] Calculate valid price range
* [ ] Determine token distribution
* [ ] Prepare token metadata
* [ ] Check base token configuration

**Deployment Process**

1. **Calculate Parameters**

```javascript
const params = {
    baseToken: baseTokenAddress,
    sqrtPa: calculateSqrtPrice(minPrice),
    sqrtPb: calculateSqrtPrice(maxPrice),
    vestingPeriod: 0  // No vesting for standard deployment
};
```

2. **Deploy Token**

```javascript
// For ERC20 base tokens
const tx = await factory.deployPandaToken(
    implementation,
    params,
    "Token Name",
    "SYMBOL",
    deployerSupplyBps  // Optional deployer allocation
);

// For native BERA
const tx = await factory.deployPandaTokenWithBera(
    implementation,
    params,
    "Token Name",
    "SYMBOL",
    deployerSupplyBps,
    { value: beraAmount }
);
```

> ⚠️ **Deployment Warning**
>
> * Verify all parameters before deployment
> * Deployment cannot be reversed
> * Parameters cannot be changed after deployment

#### 2. Trading Integration

**Pre-Trading Requirements**

1. Base token approvals
2. Minimum trade size check
3. Price impact calculations
4. Slippage protection

**Trading Functions**

1. **Buy Tokens**

```javascript
// Calculate expected output
const [amountOut, fee, sqrtP] = await pandaToken.getAmountOutBuy(amountIn);

// Apply slippage tolerance
const minOut = amountOut * (1 - slippageTolerance);

// Execute trade
const tx = await pandaToken.buyTokens(amountIn, minOut, recipient);
```

2. **Sell Tokens**

```javascript
// Calculate expected output
const [amountOut, fee, sqrtP] = await pandaToken.getAmountOutSell(amountIn);

// Apply slippage tolerance
const minOut = amountOut * (1 - slippageTolerance);

// Execute trade
const tx = await pandaToken.sellTokens(amountIn, minOut, recipient);
```

> 💡 **Trading Tips**
>
> * Always use getAmountOut functions to estimate outputs
> * Include reasonable slippage tolerance
> * Monitor price impact on larger trades

**Price Monitoring**

```javascript
// Get current price
const currentPrice = await pandaToken.getCurrentPrice();

// Get remaining tokens
const remaining = await pandaToken.remainingTokensInPool();

// Check graduation proximity
const graduationThreshold = remaining * 25 / 10000;  // 0.25%
```

#### 3. Graduation Handling

**Graduation Detection**

1. **Event Monitoring**

```javascript
pandaToken.on('LiquidityMoved', (amountPanda, amountBase) => {
    // Handle graduation
    switchToDexTrading();
});
```

2. **State Checking**

```javascript
const graduated = await pandaToken.graduated();
if (graduated) {
    const dexPair = await pandaToken.dexPair();
    // Update trading logic
}
```

**Post-Graduation Integration**

After graduation:

1. Switch to DEX pair for trading
2. Update price feeds
3. Remove pre-graduation restrictions

> ℹ️ **Graduation Information**
>
> Graduation is permanent and irreversible. Always check graduated() state before operations.

### Error Handling

#### Common Errors

| Error                        | Description                | Solution                      |
| ---------------------------- | -------------------------- | ----------------------------- |
| `INVALID_IMPLEMENTATION`     | Implementation not allowed | Verify implementation address |
| `PRICES_TOO_CLOSE`           | Invalid price range        | Increase price range          |
| `PRICES_TOO_FAR`             | Invalid price range        | Decrease price range          |
| `INSUFFICIENT_OUTPUT_AMOUNT` | Slippage check failed      | Increase slippage tolerance   |
| `TRADE_BELOW_MIN`            | Trade size too small       | Increase trade size           |
| `GRADUATED`                  | Pool already graduated     | Switch to DEX trading         |

#### Error Recovery Strategies

1. **Deployment Failures**
   * Verify all parameters
   * Check implementation status
   * Ensure base token configuration
2. **Trading Failures**
   * Refresh price data
   * Adjust slippage tolerance
   * Check trade size requirements
3. **Graduation Issues**
   * Monitor graduation events
   * Handle state transitions
   * Update integration logic

> ⚠️ **Error Handling Best Practices**
>
> * Always wrap interactions in try-catch
> * Implement proper error recovery
> * Monitor transaction status
> * Handle reverted transactions

### Security Considerations

#### Important Checks

1. **Pre-deployment**
   * Implementation verification
   * Parameter validation
   * Base token compatibility
2. **Trading**
   * Slippage protection
   * Price impact monitoring
   * Balance checks
3. **Post-graduation**
   * State verification
   * DEX pair validation
   * Trading updates

> ⚠️ **Security Warnings**
>
> * Never expose private keys
> * Validate all input parameters
> * Monitor for unexpected state changes
> * Implement proper access controls


---

# 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://documentation.kodiak.finance/developers/panda/technical-integration-guide.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.
