# Launchpad

## 1. Introduction

### Intro

The Launchpad project is a comprehensive suite of smart contracts designed to enable the launch of tokenized projects with integrated liquidity management, bonding curve mechanics, and community governance features. It serves as a platform where projects can easily create and manage tokens while providing mechanisms for initial liquidity and ongoing token management within the ecosystem.

### Core Concepts

* **Tokenized Communities**: Create ERC20 tokens with linked governance capabilities
* **Bonding Curve Economics**: Mathematical models that determine token pricing based on supply and demand
* **Automated Liquidity**: Built-in liquidity management through bonding curves and AMM integrations
* **Community Governance**: Token-based governance mechanisms for community decision-making
* **Contest Management**: Competitive structures to drive engagement within tokenized communities
* **Referral Systems**: Ecosystem growth through incentivized referrals

## 2. Deployments

*Last Updated: April 18, 2025*

### Contract Addresses

#### Base Network

| Contract Name                                                                                                                                | Address                                    |
| -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ |
| Launchpad                                                                                                                                    | 0x0C1786961CfDac88EdEb5728E52F73A0DbBe7813 |
| LPBondingCurve                                                                                                                               | 0x4bF195932E20Dc8459419Bc93a84B713bED20f38 |
| LPCurveManager                                                                                                                               | 0xaD1Bb96Db38C4839c74575A39AFabaD542597267 |
| BancorFormula                                                                                                                                | 0xBe8E967a9861fE7909de77F9dE6D6C2085d178dF |
| UniswapV3LPHook                                                                                                                              | 0x161DEa1Cd223AF8F86896502EAE96C7A5BFC4916 |
| ReferralActionHook                                                                                                                           | 0x9FF48192c34c5Af4bd9FF31bD9ad9d6f1983c203 |
| LPContestManager                                                                                                                             | 0xe1E3Ee066455d105790bedc5b8290E920d8eD2de |
| TokenCommunityManager                                                                                                                        | 0x2a813bdf2eac0c5cb270570218bc436a996da6c1 |
| ReferralFeeManager                                                                                                                           | 0x84A0CFb53a77202777fdbc845e7A5bb214311e88 |
| ReferralClaimHook                                                                                                                            | 0x5fd4a4e28ef1eab1f74046ac15039ad05064345b |
| *For additional networks (ETH Mainnet, BSC, Optimism, Linea, Arbitrium), please refer to the contract deployment details in our repository.* |                                            |

### Protocol Configuration and Parameters

| Parameter                        | Value                                      | Description                                                |
| -------------------------------- | ------------------------------------------ | ---------------------------------------------------------- |
| Launch Fee Amount (Base Mainnet) | 444000000000000 wei (0.000444 ETH)         | Fee required to launch a new token on Base Mainnet         |
| Launch Fee Amount (Base Sepolia) | 0 ETH                                      | Fee required to launch a new token on Base Sepolia testnet |
| Protocol Fee                     | 10000000000000000 (1%)                     | Percentage fee taken on transactions                       |
| Protocol Vault                   | 0x9d3BE262bed6f3A0Aab4e97c0232071EF730632f | Address where protocol fees are collected                  |
| Owner                            | 0x486BC1E7e48aCF707b3e990f266FD7207a177522 | Contract owner address with admin rights                   |

### Token Price Initialization

Initial token price is determined by the ETH value received by the LPBondingCurve contract from the `launchToken` transaction on the Launchpad contract. The calculation follows this process:

1. User sends a transaction with a specific ETH value (`msg.value`) to the Launchpad's `launchTokenWithLiquidity` function
2. Launchpad deducts the launch fee from this value
3. The remaining amount (`msg.value - launchFee`) is passed to LPBondingCurve via [`registerToken`](#lpbondingcurvesol)
4. This remaining amount establishes the initial token price through the bonding curve formula

This mechanism allows for flexible starting price points based on the initial ETH contribution. Note that `msg.value` must be greater than the launch fee to create any meaningful initial price.

**Fund Flow for Token Launch:**

```
User Transaction [totalValue] ──▶ Launchpad ──[totalValue - launchFee]──▶ LPBondingCurve
```

## 3. Events

## Event Signatures

| Event Name                                    | Contract Name         | Event Signature (topic0)                                             |
| --------------------------------------------- | --------------------- | -------------------------------------------------------------------- |
| [TokenLaunched](#tokenlaunched)               | Launchpad             | `0x49628fd1471006c1482da88028e9ce4dbb080b815c9b0344d89461a86bf2662b` |
| [LaunchpadFeeUpdated](#launchpadfeeupdated)   | Launchpad             | `0x6be8a6e5570ea7f94db0e0a94ea255edefbe4156a7e33e66e0d30c5fafda1311` |
| [LaunchpadCreated](#launchpadcreated)         | Launchpad             | `0x6c609cd15c5d8c38ee4d6addf46ca8d289008474fcf5d0430da7d14992425476` |
| [TokenRegistered](#tokenregistered)           | LPBondingCurve        | `0xb7337a12287e98a6adb7027e11ab8882e53874b818b3c71c36eb3ec34564435b` |
| [TokenPurchased](#tokenpurchased)             | LPBondingCurve        | `0xd7ad6cea671371a29863221c68dad44b3181ae274783aaa713af6ed898a8976c` |
| [TokenSold](#tokensold)                       | LPBondingCurve        | `0x9f7e860203e08a8dab749a3b13c3c9cf5e13b232b57c5c2cd3e51397a03dcfc2` |
| [LiquidityTransferred](#liquiditytransferred) | LPBondingCurve        | `0xaa3e5c78a54096e4979a5ffbb7379489ba9cd4bb8e2c2ec6bcfd195a537f503c` |
| [ReentryLock](#reentrylock)                   | LPBondingCurve        | `0x0446226aa5875fb5d9394afa5e2550027b4c19e0c598b27307a7c427779d90d8` |
| [CurveCreated](#curvecreated)                 | LPCurveManager        | `0xbab74d8b45a950447a155c6965a441957e8b62b5aff2efe0844f551ad74dd8e2` |
| [CurveUpdated](#curveupdated)                 | LPCurveManager        | `0x4b8d4340eb515bcd3d5a351d73aed6bb06e95efe3c9ded4adad26e487f4f9c30` |
| [CurveStopped](#curvestopped)                 | LPCurveManager        | `0xb8ec9c41c4afb4c9c67a61d7854e2a44c36ebbb504b541fe6d5b5856d4fc6510` |
| [ContestStarted](#conteststarted)             | LPContestManager      | `0xdb22c8c8e7e694dddae95cf41764b1998d1147dd1e90faab16250c29e88e066d` |
| [ContestEnded](#contestended)                 | LPContestManager      | `0xf48705a80b95c5d0b90c2bcc8882d845d83b5c7677a4c52e9a89c81d70a45aa1` |
| [LiquidityCreated](#liquiditycreated)         | UniswapV3LPHook       | `0xd5a14d7a354eb68c3b3c9a315ef1ff9f2369b7d48c4b8669d0f58fb8686be840` |
| [FeesCollected](#feescollected)               | UniswapV3LPHook       | `0x37a5be4e73b1c606ef99fa416b8adf8f588624b53a915a3e4dc92a17b7da0213` |
| [ReferralRecorded](#referralrecorded)         | ReferralActionHook    | `0x12bf5155cc57be50f47ee64b3a2c971823b9cbdc3cd1ac5117e1ef9a424b4a39` |
| [ReferralRewardPaid](#referralrewardpaid)     | ReferralActionHook    | `0x4ed4ee9523d0cedacc24ec78b79574478d208f2a2f7a8e613572a5ffd6d8f912` |
| [BuyRecorded](#buyrecorded)                   | KOHCurveActionHook    | `0x6a1cdb55709cbdd3841e8ccb475be0b489f3a8d9f625b43f1d53b265f4d8e19b` |
| [SellRecorded](#sellrecorded)                 | KOHCurveActionHook    | `0x96dd44fc85b41a209c4c594f6a363b9867ca6e81b6b926527f4972c7a4bc9fda` |
| [TopThreeUpdated](#topthreeupdated)           | KOHContest            | `0x4adc59efaf9eb909c3b1e1a6bee30f5c89976a939c2b8e11d3c68bb4c3043ae0` |
| [TokenCommunityLinked](#tokencommunitylinked) | TokenCommunityManager | `0x5c3add02829de3863c98f3ba9a3fbce70aa0c779b04d0ce50c26164e32fbfd9f` |
| [GovernorDeployed](#governordeployed)         | TokenCommunityManager | `0x68d226731ad1ca15dd89d10bafe344be6e827436439d392b1cbd48ca4af28abe` |

## Events by Contract

### Launchpad Contract

#### TokenLaunched

**Event Explanation:** Emitted when a new token is successfully launched through the Launchpad platform.

**Parameters:**

```solidity
event TokenLaunched(
    address indexed token,    // Address of the newly created token contract
    address indexed creator,  // Address of the token creator/launcher
    uint256 initialLiquidity  // Amount of initial liquidity provided
);
```

**Signature:** `0x49628fd1471006c1482da88028e9ce4dbb080b815c9b0344d89461a86bf2662b`

**Called By:** `launchTokenWithLiquidity` function

#### LaunchpadFeeUpdated

**Event Explanation:** Emitted when the launchpad fee amount is updated by the owner.

**Parameters:**

```solidity
event LaunchpadFeeUpdated(
    uint256 oldFee,  // Previous fee amount
    uint256 newFee   // New fee amount
);
```

**Signature:** `0x6be8a6e5570ea7f94db0e0a94ea255edefbe4156a7e33e66e0d30c5fafda1311`

**Called By:** `updateLaunchFeeAmount` function

#### LaunchpadCreated

**Event Explanation:** Emitted when a new Launchpad instance is created.

**Parameters:**

```solidity
event LaunchpadCreated(
    address launchpad  // Address of the newly created Launchpad contract
);
```

**Signature:** `0x6c609cd15c5d8c38ee4d6addf46ca8d289008474fcf5d0430da7d14992425476`

**Called By:** Contract constructor or factory deployment function

### LPBondingCurve Contract

#### TokenRegistered

**Event Explanation:** Emitted when a new token is registered with the bonding curve system.

**Parameters:**

```solidity
event TokenRegistered(
    address indexed token,     // Address of the registered token
    address indexed creator,   // Address of the token creator
    uint256 initialLiquidity   // Amount of initial liquidity provided
);
```

**Signature:** `0xb7337a12287e98a6adb7027e11ab8882e53874b818b3c71c36eb3ec34564435b`

**Called By:** `registerToken` function

#### TokenPurchased

**Event Explanation:** Emitted when tokens are purchased through the bonding curve mechanism.

**Parameters:**

```solidity
event TokenPurchased(
    address indexed buyer,   // Address of the token buyer
    address indexed token,   // Address of the token being purchased
    uint256 amountIn,        // Amount of currency sent for purchase
    uint256 amountOut        // Amount of tokens received
);
```

**Signature:** `0xd7ad6cea671371a29863221c68dad44b3181ae274783aaa713af6ed898a8976c`

**Called By:** `buyToken` and `_buyToken` functions

#### TokenSold

**Event Explanation:** Emitted when tokens are sold back to the bonding curve.

**Parameters:**

```solidity
event TokenSold(
    address indexed seller,   // Address of the token seller
    address indexed token,    // Address of the token being sold
    uint256 amountIn,         // Amount of tokens sold
    uint256 amountOut         // Amount of currency received
);
```

**Signature:** `0x9f7e860203e08a8dab749a3b13c3c9cf5e13b232b57c5c2cd3e51397a03dcfc2`

**Called By:** `sellToken` function

#### LiquidityTransferred

**Event Explanation:** Emitted when liquidity is transferred from the bonding curve to another destination.

**Parameters:**

```solidity
event LiquidityTransferred(
    address indexed token,    // Address of the token
    uint256 amount,           // Amount of liquidity transferred
    address destination       // Destination address receiving the liquidity
);
```

**Signature:** `0xaa3e5c78a54096e4979a5ffbb7379489ba9cd4bb8e2c2ec6bcfd195a537f503c`

**Called By:** `transferLiquidity` function

#### ReentryLock

**Event Explanation:** Emitted when a reentry lock is activated to prevent reentrancy attacks.

**Parameters:**

```solidity
event ReentryLock(
    address indexed caller,   // Address of the caller that triggered the lock
    uint256 timestamp         // Timestamp when the lock was activated
);
```

**Signature:** `0x0446226aa5875fb5d9394afa5e2550027b4c19e0c598b27307a7c427779d90d8`

**Called By:** `_nonReentrantBefore` function

### LPCurveManager Contract

#### CurveCreated

**Event Explanation:** Emitted when a new bonding curve is created and registered in the system.

**Parameters:**

```solidity
event CurveCreated(
    uint256 curveId,          // ID of the newly created curve
    address logicContract     // Address of the logic contract implementing the curve formula
);
```

**Signature:** `0xbab74d8b45a950447a155c6965a441957e8b62b5aff2efe0844f551ad74dd8e2`

**Called By:** `createCurve` function

#### CurveUpdated

**Event Explanation:** Emitted when an existing curve's parameters are updated.

**Parameters:**

```solidity
event CurveUpdated(
    uint256 curveId,    // ID of the updated curve
    bool isFrozen,      // New frozen status
    bool isVetted       // New vetted status
);
```

**Signature:** `0x4b8d4340eb515bcd3d5a351d73aed6bb06e95efe3c9ded4adad26e487f4f9c30`

**Called By:** `updateCurve` function

#### CurveStopped

**Event Explanation:** Emitted when a curve is stopped or its operations are frozen.

**Parameters:**

```solidity
event CurveStopped(
    uint256 curveId,    // ID of the stopped curve
    bool isFrozen       // Frozen status (true when stopped)
);
```

**Signature:** `0xb8ec9c41c4afb4c9c67a61d7854e2a44c36ebbb504b541fe6d5b5856d4fc6510`

**Called By:** `freezeCurve` function

### LPContestManager Contract

#### ContestStarted

**Event Explanation:** Emitted when a new contest is started for a token community.

**Parameters:**

```solidity
event ContestStarted(
    address indexed token,     // Address of the token for which the contest is started
    uint256 indexed contestId, // Unique identifier for the contest
    uint256 startTime,         // Timestamp when the contest starts
    uint256 endTime            // Timestamp when the contest ends
);
```

**Signature:** `0xdb22c8c8e7e694dddae95cf41764b1998d1147dd1e90faab16250c29e88e066d`

**Called By:** `startContest` function

#### ContestEnded

**Event Explanation:** Emitted when a contest ends and winners are determined.

**Parameters:**

```solidity
event ContestEnded(
    address indexed token,     // Address of the token for which the contest ended
    uint256 indexed contestId, // Unique identifier for the contest
    address[] winners          // Array of addresses that won the contest
);
```

**Signature:** `0xf48705a80b95c5d0b90c2bcc8882d845d83b5c7677a4c52e9a89c81d70a45aa1`

**Called By:** Internal contest ending logic, typically triggered by time or manual end function

### UniswapV3LPHook Contract

#### LiquidityCreated

**Event Explanation:** Emitted when liquidity is created in a Uniswap V3 pool.

**Parameters:**

```solidity
event LiquidityCreated(
    address indexed token,   // Address of the token
    address indexed pool,    // Address of the Uniswap V3 pool
    uint256 amount0,         // Amount of token0 added to the pool
    uint256 amount1,         // Amount of token1 added to the pool
    uint128 liquidity        // Amount of liquidity tokens minted
);
```

**Signature:** `0xd5a14d7a354eb68c3b3c9a315ef1ff9f2369b7d48c4b8669d0f58fb8686be840`

**Called By:** `createLiquidity` function

#### FeesCollected

**Event Explanation:** Emitted when fees are collected from a Uniswap V3 pool.

**Parameters:**

```solidity
event FeesCollected(
    address indexed token,   // Address of the token
    address indexed pool,    // Address of the Uniswap V3 pool
    uint256 amount0,         // Amount of token0 fees collected
    uint256 amount1          // Amount of token1 fees collected
);
```

**Signature:** `0x37a5be4e73b1c606ef99fa416b8adf8f588624b53a915a3e4dc92a17b7da0213`

**Called By:** `collectFees` function

### ReferralActionHook Contract

#### ReferralRecorded

**Event Explanation:** Emitted when a referral is recorded in the system.

**Parameters:**

```solidity
event ReferralRecorded(
    address indexed referrer,  // Address of the referrer
    address indexed buyer,     // Address of the buyer who was referred
    uint256 amount             // Amount of the transaction that triggered the referral
);
```

**Signature:** `0x12bf5155cc57be50f47ee64b3a2c971823b9cbdc3cd1ac5117e1ef9a424b4a39`

**Called By:** `postBuyHook` function

#### ReferralRewardPaid

**Event Explanation:** Emitted when a referral reward is paid to a referrer.

**Parameters:**

```solidity
event ReferralRewardPaid(
    address indexed referrer,  // Address of the referrer receiving the reward
    uint256 amount             // Amount of the reward paid
);
```

**Signature:** `0x4ed4ee9523d0cedacc24ec78b79574478d208f2a2f7a8e613572a5ffd6d8f912`

**Called By:** Internal reward distribution logic

### KOHCurveActionHook Contract

#### BuyRecorded

**Event Explanation:** Emitted when a token purchase is recorded for the King of the Hill contest.

**Parameters:**

```solidity
event BuyRecorded(
    address indexed buyer,   // Address of the buyer
    address indexed token,   // Address of the token being purchased
    uint256 amount           // Amount of tokens purchased
);
```

**Signature:** `0x6a1cdb55709cbdd3841e8ccb475be0b489f3a8d9f625b43f1d53b265f4d8e19b`

**Called By:** `postBuyHook` function

#### SellRecorded

**Event Explanation:** Emitted when a token sale is recorded for the King of the Hill contest.

**Parameters:**

```solidity
event SellRecorded(
    address indexed seller,  // Address of the seller
    address indexed token,   // Address of the token being sold
    uint256 amount           // Amount of tokens sold
);
```

**Signature:** `0x96dd44fc85b41a209c4c594f6a363b9867ca6e81b6b926527f4972c7a4bc9fda`

**Called By:** `postSellHook` function

### KOHContest Contract

#### TopThreeUpdated

**Event Explanation:** Emitted when the top three participants in a King of the Hill contest are updated.

**Parameters:**

```solidity
event TopThreeUpdated(
    address indexed token,     // Address of the token for which the contest is running
    address[3] topAddresses,   // Array of the top three addresses
    uint256[3] topAmounts      // Array of the corresponding amounts for each top address
);
```

**Signature:** `0x4adc59efaf9eb909c3b1e1a6bee30f5c89976a939c2b8e11d3c68bb4c3043ae0`

**Called By:** `_sortTopThree` function, triggered by `recordBuy` and `recordSell`

### TokenCommunityManager Contract

#### TokenCommunityLinked

**Event Explanation:** Emitted when a token is linked to a community namespace.

**Parameters:**

```solidity
event TokenCommunityLinked(
    address indexed token,      // Address of the token
    address indexed namespace,  // Address of the namespace contract
    string name                 // Name of the community
);
```

**Signature:** `0x5c3add02829de3863c98f3ba9a3fbce70aa0c779b04d0ce50c26164e32fbfd9f`

**Called By:** `executeLaunchAction` function

#### GovernorDeployed

**Event Explanation:** Emitted when a governance contract is deployed for a token community.

**Parameters:**

```solidity
event GovernorDeployed(
    address indexed token,     // Address of the token
    address indexed governor   // Address of the deployed governor contract
);
```

**Signature:** `0x68d226731ad1ca15dd89d10bafe344be6e827436439d392b1cbd48ca4af28abe`

**Called By:** Governance deployment function within `executeLaunchAction`

## 4. Contract Details/Architecture

### Launchpad.sol

**Purpose**: Main entry point for launching new tokenized communities with initial liquidity.

**Key Functions**:

* `launchTokenWithLiquidity`: Creates a new ERC20 token and establishes initial liquidity through the bonding curve.
* `_verifyHolderData`: Validates initial token holder data for token distribution during launch.
* `updateLaunchFeeAmount`: Allows the owner to update the fee required to launch a new token.

**Rules**:

* Launch fees must be paid in native currency (ETH/equivalent)
* Initial holders data must be validated before launch
* Token parameters must be properly configured for successful launch
* Only owner can update launch fee amounts

| Function Name              | Input Parameters                                                                                                                                          | Visibility         | Events It Triggers    |
| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | --------------------- |
| `launchTokenWithLiquidity` | `string memory _name, string memory _symbol, address[] memory _initialHolders, uint256[] memory _initialAmounts, uint256 _initialSupply, address _lpHook` | External (payable) | `TokenLaunched`       |
| `_verifyHolderData`        | `address[] memory _initialHolders, uint256[] memory _initialAmounts, uint256 _initialSupply`                                                              | Internal           | None                  |
| `updateLaunchFeeAmount`    | `uint256 _newFee`                                                                                                                                         | External           | `LaunchpadFeeUpdated` |
| `constructor`              | `address _bondingCurve, address _defaultLPHook, uint256 _launchFeeAmount, uint256 _protocolFee, address _protocolVault`                                   | Public             | `LaunchpadCreated`    |
| `receive`                  | None                                                                                                                                                      | External (payable) | None                  |

### LPBondingCurve.sol

**Purpose**: Manages the bonding curve economics for tokens, enabling price discovery based on supply and demand.

**Key Functions**:

* `registerToken`: Registers a new token with the bonding curve system.
* `buyToken`: Allows users to purchase tokens through the bonding curve mechanism.
* `sellToken`: Allows users to sell tokens back to the bonding curve.
* `getPrice`: Calculates the current token price based on the bonding curve formula.
* `transferLiquidity`: Transfers a portion of liquidity to external systems (e.g., AMM pools).

**Rules**:

* Bonding curve parameters are immutable after token creation
* Pricing follows the mathematical formula defined in the curve logic
* Protocol fees are applied to all buy/sell transactions
* Reentry protection is implemented for all critical functions

| Function Name             | Input Parameters                                                                                          | Visibility         | Events It Triggers     |
| ------------------------- | --------------------------------------------------------------------------------------------------------- | ------------------ | ---------------------- |
| `registerToken`           | `address _token, address _creator, uint256 _initialLiquidity, address _curveActionHook, uint256 _curveId` | External (payable) | `TokenRegistered`      |
| `buyToken`                | `address _token, uint256 _minReturn`                                                                      | Public (payable)   | `TokenPurchased`       |
| `_buyToken`               | `address _token, uint256 _minReturn, address _buyer`                                                      | Internal           | None                   |
| `sellToken`               | `address _token, uint256 _amount, uint256 _minReturn`                                                     | Public (payable)   | `TokenSold`            |
| `getPrice`                | `address _token`                                                                                          | External           | None                   |
| `_getPrice`               | `address _token, uint256 _supply`                                                                         | Internal           | None                   |
| `transferLiquidity`       | `address _token, uint256 _amount`                                                                         | External (payable) | `LiquidityTransferred` |
| `_getFloatingTokenSupply` | `address _token`                                                                                          | Public             | None                   |
| `_getTotalTokenSupply`    | `address _token`                                                                                          | Public             | None                   |
| `_isFunded`               | `address _token`                                                                                          | Public             | None                   |
| `_launchpadLiquidity`     | `address _token`                                                                                          | Public             | None                   |
| `_poolLiquidity`          | `address _token`                                                                                          | Public             | None                   |
| `_nonReentrantBefore`     | None                                                                                                      | Private            | `ReentryLock`          |
| `_nonReentrantAfter`      | None                                                                                                      | Private            | None                   |
| `constructor`             | `address _curveManager, uint256 _protocolFeePercent, address _protocolFeeDestination`                     | Public             | None                   |

### TokenCommunityManager.sol

**Purpose**: Manages the relationship between tokens and their associated community namespaces.

**Key Functions**:

* `executeLaunchAction`: Executes actions upon token launch, such as namespace linking.
* `namespaceForToken`: Retrieves the namespace associated with a token.
* `namespaceAddressForToken`: Gets the namespace contract address for a specific token.

**Rules**:

* Each token can be associated with one namespace
* Only authorized contracts can register token-namespace associations
* Governance parameters can be set for each token community

| Function Name              | Input Parameters                                              | Visibility | Events It Triggers                         |
| -------------------------- | ------------------------------------------------------------- | ---------- | ------------------------------------------ |
| `executeLaunchAction`      | `address _token, string memory _name, uint256 _initialSupply` | External   | `TokenCommunityLinked`, `GovernorDeployed` |
| `namespaceForToken`        | `address _token`                                              | External   | None                                       |
| `namespaceAddressForToken` | `address _token`                                              | External   | None                                       |
| `setLaunchpad`             | `address _launchpad`                                          | External   | None                                       |
| `setNamespaceFactory`      | `address _factory`                                            | External   | None                                       |
| `setDefaultQuorum`         | `uint256 _quorum`                                             | External   | None                                       |
| `setDefaultVoteDelay`      | `uint256 _delay`                                              | External   | None                                       |
| `setDefaultVotePeriod`     | `uint256 _period`                                             | External   | None                                       |
| `setPresetShares`          | `uint256[] memory _shares`                                    | External   | None                                       |
| `transferOwnership`        | `address _newOwner`                                           | External   | None                                       |
| `_stringToBytes32`         | `string memory _source`                                       | Internal   | None                                       |
| `constructor`              | `address _namespaceFactory, address _owner`                   | Public     | None                                       |

### LPContestManager.sol

**Purpose**: Manages contests for tokenized communities to drive engagement and participation.

**Key Functions**:

* `startContest`: Initializes a new contest for a token community.
* `setContestTime`: Configures the duration for contests.
* `setWinnerShares`: Sets the distribution of rewards among contest winners.

**Rules**:

* Contest rewards are distributed based on predefined shares
* Only token community admins can configure contests
* Contest timing and parameters must be set before contest start

| Function Name         | Input Parameters                                                                    | Visibility | Events It Triggers |
| --------------------- | ----------------------------------------------------------------------------------- | ---------- | ------------------ |
| `startContest`        | `address _token`                                                                    | External   | `ContestStarted`   |
| `setOwner`            | `address _newOwner`                                                                 | External   | None               |
| `setNamespaceFactory` | `address _factory`                                                                  | External   | None               |
| `setTokenManager`     | `address _manager`                                                                  | External   | None               |
| `setLpHook`           | `address _hook`                                                                     | External   | None               |
| `setContestTime`      | `uint256 _duration`                                                                 | External   | None               |
| `setWinnerShares`     | `uint256[] memory _shares`                                                          | External   | None               |
| `constructor`         | `address _owner, address _namespaceFactory, address _tokenManager, address _lpHook` | Public     | None               |

### LPCurveManager.sol

**Purpose**: Manages different bonding curve formulas and their parameters.

**Key Functions**:

* `calculatePurchaseReturn`: Calculates tokens received when purchasing with base currency.
* `calculateSaleReturn`: Calculates currency received when selling tokens.
* `isCurveValid`: Checks if a specific curve ID is valid and active.

**Rules**:

* Curve operations can be frozen by authorized managers
* Curve logic contracts implement the mathematical formulas
* Curves can be vetted to become immutable for security

| Function Name             | Input Parameters                                                                         | Visibility | Events It Triggers |
| ------------------------- | ---------------------------------------------------------------------------------------- | ---------- | ------------------ |
| `createCurve`             | `uint256 _curveId, address _logicContract`                                               | Public     | `CurveCreated`     |
| `updateCurve`             | `uint256 _curveId, bool _isVetted, bool _isFrozen, address _logicContract`               | Public     | `CurveUpdated`     |
| `freezeCurve`             | `uint256 _curveId, bool _isFrozen`                                                       | Public     | `CurveStopped`     |
| `calculatePurchaseReturn` | `uint256 _curveId, uint256 _supply, uint256 _amount, uint256 _decimals, uint256 _scalar` | External   | None               |
| `calculateSaleReturn`     | `uint256 _curveId, uint256 _supply, uint256 _amount, uint256 _decimals, uint256 _scalar` | External   | None               |
| `setCurveManager`         | `address _newCurveManager`                                                               | Public     | None               |
| `changeTradeManager`      | `address _newTradeManager`                                                               | Public     | None               |
| `isCurveValid`            | `uint256 _curveId`                                                                       | External   | None               |
| `constructor`             | None                                                                                     | Public     | None               |

### KOHContest.sol

**Purpose**: Implements "King of the Hill" style contests where users compete for positions based on token activity.

**Key Functions**:

* `recordBuy`: Records buying activity for contest ranking.
* `recordSell`: Records selling activity for contest ranking.
* `_sortTopThree`: Sorts contestants based on their activity levels.

**Rules**:

* Only authorized hooks can record buy/sell activities
* Contest rankings are updated in real-time based on token activity
* Contest periods have defined start and end times

| Function Name       | Input Parameters                                       | Visibility         | Events It Triggers |
| ------------------- | ------------------------------------------------------ | ------------------ | ------------------ |
| `recordBuy`         | `address _buyer, uint256 _amount`                      | External           | `TopThreeUpdated`  |
| `recordSell`        | `address _seller, uint256 _amount`                     | External           | `TopThreeUpdated`  |
| `_isInTopThree`     | `address _participant`                                 | Internal           | None               |
| `_sortTopThree`     | None                                                   | Internal           | `TopThreeUpdated`  |
| `_checkContestTime` | None                                                   | Internal           | None               |
| `_buyCurve`         | `address _participant, uint256 _amount`                | Internal           | None               |
| `_buyAMM`           | `address _participant, uint256 _amount`                | Internal           | None               |
| `receive`           | None                                                   | External (payable) | None               |
| `constructor`       | `address _token, address _bondingCurve, address _hook` | Public             | None               |

### CommonERC20.sol

**Purpose**: Implementation of the ERC20 token with additional governance capabilities.

**Key Functions**:

* Standard ERC20 functions
* Governance-related functions from ERC20Votes

**Rules**:

* Tokens support the EIP-2612 permit standard for gasless approvals
* Vote delegation and tracking for governance participation
* Fully compatible with the OpenZeppelin ERC20 standard

| Function Name   | Input Parameters                                                                        | Visibility | Events It Triggers                                 |
| --------------- | --------------------------------------------------------------------------------------- | ---------- | -------------------------------------------------- |
| `constructor`   | `string memory _name, string memory _symbol`                                            | Public     | None                                               |
| `nonces`        | `address _owner`                                                                        | Public     | None                                               |
| `_update`       | `address _from, address _to, uint256 _amount`                                           | Internal   | `DelegateVotesChanged`                             |
| `transfer`      | `address _to, uint256 _amount`                                                          | Public     | `Transfer`, possibly `DelegateVotesChanged`        |
| `transferFrom`  | `address _from, address _to, uint256 _amount`                                           | Public     | `Transfer`, possibly `DelegateVotesChanged`        |
| `approve`       | `address _spender, uint256 _amount`                                                     | Public     | `Approval`                                         |
| `delegate`      | `address _delegatee`                                                                    | Public     | `DelegateChanged`, possibly `DelegateVotesChanged` |
| `delegateBySig` | `address _delegatee, uint256 _nonce, uint256 _expiry, uint8 _v, bytes32 _r, bytes32 _s` | Public     | `DelegateChanged`, possibly `DelegateVotesChanged` |

### CommonGovernor.sol

**Purpose**: Governance system for token communities based on the Governor standard.

**Key Functions**:

* `propose`: Creates new governance proposals.
* `cancel`: Cancels existing proposals.
* `state`: Retrieves the current state of a proposal.

**Rules**:

* Governance voting follows the GovernorVotes standard
* Quorum requirements based on token supply
* Proposal lifecycle management with defined voting periods

| Function Name       | Input Parameters                                                                                             | Visibility | Events It Triggers |
| ------------------- | ------------------------------------------------------------------------------------------------------------ | ---------- | ------------------ |
| `votingDelay`       | None                                                                                                         | Public     | None               |
| `votingPeriod`      | None                                                                                                         | Public     | None               |
| `proposalThreshold` | None                                                                                                         | Public     | None               |
| `state`             | `uint256 _proposalId`                                                                                        | Public     | None               |
| `propose`           | `address[] memory _targets, uint256[] memory _values, bytes[] memory _calldatas, string memory _description` | Public     | `ProposalCreated`  |
| `cancel`            | `uint256 _proposalId`                                                                                        | Public     | `ProposalCanceled` |
| `supportsInterface` | `bytes4 _interfaceId`                                                                                        | Public     | None               |
| `constructor`       | `string memory _name, IVotes _token, uint256 _quorumNumerator`                                               | Public     | None               |
| `castVote`          | `uint256 _proposalId, uint8 _support`                                                                        | Public     | `VoteCast`         |
| `execute`           | `address[] memory _targets, uint256[] memory _values, bytes[] memory _calldatas, bytes32 _descriptionHash`   | Public     | `ProposalExecuted` |

### UniswapV3LPHook.sol

**Purpose**: Hook for creating and managing liquidity in Uniswap V3 pools.

**Key Functions**:

* `createLiquidity`: Creates liquidity in a Uniswap V3 pool.
* `collectFees`: Collects fees from Uniswap V3 positions.
* `_calculateSqrtPriceX96`: Calculates the sqrt price for Uniswap V3.

**Rules**:

* Interacts with Uniswap V3 protocol for liquidity management
* Manages position NFTs for liquidity tracking
* Enables fee collection from liquidity positions

| Function Name            | Input Parameters                                       | Visibility         | Events It Triggers |
| ------------------------ | ------------------------------------------------------ | ------------------ | ------------------ |
| `createLiquidity`        | `address _token, uint256 _amount`                      | External (payable) | `LiquidityCreated` |
| `onERC721Received`       | `address, address, uint256, bytes memory`              | External           | None               |
| `_calculateSqrtPriceX96` | `address _token, uint256 _price`                       | Internal           | None               |
| `collectFees`            | `address _token`                                       | External           | `FeesCollected`    |
| `_postLPactions`         | `address _token`                                       | Internal           | None               |
| `setContestManager`      | `address _manager`                                     | External           | None               |
| `updateTokenFee`         | `address _token, uint24 _fee`                          | External           | None               |
| `updateEthFee`           | `uint24 _fee`                                          | External           | None               |
| `constructor`            | `address _factory, address _swapRouter, address _weth` | Public             | None               |

### ReferralActionHook.sol

**Purpose**: Manages referrals and incentives for the platform.

**Key Functions**:

* `postBuyHook`: Actions executed after token purchases.
* `postSellHook`: Actions executed after token sales.
* `setReferralManager`: Sets the referral manager contract.

**Rules**:

* Only callable by the bonding curve contract
* Tracks referrals for reward distribution
* Maps referrals to namespaces

| Function Name            | Input Parameters                                                                         | Visibility | Events It Triggers |
| ------------------------ | ---------------------------------------------------------------------------------------- | ---------- | ------------------ |
| `postBuyHook`            | `address _buyer, address _token, uint256 _amountIn, uint256 _amountOut`                  | External   | `ReferralRecorded` |
| `postSellHook`           | `address _seller, address _token, uint256 _amountIn, uint256 _amountOut`                 | External   | None               |
| `setBondingCurveAddress` | `address _bondingCurve`                                                                  | External   | None               |
| `setTokenManager`        | `address _manager`                                                                       | External   | None               |
| `setReferralManager`     | `address _manager`                                                                       | External   | None               |
| `newOwner`               | `address _owner`                                                                         | External   | None               |
| `constructor`            | `address _owner, address _bondingCurve, address _tokenManager, address _referralManager` | Public     | None               |

## 5. User Flows

### Token Launch Flow

**What is Token Launch Flow?**\
The Token Launch Flow represents the end-to-end process of creating a new tokenized community using the Launchpad platform. This flow enables project creators to deploy their own ERC20 token with customizable parameters, establish initial liquidity through a bonding curve mechanism, and set up governance structures—all in a single transaction. This streamlined process eliminates the need for complex multi-step deployments that would typically require expertise in smart contract development.

During this flow, creators can define token parameters such as name and symbol, allocate initial token distribution among multiple addresses, set the initial supply, and select the appropriate liquidity model. The platform handles the complex interactions between the token contract, bonding curve, and associated namespace while ensuring proper security checks and protocol fee collection.

1. **Preparation**:
   * Creator prepares token parameters (name, symbol, initial supply)
   * Creator prepares initial holder data (if distributing to multiple addresses)
   * Creator selects bonding curve formula and parameters
2. **Launch Process**:
   * Creator calls `launchTokenWithLiquidity` on Launchpad contract
   * Pays required launch fee in native currency (0.000444 ETH)
   * Provides initial liquidity for the bonding curve
3. **Post-Launch**:
   * Token is registered with the bonding curve
   * Namespace is created and linked to the token
   * Initial governance parameters are set
   * Creator can configure additional features (contests, etc.)

**Flow Chart: Token Launch Flow**

```
┌─────────────────┐     ┌────────────────────┐     ┌────────────────────┐
│                 │     │                    │     │                    │
│  Preparation    │────▶│  Launch Process    │────▶│   Post-Launch      │
│                 │     │                    │     │                    │
└─────────────────┘     └────────────────────┘     └────────────────────┘
       │                         │                          │
       ▼                         ▼                          ▼
┌─────────────────┐     ┌────────────────────┐     ┌────────────────────┐
│ Define Token    │     │ Call launchToken   │     │ Token registered   │
│ Parameters      │     │ WithLiquidity      │     │ with bonding curve │
└─────────────────┘     └────────────────────┘     └────────────────────┘
       │                         │                          │
       ▼                         ▼                          ▼
┌─────────────────┐     ┌────────────────────┐     ┌────────────────────┐
│ Prepare Initial │     │ Pay launch fee     │     │ Namespace created  │
│ Holder Data     │     │ (0.000444 ETH)     │     │ and linked         │
└─────────────────┘     └────────────────────┘     └────────────────────┘
       │                         │                          │
       ▼                         ▼                          ▼
┌─────────────────┐     ┌────────────────────┐     ┌────────────────────┐
│ Select Bonding  │     │ Provide initial    │     │ Governance         │
│ Curve Parameters│     │ liquidity          │     │ parameters set     │
└─────────────────┘     └────────────────────┘     └────────────────────┘
                                                          │
                                                          ▼
                                                  ┌────────────────────┐
                                                  │ Configure          │
                                                  │ additional features│
                                                  └────────────────────┘
```

### Token Trading Flow

**What is Token Trading Flow?**\
The Token Trading Flow encompasses the mechanisms by which users can buy and sell tokens through the platform's bonding curve system. Unlike traditional exchanges with order books, the bonding curve mathematically determines token prices based on the current supply, creating a seamless, always-available trading mechanism. This approach ensures continuous liquidity and predictable price movements based on token supply changes.

The flow handles all aspects of token trading, including price calculation using the bonding curve formula, protocol fee management, token minting and burning, and integration with external hooks that enable additional functionality such as referral tracking and contest participation. All transactions are secured against reentrancy attacks and other potential vulnerabilities.

1. **Buying Tokens**:
   * User sends native currency to `buyToken` function
   * LPBondingCurve calculates token amount based on curve formula
   * Protocol fee (1%) is deducted and sent to protocol vault
   * Tokens are minted and sent to the buyer
   * Any post-buy hooks are executed (referrals, contests, etc.)
2. **Selling Tokens**:
   * User calls `sellToken` with desired token amount
   * LPBondingCurve calculates native currency return
   * Protocol fee (1%) is deducted and sent to protocol vault
   * Tokens are burned
   * Native currency is sent to the seller
   * Any post-sell hooks are executed

**Flow Chart: Token Trading Flow**

```
┌─────────────────────────┐                    ┌─────────────────────────┐
│                         │                    │                         │
│    Buying Tokens        │                    │    Selling Tokens       │
│                         │                    │                         │
└─────────────────────────┘                    └─────────────────────────┘
           │                                              │
           ▼                                              ▼
┌─────────────────────────┐                    ┌─────────────────────────┐
│ User sends ETH to       │                    │ User calls sellToken    │
│ buyToken function       │                    │ with amount             │
└─────────────────────────┘                    └─────────────────────────┘
           │                                              │
           ▼                                              ▼
┌─────────────────────────┐                    ┌─────────────────────────┐
│ Calculate tokens based  │                    │ Calculate ETH return    │
│ on bonding curve formula│                    │ based on curve formula  │
└─────────────────────────┘                    └─────────────────────────┘
           │                                              │
           ▼                                              ▼
┌─────────────────────────┐                    ┌─────────────────────────┐
│ Deduct protocol fee (1%)│                    │ Deduct protocol fee (1%)│
│ and send to vault       │                    │ and send to vault       │
└─────────────────────────┘                    └─────────────────────────┘
           │                                              │
           ▼                                              ▼
┌─────────────────────────┐                    ┌─────────────────────────┐
│ Mint tokens and send    │                    │ Burn tokens from        │
│ to buyer                │                    │ seller                  │
└─────────────────────────┘                    └─────────────────────────┘
           │                                              │
           ▼                                              ▼
┌─────────────────────────┐                    ┌─────────────────────────┐
│ Execute post-buy hooks  │                    │ Send ETH to seller      │
│ (referrals, contests)   │                    │                         │
└─────────────────────────┘                    └─────────────────────────┘
                                                          │
                                                          ▼
                                               ┌─────────────────────────┐
                                               │ Execute post-sell hooks │
                                               │ (contests, etc.)        │
                                               └─────────────────────────┘
```

### Community Governance Flow

**What is Community Governance Flow?**\
The Community Governance Flow provides token holders with decision-making power within their community through on-chain voting mechanisms. This flow leverages the OpenZeppelin Governor framework to enable decentralized governance where token holders can propose changes, vote on proposals, and automatically execute approved actions. The governance system uses token balances or delegated voting power to weight votes, ensuring that those with greater stake in the community have proportional influence.

The flow handles the entire lifecycle of governance proposals, including creation, voting periods, quorum requirements, execution of approved proposals, and the ability to cancel proposals under certain conditions. This enables communities to collectively manage protocol parameters, token economics, treasury funds, and other critical aspects of the project in a transparent and trustless manner.

1. **Proposal Creation**:
   * Token holder with sufficient voting power creates proposal
   * Proposal includes description, actions, and voting period
2. **Voting Process**:
   * Eligible token holders cast votes during voting period
   * Votes are weighted by token balance or delegated voting power
3. **Execution**:
   * If proposal reaches quorum and majority approval
   * Proposal actions are executed after timelock period (if applicable)
   * Results are recorded on-chain

**Flow Chart: Community Governance Flow**

```
┌─────────────────────┐       ┌─────────────────────┐       ┌─────────────────────┐
│                     │       │                     │       │                     │
│  Proposal Creation  │──────▶│   Voting Process    │──────▶│     Execution       │
│                     │       │                     │       │                     │
└─────────────────────┘       └─────────────────────┘       └─────────────────────┘
          │                            │                             │
          ▼                            ▼                             ▼
┌─────────────────────┐       ┌─────────────────────┐       ┌─────────────────────┐
│ Token holder with   │       │ Eligible holders    │       │ If quorum and       │
│ sufficient voting   │       │ cast votes during   │       │ majority approval   │
│ power creates       │       │ voting period       │       │ reached             │
└─────────────────────┘       └─────────────────────┘       └─────────────────────┘
          │                            │                             │
          ▼                            ▼                             ▼
┌─────────────────────┐       ┌─────────────────────┐       ┌─────────────────────┐
│ Define proposal     │       │ Votes weighted by   │       │ Wait for timelock   │
│ description and     │       │ token balance or    │       │ period (if any)     │
│ actions             │       │ delegated power     │       │                     │
└─────────────────────┘       └─────────────────────┘       └─────────────────────┘
          │                                                          │
          ▼                                                          ▼
┌─────────────────────┐                                    ┌─────────────────────┐
│ Set voting period   │                                    │ Execute proposal    │
│ parameters          │                                    │ actions on-chain    │
└─────────────────────┘                                    └─────────────────────┘
                                                                     │
                                                                     ▼
                                                          ┌─────────────────────┐
                                                          │ Record results      │
                                                          │ on-chain            │
                                                          └─────────────────────┘
```

### Contest Participation Flow

**What is Contest Participation Flow?**\
The Contest Participation Flow creates engagement mechanisms that incentivize community activity through competitive events with token rewards. Contests serve as powerful tools for driving user participation, increasing token velocity, and rewarding active community members. The platform supports various contest types, with "King of the Hill" (KOH) contests being a specialized format that ranks participants based on their trading activity.

This flow enables community administrators to configure contest parameters, tracks participant activity throughout the contest period, determines winners based on predefined criteria, and distributes rewards automatically. The entire process is managed on-chain, ensuring transparency and eliminating the need for manual reward distribution. Contests can be recurring or one-time events, offering flexibility to meet different community needs.

1. **Contest Setup**:
   * Community admin configures contest parameters
   * Sets reward distribution and timing
   * Initializes contest through LPContestManager
2. **Participation**:
   * Users participate through specified actions (buying/selling tokens, etc.)
   * Activities are recorded and ranked
   * For KOH contests, top positions are updated in real-time
3. **Rewards Distribution**:
   * At contest end, winners are determined by final rankings
   * Rewards are distributed according to predefined shares
   * Results are recorded for historical tracking

**Flow Chart: Contest Participation Flow**

```
┌─────────────────────┐       ┌─────────────────────┐       ┌─────────────────────┐
│                     │       │                     │       │                     │
│   Contest Setup     │──────▶│    Participation    │──────▶│ Rewards Distribution│
│                     │       │                     │       │                     │
└─────────────────────┘       └─────────────────────┘       └─────────────────────┘
          │                            │                             │
          ▼                            ▼                             ▼
┌─────────────────────┐       ┌─────────────────────┐       ┌─────────────────────┐
│ Admin configures    │       │ Users participate   │       │ At contest end,     │
│ contest parameters  │       │ through specified   │       │ determine winners   │
│                     │       │ actions             │       │ by final rankings   │
└─────────────────────┘       └─────────────────────┘       └─────────────────────┘
          │                            │                             │
          ▼                            ▼                             ▼
┌─────────────────────┐       ┌─────────────────────┐       ┌─────────────────────┐
│ Set reward          │       │ Activities recorded  │       │ Distribute rewards  │
│ distribution shares │       │ and ranked          │       │ according to        │
│                     │       │                     │       │ predefined shares   │
└─────────────────────┘       └─────────────────────┘       └─────────────────────┘
          │                            │                             │
          ▼                            ▼                             ▼
┌─────────────────────┐       ┌─────────────────────┐       ┌─────────────────────┐
│ Set contest timing  │       │ For KOH contests,   │       │ Record results for  │
│ parameters          │       │ top positions       │       │ historical tracking │
│                     │       │ updated in real-time│       │                     │
└─────────────────────┘       └─────────────────────┘       └─────────────────────┘
          │
          ▼
┌─────────────────────┐
│ Initialize contest  │
│ through LPContest   │
│ Manager             │
└─────────────────────┘
```
