Skip to content
Verified contractExactMIT

PlainLaunchToken

Address0x21d131914642363f0cdae09598be1dfd3145eced
Balance

0 ETH

 

Transactions

126

 

Compiler

solc 0.8.37

 

Same code

3 more contracts

 

Details

Compiler
solc 0.8.37+commit.f401782d
Language
solidity
Optimization
Yes, 1 runs
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,055,053
Creation transaction
0x7ea79f1a5e…0c073c731c

project/contracts/plain/PlainLaunchToken.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.37;

import {LaunchableTokenBase} from "../core/token/LaunchableTokenBase.sol";
import {CommonTokenParams} from "../core/interfaces/LaunchTypes.sol";

/// @title PlainLaunchToken
/// @notice Minimal launchable ERC20 without ABT.
contract PlainLaunchToken is LaunchableTokenBase {
    bytes32 public constant PROVIDER_ID = keccak256("PLAIN_ERC20_V1");

    string private _name;
    string private _symbol;
    uint8 private _decimals;

    constructor(address factory_) LaunchableTokenBase(factory_) {
        (CommonTokenParams memory common,) = _takeBootPayload();
        _name = common.name;
        _symbol = common.symbol;
        _decimals = common.decimals;
    }

    function providerId() external pure returns (bytes32) {
        return PROVIDER_ID;
    }

    function name() public view override returns (string memory) {
        return _name;
    }

    function symbol() public view override returns (string memory) {
        return _symbol;
    }

    function decimals() public view override returns (uint8) {
        return _decimals;
    }
}

npm/[email protected]/src/tokens/ERC20.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/// @notice Simple ERC20 + EIP-2612 implementation.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol)
///
/// @dev Note:
/// - The ERC20 standard allows minting and transferring to and from the zero address,
///   minting and transferring zero tokens, as well as self-approvals.
///   For performance, this implementation WILL NOT revert for such actions.
///   Please add any checks with overrides if desired.
/// - The `permit` function uses the ecrecover precompile (0x1).
///
/// If you are overriding:
/// - NEVER violate the ERC20 invariant:
///   the total sum of all balances must be equal to `totalSupply()`.
/// - Check that the overridden function is actually used in the function you want to
///   change the behavior of. Much of the code has been manually inlined for performance.
abstract contract ERC20 {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The total supply has overflowed.
    error TotalSupplyOverflow();

    /// @dev The allowance has overflowed.
    error AllowanceOverflow();

    /// @dev The allowance has underflowed.
    error AllowanceUnderflow();

    /// @dev Insufficient balance.
    error InsufficientBalance();

    /// @dev Insufficient allowance.
    error InsufficientAllowance();

    /// @dev The permit is invalid.
    error InvalidPermit();

    /// @dev The permit has expired.
    error PermitExpired();

    /// @dev The allowance of Permit2 is fixed at infinity.
    error Permit2AllowanceIsFixedAtInfinity();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           EVENTS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Emitted when `amount` tokens is transferred from `from` to `to`.
    event Transfer(address indexed from, address indexed to, uint256 amount);

    /// @dev Emitted when `amount` tokens is approved by `owner` to be used by `spender`.
    event Approval(address indexed owner, address indexed spender, uint256 amount);

    /// @dev `keccak256(bytes("Transfer(address,address,uint256)"))`.
    uint256 private constant _TRANSFER_EVENT_SIGNATURE =
        0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;

    /// @dev `keccak256(bytes("Approval(address,address,uint256)"))`.
    uint256 private constant _APPROVAL_EVENT_SIGNATURE =
        0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                          STORAGE                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The storage slot for the total supply.
    uint256 private constant _TOTAL_SUPPLY_SLOT = 0x05345cdf77eb68f44c;

    /// @dev The balance slot of `owner` is given by:
    /// ```
    ///     mstore(0x0c, _BALANCE_SLOT_SEED)
    ///     mstore(0x00, owner)
    ///     let balanceSlot := keccak256(0x0c, 0x20)
    /// ```
    uint256 private constant _BALANCE_SLOT_SEED = 0x87a211a2;

    /// @dev The allowance slot of (`owner`, `spender`) is given by:
    /// ```
    ///     mstore(0x20, spender)
    ///     mstore(0x0c, _ALLOWANCE_SLOT_SEED)
    ///     mstore(0x00, owner)
    ///     let allowanceSlot := keccak256(0x0c, 0x34)
    /// ```
    uint256 private constant _ALLOWANCE_SLOT_SEED = 0x7f5e9f20;

    /// @dev The nonce slot of `owner` is given by:
    /// ```
    ///     mstore(0x0c, _NONCES_SLOT_SEED)
    ///     mstore(0x00, owner)
    ///     let nonceSlot := keccak256(0x0c, 0x20)
    /// ```
    uint256 private constant _NONCES_SLOT_SEED = 0x38377508;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev `(_NONCES_SLOT_SEED << 16) | 0x1901`.
    uint256 private constant _NONCES_SLOT_SEED_WITH_SIGNATURE_PREFIX = 0x383775081901;

    /// @dev `keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")`.
    bytes32 private constant _DOMAIN_TYPEHASH =
        0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;

    /// @dev `keccak256("1")`.
    /// If you need to use a different version, override `_versionHash`.
    bytes32 private constant _DEFAULT_VERSION_HASH =
        0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6;

    /// @dev `keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")`.
    bytes32 private constant _PERMIT_TYPEHASH =
        0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;

    /// @dev The canonical Permit2 address.
    /// For signature-based allowance granting for single transaction ERC20 `transferFrom`.
    /// Enabled by default. To disable, override `_givePermit2InfiniteAllowance()`.
    /// [Github](https://github.com/Uniswap/permit2)
    /// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
    address internal constant _PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       ERC20 METADATA                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the name of the token.
    function name() public view virtual returns (string memory);

    /// @dev Returns the symbol of the token.
    function symbol() public view virtual returns (string memory);

    /// @dev Returns the decimals places of the token.
    function decimals() public view virtual returns (uint8) {
        return 18;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           ERC20                            */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the amount of tokens in existence.
    function totalSupply() public view virtual returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := sload(_TOTAL_SUPPLY_SLOT)
        }
    }

    /// @dev Returns the amount of tokens owned by `owner`.
    function balanceOf(address owner) public view virtual returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x0c, _BALANCE_SLOT_SEED)
            mstore(0x00, owner)
            result := sload(keccak256(0x0c, 0x20))
        }
    }

    /// @dev Returns the amount of tokens that `spender` can spend on behalf of `owner`.
    function allowance(address owner, address spender)
        public
        view
        virtual
        returns (uint256 result)
    {
        if (_givePermit2InfiniteAllowance()) {
            if (spender == _PERMIT2) return type(uint256).max;
        }
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x20, spender)
            mstore(0x0c, _ALLOWANCE_SLOT_SEED)
            mstore(0x00, owner)
            result := sload(keccak256(0x0c, 0x34))
        }
    }

    /// @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
    ///
    /// Emits a {Approval} event.
    function approve(address spender, uint256 amount) public virtual returns (bool) {
        if (_givePermit2InfiniteAllowance()) {
            /// @solidity memory-safe-assembly
            assembly {
                // If `spender == _PERMIT2 && amount != type(uint256).max`.
                if iszero(or(xor(shr(96, shl(96, spender)), _PERMIT2), iszero(not(amount)))) {
                    mstore(0x00, 0x3f68539a) // `Permit2AllowanceIsFixedAtInfinity()`.
                    revert(0x1c, 0x04)
                }
            }
        }
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the allowance slot and store the amount.
            mstore(0x20, spender)
            mstore(0x0c, _ALLOWANCE_SLOT_SEED)
            mstore(0x00, caller())
            sstore(keccak256(0x0c, 0x34), amount)
            // Emit the {Approval} event.
            mstore(0x00, amount)
            log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, caller(), shr(96, mload(0x2c)))
        }
        return true;
    }

    /// @dev Transfer `amount` tokens from the caller to `to`.
    ///
    /// Requirements:
    /// - `from` must at least have `amount`.
    ///
    /// Emits a {Transfer} event.
    function transfer(address to, uint256 amount) public virtual returns (bool) {
        _beforeTokenTransfer(msg.sender, to, amount);
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the balance slot and load its value.
            mstore(0x0c, _BALANCE_SLOT_SEED)
            mstore(0x00, caller())
            let fromBalanceSlot := keccak256(0x0c, 0x20)
            let fromBalance := sload(fromBalanceSlot)
            // Revert if insufficient balance.
            if gt(amount, fromBalance) {
                mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
                revert(0x1c, 0x04)
            }
            // Subtract and store the updated balance.
            sstore(fromBalanceSlot, sub(fromBalance, amount))
            // Compute the balance slot of `to`.
            mstore(0x00, to)
            let toBalanceSlot := keccak256(0x0c, 0x20)
            // Add and store the updated balance of `to`.
            // Will not overflow because the sum of all user balances
            // cannot exceed the maximum uint256 value.
            sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
            // Emit the {Transfer} event.
            mstore(0x20, amount)
            log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, caller(), shr(96, mload(0x0c)))
        }
        _afterTokenTransfer(msg.sender, to, amount);
        return true;
    }

    /// @dev Transfers `amount` tokens from `from` to `to`.
    ///
    /// Note: Does not update the allowance if it is the maximum uint256 value.
    ///
    /// Requirements:
    /// - `from` must at least have `amount`.
    /// - The caller must have at least `amount` of allowance to transfer the tokens of `from`.
    ///
    /// Emits a {Transfer} event.
    function transferFrom(address from, address to, uint256 amount) public virtual returns (bool) {
        _beforeTokenTransfer(from, to, amount);
        // Code duplication is for zero-cost abstraction if possible.
        if (_givePermit2InfiniteAllowance()) {
            /// @solidity memory-safe-assembly
            assembly {
                let from_ := shl(96, from)
                if iszero(eq(caller(), _PERMIT2)) {
                    // Compute the allowance slot and load its value.
                    mstore(0x20, caller())
                    mstore(0x0c, or(from_, _ALLOWANCE_SLOT_SEED))
                    let allowanceSlot := keccak256(0x0c, 0x34)
                    let allowance_ := sload(allowanceSlot)
                    // If the allowance is not the maximum uint256 value.
                    if not(allowance_) {
                        // Revert if the amount to be transferred exceeds the allowance.
                        if gt(amount, allowance_) {
                            mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
                            revert(0x1c, 0x04)
                        }
                        // Subtract and store the updated allowance.
                        sstore(allowanceSlot, sub(allowance_, amount))
                    }
                }
                // Compute the balance slot and load its value.
                mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
                let fromBalanceSlot := keccak256(0x0c, 0x20)
                let fromBalance := sload(fromBalanceSlot)
                // Revert if insufficient balance.
                if gt(amount, fromBalance) {
                    mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
                    revert(0x1c, 0x04)
                }
                // Subtract and store the updated balance.
                sstore(fromBalanceSlot, sub(fromBalance, amount))
                // Compute the balance slot of `to`.
                mstore(0x00, to)
                let toBalanceSlot := keccak256(0x0c, 0x20)
                // Add and store the updated balance of `to`.
                // Will not overflow because the sum of all user balances
                // cannot exceed the maximum uint256 value.
                sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
                // Emit the {Transfer} event.
                mstore(0x20, amount)
                log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
            }
        } else {
            /// @solidity memory-safe-assembly
            assembly {
                let from_ := shl(96, from)
                // Compute the allowance slot and load its value.
                mstore(0x20, caller())
                mstore(0x0c, or(from_, _ALLOWANCE_SLOT_SEED))
                let allowanceSlot := keccak256(0x0c, 0x34)
                let allowance_ := sload(allowanceSlot)
                // If the allowance is not the maximum uint256 value.
                if not(allowance_) {
                    // Revert if the amount to be transferred exceeds the allowance.
                    if gt(amount, allowance_) {
                        mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
                        revert(0x1c, 0x04)
                    }
                    // Subtract and store the updated allowance.
                    sstore(allowanceSlot, sub(allowance_, amount))
                }
                // Compute the balance slot and load its value.
                mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
                let fromBalanceSlot := keccak256(0x0c, 0x20)
                let fromBalance := sload(fromBalanceSlot)
                // Revert if insufficient balance.
                if gt(amount, fromBalance) {
                    mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
                    revert(0x1c, 0x04)
                }
                // Subtract and store the updated balance.
                sstore(fromBalanceSlot, sub(fromBalance, amount))
                // Compute the balance slot of `to`.
                mstore(0x00, to)
                let toBalanceSlot := keccak256(0x0c, 0x20)
                // Add and store the updated balance of `to`.
                // Will not overflow because the sum of all user balances
                // cannot exceed the maximum uint256 value.
                sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
                // Emit the {Transfer} event.
                mstore(0x20, amount)
                log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
            }
        }
        _afterTokenTransfer(from, to, amount);
        return true;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                          EIP-2612                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev For more performance, override to return the constant value
    /// of `keccak256(bytes(name()))` if `name()` will never change.
    function _constantNameHash() internal view virtual returns (bytes32 result) {}

    /// @dev If you need a different value, override this function.
    function _versionHash() internal view virtual returns (bytes32 result) {
        result = _DEFAULT_VERSION_HASH;
    }

    /// @dev For inheriting contracts to increment the nonce.
    function _incrementNonce(address owner) internal virtual {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x0c, _NONCES_SLOT_SEED)
            mstore(0x00, owner)
            let nonceSlot := keccak256(0x0c, 0x20)
            sstore(nonceSlot, add(1, sload(nonceSlot)))
        }
    }

    /// @dev Returns the current nonce for `owner`.
    /// This value is used to compute the signature for EIP-2612 permit.
    function nonces(address owner) public view virtual returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the nonce slot and load its value.
            mstore(0x0c, _NONCES_SLOT_SEED)
            mstore(0x00, owner)
            result := sload(keccak256(0x0c, 0x20))
        }
    }

    /// @dev Sets `value` as the allowance of `spender` over the tokens of `owner`,
    /// authorized by a signed approval by `owner`.
    ///
    /// Emits a {Approval} event.
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual {
        if (_givePermit2InfiniteAllowance()) {
            /// @solidity memory-safe-assembly
            assembly {
                // If `spender == _PERMIT2 && value != type(uint256).max`.
                if iszero(or(xor(shr(96, shl(96, spender)), _PERMIT2), iszero(not(value)))) {
                    mstore(0x00, 0x3f68539a) // `Permit2AllowanceIsFixedAtInfinity()`.
                    revert(0x1c, 0x04)
                }
            }
        }
        bytes32 nameHash = _constantNameHash();
        //  We simply calculate it on-the-fly to allow for cases where the `name` may change.
        if (nameHash == bytes32(0)) nameHash = keccak256(bytes(name()));
        bytes32 versionHash = _versionHash();
        /// @solidity memory-safe-assembly
        assembly {
            // Revert if the block timestamp is greater than `deadline`.
            if gt(timestamp(), deadline) {
                mstore(0x00, 0x1a15a3cc) // `PermitExpired()`.
                revert(0x1c, 0x04)
            }
            let m := mload(0x40) // Grab the free memory pointer.
            // Clean the upper 96 bits.
            owner := shr(96, shl(96, owner))
            spender := shr(96, shl(96, spender))
            // Compute the nonce slot and load its value.
            mstore(0x0e, _NONCES_SLOT_SEED_WITH_SIGNATURE_PREFIX)
            mstore(0x00, owner)
            let nonceSlot := keccak256(0x0c, 0x20)
            let nonceValue := sload(nonceSlot)
            // Prepare the domain separator.
            mstore(m, _DOMAIN_TYPEHASH)
            mstore(add(m, 0x20), nameHash)
            mstore(add(m, 0x40), versionHash)
            mstore(add(m, 0x60), chainid())
            mstore(add(m, 0x80), address())
            mstore(0x2e, keccak256(m, 0xa0))
            // Prepare the struct hash.
            mstore(m, _PERMIT_TYPEHASH)
            mstore(add(m, 0x20), owner)
            mstore(add(m, 0x40), spender)
            mstore(add(m, 0x60), value)
            mstore(add(m, 0x80), nonceValue)
            mstore(add(m, 0xa0), deadline)
            mstore(0x4e, keccak256(m, 0xc0))
            // Prepare the ecrecover calldata.
            mstore(0x00, keccak256(0x2c, 0x42))
            mstore(0x20, and(0xff, v))
            mstore(0x40, r)
            mstore(0x60, s)
            let t := staticcall(gas(), 1, 0x00, 0x80, 0x20, 0x20)
            // If the ecrecover fails, the returndatasize will be 0x00,
            // `owner` will be checked if it equals the hash at 0x00,
            // which evaluates to false (i.e. 0), and we will revert.
            // If the ecrecover succeeds, the returndatasize will be 0x20,
            // `owner` will be compared against the returned address at 0x20.
            if iszero(eq(mload(returndatasize()), owner)) {
                mstore(0x00, 0xddafbaef) // `InvalidPermit()`.
                revert(0x1c, 0x04)
            }
            // Increment and store the updated nonce.
            sstore(nonceSlot, add(nonceValue, t)) // `t` is 1 if ecrecover succeeds.
            // Compute the allowance slot and store the value.
            // The `owner` is already at slot 0x20.
            mstore(0x40, or(shl(160, _ALLOWANCE_SLOT_SEED), spender))
            sstore(keccak256(0x2c, 0x34), value)
            // Emit the {Approval} event.
            log3(add(m, 0x60), 0x20, _APPROVAL_EVENT_SIGNATURE, owner, spender)
            mstore(0x40, m) // Restore the free memory pointer.
            mstore(0x60, 0) // Restore the zero pointer.
        }
    }

    /// @dev Returns the EIP-712 domain separator for the EIP-2612 permit.
    function DOMAIN_SEPARATOR() public view virtual returns (bytes32 result) {
        bytes32 nameHash = _constantNameHash();
        //  We simply calculate it on-the-fly to allow for cases where the `name` may change.
        if (nameHash == bytes32(0)) nameHash = keccak256(bytes(name()));
        bytes32 versionHash = _versionHash();
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Grab the free memory pointer.
            mstore(m, _DOMAIN_TYPEHASH)
            mstore(add(m, 0x20), nameHash)
            mstore(add(m, 0x40), versionHash)
            mstore(add(m, 0x60), chainid())
            mstore(add(m, 0x80), address())
            result := keccak256(m, 0xa0)
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  INTERNAL MINT FUNCTIONS                   */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Mints `amount` tokens to `to`, increasing the total supply.
    ///
    /// Emits a {Transfer} event.
    function _mint(address to, uint256 amount) internal virtual {
        _beforeTokenTransfer(address(0), to, amount);
        /// @solidity memory-safe-assembly
        assembly {
            let totalSupplyBefore := sload(_TOTAL_SUPPLY_SLOT)
            let totalSupplyAfter := add(totalSupplyBefore, amount)
            // Revert if the total supply overflows.
            if lt(totalSupplyAfter, totalSupplyBefore) {
                mstore(0x00, 0xe5cfe957) // `TotalSupplyOverflow()`.
                revert(0x1c, 0x04)
            }
            // Store the updated total supply.
            sstore(_TOTAL_SUPPLY_SLOT, totalSupplyAfter)
            // Compute the balance slot and load its value.
            mstore(0x0c, _BALANCE_SLOT_SEED)
            mstore(0x00, to)
            let toBalanceSlot := keccak256(0x0c, 0x20)
            // Add and store the updated balance.
            sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
            // Emit the {Transfer} event.
            mstore(0x20, amount)
            log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, 0, shr(96, mload(0x0c)))
        }
        _afterTokenTransfer(address(0), to, amount);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  INTERNAL BURN FUNCTIONS                   */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Burns `amount` tokens from `from`, reducing the total supply.
    ///
    /// Emits a {Transfer} event.
    function _burn(address from, uint256 amount) internal virtual {
        _beforeTokenTransfer(from, address(0), amount);
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the balance slot and load its value.
            mstore(0x0c, _BALANCE_SLOT_SEED)
            mstore(0x00, from)
            let fromBalanceSlot := keccak256(0x0c, 0x20)
            let fromBalance := sload(fromBalanceSlot)
            // Revert if insufficient balance.
            if gt(amount, fromBalance) {
                mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
                revert(0x1c, 0x04)
            }
            // Subtract and store the updated balance.
            sstore(fromBalanceSlot, sub(fromBalance, amount))
            // Subtract and store the updated total supply.
            sstore(_TOTAL_SUPPLY_SLOT, sub(sload(_TOTAL_SUPPLY_SLOT), amount))
            // Emit the {Transfer} event.
            mstore(0x00, amount)
            log3(0x00, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, shl(96, from)), 0)
        }
        _afterTokenTransfer(from, address(0), amount);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                INTERNAL TRANSFER FUNCTIONS                 */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Moves `amount` of tokens from `from` to `to`.
    function _transfer(address from, address to, uint256 amount) internal virtual {
        _beforeTokenTransfer(from, to, amount);
        /// @solidity memory-safe-assembly
        assembly {
            let from_ := shl(96, from)
            // Compute the balance slot and load its value.
            mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
            let fromBalanceSlot := keccak256(0x0c, 0x20)
            let fromBalance := sload(fromBalanceSlot)
            // Revert if insufficient balance.
            if gt(amount, fromBalance) {
                mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
                revert(0x1c, 0x04)
            }
            // Subtract and store the updated balance.
            sstore(fromBalanceSlot, sub(fromBalance, amount))
            // Compute the balance slot of `to`.
            mstore(0x00, to)
            let toBalanceSlot := keccak256(0x0c, 0x20)
            // Add and store the updated balance of `to`.
            // Will not overflow because the sum of all user balances
            // cannot exceed the maximum uint256 value.
            sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
            // Emit the {Transfer} event.
            mstore(0x20, amount)
            log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
        }
        _afterTokenTransfer(from, to, amount);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                INTERNAL ALLOWANCE FUNCTIONS                */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Updates the allowance of `owner` for `spender` based on spent `amount`.
    function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
        if (_givePermit2InfiniteAllowance()) {
            if (spender == _PERMIT2) return; // Do nothing, as allowance is infinite.
        }
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the allowance slot and load its value.
            mstore(0x20, spender)
            mstore(0x0c, _ALLOWANCE_SLOT_SEED)
            mstore(0x00, owner)
            let allowanceSlot := keccak256(0x0c, 0x34)
            let allowance_ := sload(allowanceSlot)
            // If the allowance is not the maximum uint256 value.
            if not(allowance_) {
                // Revert if the amount to be transferred exceeds the allowance.
                if gt(amount, allowance_) {
                    mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
                    revert(0x1c, 0x04)
                }
                // Subtract and store the updated allowance.
                sstore(allowanceSlot, sub(allowance_, amount))
            }
        }
    }

    /// @dev Sets `amount` as the allowance of `spender` over the tokens of `owner`.
    ///
    /// Emits a {Approval} event.
    function _approve(address owner, address spender, uint256 amount) internal virtual {
        if (_givePermit2InfiniteAllowance()) {
            /// @solidity memory-safe-assembly
            assembly {
                // If `spender == _PERMIT2 && amount != type(uint256).max`.
                if iszero(or(xor(shr(96, shl(96, spender)), _PERMIT2), iszero(not(amount)))) {
                    mstore(0x00, 0x3f68539a) // `Permit2AllowanceIsFixedAtInfinity()`.
                    revert(0x1c, 0x04)
                }
            }
        }
        /// @solidity memory-safe-assembly
        assembly {
            let owner_ := shl(96, owner)
            // Compute the allowance slot and store the amount.
            mstore(0x20, spender)
            mstore(0x0c, or(owner_, _ALLOWANCE_SLOT_SEED))
            sstore(keccak256(0x0c, 0x34), amount)
            // Emit the {Approval} event.
            mstore(0x00, amount)
            log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, shr(96, owner_), shr(96, mload(0x2c)))
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                     HOOKS TO OVERRIDE                      */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Hook that is called before any transfer of tokens.
    /// This includes minting and burning.
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}

    /// @dev Hook that is called after any transfer of tokens.
    /// This includes minting and burning.
    function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                          PERMIT2                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns whether to fix the Permit2 contract's allowance at infinity.
    ///
    /// This value should be kept constant after contract initialization,
    /// or else the actual allowance values may not match with the {Approval} events.
    /// For best performance, return a compile-time constant for zero-cost abstraction.
    function _givePermit2InfiniteAllowance() internal view virtual returns (bool) {
        return true;
    }
}

project/contracts/core/interfaces/DeployContextKinds.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.37;

/// @notice Kind tags for TokenLaunchFactory deploy-context staging/consume.
library DeployContextKinds {
    bytes32 internal constant TOKEN = keccak256("TOKEN");
    bytes32 internal constant GRADUATION_POOL = keccak256("GRADUATION_POOL");
    bytes32 internal constant SVG_ART_ASSETS = keccak256("SVG_ART_ASSETS");
    bytes32 internal constant DATA_PAYLOAD_STORE = keccak256("DATA_PAYLOAD_STORE");
    bytes32 internal constant SVG_LAYER_REVEAL = keccak256("SVG_LAYER_REVEAL");
    bytes32 internal constant SVG_SEED_QUEUE = keccak256("SVG_SEED_QUEUE");
    bytes32 internal constant LAYER_ART_ASSETS = keccak256("LAYER_ART_ASSETS");
    bytes32 internal constant LAYER_REVEAL = keccak256("LAYER_REVEAL");
    bytes32 internal constant HOLDER_TAX_DISTRIBUTOR = keccak256("HOLDER_TAX_DISTRIBUTOR");
}

project/contracts/core/interfaces/ILaunchableERC20.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.37;

import {LaunchPhase, BuyerWhitelistMode, BuyerWhitelistDisableReason} from "./LaunchTypes.sol";

/// @title ILaunchableERC20
/// @notice Minimal API every launch ERC20 must expose to the factory and pools.
interface ILaunchableERC20 {
    /// @notice Emitted when the launch phase changes.
    event PhaseChanged(LaunchPhase oldPhase, LaunchPhase newPhase);

    /// @notice Emitted when a two-step ownership transfer starts.
    event OwnershipTransferStarted(address indexed currentOwner, address indexed pendingOwner);

    /// @notice Emitted when ownership transfer completes.
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /// @notice Emitted when the creator completes the mandatory initial buy at launch.
    event CreatorInitialBuy(address indexed buyer, uint256 quoteIn, uint256 tokensOut, uint256 taxQuote);

    /// @notice Returns the provider id that created this token.
    function providerId() external view returns (bytes32);

    /// @notice Current launch phase.
    function launchPhase() external view returns (LaunchPhase);

    /// @notice Bonding pool address in Graduating phase; otherwise zero.
    function bondingPool() external view returns (address);

    /// @notice Uniswap V4 PoolManager after bonding graduation.
    function tradingPool() external view returns (address);

    /// @notice Max tokens per buy (bonding + V4); zero in Created and before the fair-limit clock starts.
    function buyCap() external view returns (uint256);

    /// @notice Growing net-holdings cap per wallet; zero in Created and before the fair-limit clock starts.
    function walletCap() external view returns (uint256);

    /// @notice Launch creator address snapshotted at Graduating activation (before ownership renounce).
    function launchCreator() external view returns (address);

    /// @notice Baseline balance excluded from maxWallet (creator initial alloc at activation).
    function walletBaseline(address wallet) external view returns (uint256);

    /// @notice Net holdings counted toward maxWallet: max(0, balanceOf - walletBaseline).
    function effectiveHoldings(address wallet) external view returns (uint256);

    /// @notice Creator share of totalSupply in bps (0..100, max 1%).
    function creatorAllocBps() external view returns (uint256);

    /// @notice Max initial buy at launch (totalSupply * creatorAllocBps / 10000); not a free grant.
    function creatorAllocAmount() external view returns (uint256);

    /// @notice True while bonding buyer whitelist is enforced (Graduating, trading open, not disabled).
    function buyerWhitelistActive() external view returns (bool);

    /// @notice Buyer whitelist mode (Disabled until configured in Created phase).
    function buyerWhitelistMode() external view returns (BuyerWhitelistMode);

    /// @notice Whether `wallet` may buy from the bonding curve while whitelist is active.
    function isBuyerWhitelisted(address wallet) external view returns (bool);

    /// @notice Per-wallet alloc bps in Individual mode (0 in SharedPool mode).
    function buyerWhitelistAllocBps(address wallet) external view returns (uint256);

    /// @notice Cumulative tokens bought from bonding curve by `wallet` while whitelist was tracked.
    function buyerWhitelistBought(address wallet) external view returns (uint256);

    /// @notice Remaining whitelist cap for `wallet` (0 if not whitelisted).
    function buyerWhitelistRemaining(address wallet) external view returns (uint256);

    /// @notice Shared pool bps in SharedPool mode.
    function buyerWhitelistSharedPoolBps() external view returns (uint256);

    /// @notice Total tokens bought by all whitelisted wallets from bonding curve.
    function buyerWhitelistTotalBought() external view returns (uint256);

    /// @notice Number of whitelisted wallets.
    function buyerWhitelistWalletCount() external view returns (uint256);

    /// @notice WL-only bonding buy window after tradingStartsAt; 0 until first wallet or explicit set.
    /// @dev When whitelist is configured: 1..4320 minutes; default 60 on first addBuyerWhitelistWallet.
    function buyerWhitelistMinutes() external view returns (uint32);

    /// @notice Unix timestamp when the WL window ends; 0 before launch or when minutes unset.
    function buyerWhitelistUntil() external view returns (uint256);

    /// @notice Sets buyer whitelist mode (Created phase only).
    function setBuyerWhitelistMode(BuyerWhitelistMode mode) external;

    /// @notice Sets shared pool bps for SharedPool mode (Created phase only).
    function setBuyerWhitelistSharedPoolBps(uint256 sharedPoolBps) external;

    /// @notice Sets WL-only window length in minutes (Created phase only); 1..4320; 0 reverts.
    function setBuyerWhitelistMinutes(uint32 whitelistMinutes) external;

    /// @notice Adds a wallet to the buyer whitelist (Created phase only).
    /// @param allocBps Individual mode: 0 uses default 1%; SharedPool mode: must be 0.
    function addBuyerWhitelistWallet(address wallet, uint256 allocBps) external;

    /// @notice Batch add/update or remove buyer whitelist wallets (Created phase only).
    /// @param whitelisted true = add or update alloc; false = remove wallets.
    /// @param allocBps required when whitelisted; length must match wallets.
    function setBuyerWhitelistWallets(
        bool whitelisted,
        address[] calldata wallets,
        uint256[] calldata allocBps
    ) external;

    /// @notice Launch owner (creator) with transferable rights.
    function owner() external view returns (address);

    /// @notice Pending owner during two-step ownership transfer.
    function pendingOwner() external view returns (address);

    /// @notice Starts a two-step ownership transfer.
    function transferOwnership(address newOwner) external;

    /// @notice Accepts pending ownership.
    function acceptOwnership() external;

    /// @notice Called by the factory or graduation pool when trading moves to V4.
    /// @param tradingPool PoolManager address used to detect buy/sell.
    function onTradingStarted(address tradingPool) external;

    /// @notice Called by the factory in launch() to finalize provider content (SVG/data) before trading setup.
    /// @dev Plain tokens no-op. Content tokens lock their sidecar; incomplete upload reverts.
    function finalizeContent() external;

    /// @notice Activates Graduating phase and starts the max-buy clock after creator initial buy.
    function activateGraduatingPhase(uint256 tradingStartsAt) external;

    /// @notice Called by the factory at end of launch(); sets owner to address(0).
    /// @dev Callable by the factory regardless of the current token owner.
    function renounceOwnership() external;

    /// @notice Burns launch tokens held by the fee burn sink; reduces totalSupply.
    /// @dev Callable only by LaunchTaxHook or LaunchFeeBurnRouter.
    function burnFeeTokens(uint256 amount) external;

    /// @notice Burns unsold bonding excess on time-path graduation; reduces totalSupply.
    /// @dev Callable only by the graduation pool when `fixedSupply` is false.
    function burnBondingExcess(uint256 amount) external;
}

project/contracts/core/interfaces/ISystemConfig.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.37;

/// @title ISystemConfig
/// @notice Unified TokenGenerator protocol settings registry.
/// @dev Stores platform tax rates, V4 pool params, and infrastructure addresses (Uniswap V4, hook, factory).
///      Swap tax is immutable in the ctor (1..100 bps); change only via system redeploy.
///      Mutable fields are updated by the SystemConfig contract owner (onlyOwner).
interface ISystemConfig {
    /// @notice Emitted when the platform share of swap tax is updated.
    /// @param oldBps Previous value in basis points (1 bps = 0.01%).
    /// @param newBps New value in basis points.
    event SystemFeeShareBpsUpdated(uint256 oldBps, uint256 newBps);

    /// @notice Emitted when owner updates ERC20 quote allowlist entry.
    /// @param minTarget Per-quote floor in raw units when `allowed`; 0 when disabled.
    event QuoteTokenAllowedUpdated(address indexed quoteToken, bool allowed, uint256 minTarget);

    /// @notice Emitted when owner updates per-ERC20 minimum bondingQuoteTarget.
    event MinBondingQuoteTargetForQuoteUpdated(
        address indexed quoteToken, uint256 oldTarget, uint256 newTarget
    );

    /// @notice Emitted when owner irreversibly opens a launch type to all callers.
    event LaunchTypeOpened(bytes32 indexed launchTypeId);

    /// @notice Emitted when owner disables public launch for a type.
    event LaunchTypeClosed(bytes32 indexed launchTypeId);

    /// @notice Emitted when owner updates the bonding→LP token share used to derive virtualQuoteReserve.
    event GraduationLpBpsUpdated(uint256 oldBps, uint256 newBps);

    /// @notice Emitted when owner updates allowed time-graduation duration bounds for new launches.
    event GraduationDurationBoundsUpdated(uint32 oldMin, uint32 oldMax, uint32 newMin, uint32 newMax);

    /// @notice Emitted when owner updates the minimum bondingQuoteTarget for new launches.
    event MinBondingQuoteTargetUpdated(uint256 oldTarget, uint256 newTarget);

    /// @notice Emitted when the time-path collectedQuote floor (bps of quoteTarget) changes.
    event MinTimeGraduationCollectedQuoteBpsUpdated(uint256 oldBps, uint256 newBps);

    /// @notice Emitted when the protocol flushFeeBurn slippage floor changes.
    event FeeBurnMaxSlippageBpsUpdated(uint256 oldBps, uint256 newBps);

    /// @notice Emitted when owner updates max quote per permissionless flushFeeBurn (0 = unlimited).
    event MaxFeeBurnQuotePerFlushUpdated(uint256 oldCap, uint256 newCap);

    /// @notice Emitted when owner updates max royalty swap input per tx (0 = unlimited).
    event MaxRoyaltySwapInputPerTxUpdated(uint256 oldCap, uint256 newCap);
    event RoyaltySwapTokenAllowedUpdated(address indexed token, bool allowed);

    /// @notice Emitted when owner updates the SVG FIFO auto-drain batch size (instant + reveal).
    event SvgAdvanceBatchCapUpdated(uint256 oldCap, uint256 newCap);

    /// @notice Emitted when owner updates holder-tax period length for new HolderTaxDistributor deploys.
    event HolderTaxPeriodLengthSecondsUpdated(uint32 oldSeconds, uint32 newSeconds);

    /// @notice Emitted when owner updates the protocol launch fee (native ETH, charged in `launch()`).
    event LaunchFeeUpdated(uint256 feeWei);

    /// @notice Emitted when owner updates the default metadata base URI for layer kiosk collections.
    event KioskLayerMetadataBaseUriUpdated(string uri);

    /// @notice Reverts when kioskLayerMetadataBaseUri exceeds the max length.
    error MetadataBaseUriTooLong();

    /// @notice Emitted once when owner wires global ABT marketplace and offers venues.
    event AbtVenuesSet(address marketplace, address offers);

    /// @notice Emitted when owner updates ABT venue provider allowlist entry.
    event AbtVenueProviderSet(bytes32 indexed providerId, bool allowed);

    /// @notice Reverts when enablePublicLaunch is called for an already-public launch type.
    error LaunchTypeAlreadyPublic();

    /// @notice Reverts when disablePublicLaunch is called for a non-public launch type.
    error LaunchTypeNotPublic();

    /// @notice Reverts when caller is not allowed to launch the given type.
    error LaunchTypeRestricted();

    /// @notice Reverts when graduationLpBps is outside the allowed range.
    error InvalidGraduationLpBps();

    /// @notice Reverts when graduation duration bounds are invalid.
    error InvalidGraduationDurationBounds();

    /// @notice Reverts when minBondingQuoteTarget exceeds type(uint128).max.
    error InvalidMinBondingQuoteTarget();

    /// @notice Reverts when minTimeGraduationCollectedQuoteBps exceeds 10000.
    error InvalidMinTimeGraduationCollectedQuoteBps();

    /// @notice Reverts when feeBurnMaxSlippageBps exceeds 10000.
    error InvalidFeeBurnMaxSlippageBps();

    /// @notice Reverts when maxFeeBurnQuotePerFlush exceeds the protocol cap.
    error InvalidMaxFeeBurnQuotePerFlush();

    /// @notice Reverts when maxRoyaltySwapInputPerTx exceeds the protocol cap.
    error InvalidMaxRoyaltySwapInputPerTx();

    /// @notice Reverts when updating min for a quote token that is not allowlisted.
    error QuoteTokenNotAllowed();

    /// @notice Reverts when allowing a quote token that has no deployed bytecode.
    error QuoteTokenNotDeployed();

    /// @notice Reverts when v4TickSpacing is outside Uniswap v4 bounds (1..16384).
    error InvalidTickSpacing();

    /// @notice Reverts when svgAdvanceBatchCap is outside 1..100.
    error InvalidSvgAdvanceBatchCap();

    /// @notice Reverts when holderTaxPeriodLengthSeconds is outside protocol bounds.
    error InvalidHolderTaxPeriodLengthSeconds();

    /// @notice Reverts when abtVenueProviders batch arrays have mismatched lengths.
    error ArrayLengthMismatch();

    /// @notice Reverts when launch wiring (V4, hook, factory, registry) is incomplete.
    error IncompleteSystemWiring();

    /// @notice True when V4, hook, factory, and creator fee registry are wired.
    function isLaunchWiringComplete() external view returns (bool);

    /// @notice True when owner has enabled public launch for this type (may be disabled again).
    function isLaunchTypePublic(bytes32 launchTypeId) external view returns (bool);

    /// @notice Whether `account` may prepareLaunch / deployToken for `launchTypeId`.
    function canLaunchType(bytes32 launchTypeId, address account) external view returns (bool);

    /// @notice Reverts IncompleteSystemWiring or LaunchTypeRestricted.
    function assertCanLaunchType(bytes32 launchTypeId, address account) external view;

    /// @notice Reverts IncompleteSystemWiring when protocol wiring is incomplete.
    function assertLaunchWiring() external view;

    /// @notice Owner opens a launch type to all callers (requires wiring).
    function enablePublicLaunch(bytes32 launchTypeId) external;

    /// @notice Batch enablePublicLaunch.
    function enablePublicLaunches(bytes32[] calldata launchTypeIds) external;

    /// @notice Owner closes public launch for a type (existing launches unaffected).
    function disablePublicLaunch(bytes32 launchTypeId) external;

    /// @notice Batch disablePublicLaunch.
    function disablePublicLaunches(bytes32[] calldata launchTypeIds) external;

    /// @notice Swap tax on bonding and V4, in basis points (100 = 1%, immutable after deploy).
    function swapTaxBps() external view returns (uint256);

    /// @notice Default platform share of swap tax for new launches, in basis points (max 3000 = 30%).
    /// @dev Remainder (10000 - systemFeeShareBps) goes to the launch creator.
    ///      Snapshotted into LaunchInfo at prepareLaunch; per-token split via factory.systemFeeShareBpsOfToken.
    function systemFeeShareBps() external view returns (uint256);

    /// @notice Updates the default platform share for future launches.
    /// @param bps New platform share in basis points (max 3000); creator share = 10000 - bps.
    function setSystemFeeShareBps(uint256 bps) external;

    /// @notice Share of bonding tokens reserved for V4 LP at graduation, in bps (2100 ≈ 21% LP / 79% sold).
    /// @dev virtualQuoteReserve = bondingQuoteTarget * graduationLpBps / (10000 - graduationLpBps); snapshot at prepareLaunch.
    function graduationLpBps() external view returns (uint256);

    /// @notice Owner updates graduation LP share for new launches only.
    function setGraduationLpBps(uint256 bps) external;

    /// @notice Minimum allowed `graduationDurationSeconds` for new launches (0 = time-graduation off only).
    function minGraduationDurationSeconds() external view returns (uint32);

    /// @notice Maximum allowed `graduationDurationSeconds` for new launches.
    function maxGraduationDurationSeconds() external view returns (uint32);

    /// @notice Owner updates allowed time-graduation duration bounds for new launches only.
    function setGraduationDurationBounds(uint32 minSeconds, uint32 maxSeconds) external;

    /// @notice Holder-tax period length in seconds for new HolderTaxDistributor deploys (snapshotted in distributor ctor).
    function holderTaxPeriodLengthSeconds() external view returns (uint32);

    /// @notice Owner updates holder-tax period length for future distributor deploys only.
    function setHolderTaxPeriodLengthSeconds(uint32 seconds_) external;

    /// @notice Minimum `bondingQuoteTarget` for new ETH launches (raw quote units; 0 = product floor off).
    /// @dev Default at deploy is typically 1 ether; onlyOwner may change for new launches only.
    function minBondingQuoteTarget() external view returns (uint256);

    /// @notice Per-ERC20 minimum `bondingQuoteTarget` (raw quote units; 0 when not allowlisted).
    function minBondingQuoteTargetByQuote(address quoteToken) external view returns (uint256);

    /// @notice Minimum `bondingQuoteTarget` floor for a quote token (ETH uses global min).
    function minBondingQuoteTargetForQuote(address quoteToken) external view returns (uint256);

    /// @notice Owner updates minimum bondingQuoteTarget for new ETH launches only.
    /// @param target New floor in raw quote units (`<= type(uint128).max`; 0 disables product floor).
    function setMinBondingQuoteTarget(uint256 target) external;

    /// @notice Minimum collectedQuote on time-path graduation as bps of quoteTarget (100 = 1%; 0 = off).
    function minTimeGraduationCollectedQuoteBps() external view returns (uint256);

    /// @notice Owner updates time-path collectedQuote floor for new launches only.
    function setMinTimeGraduationCollectedQuoteBps(uint256 bps) external;

    /// @notice Max slippage on permissionless flushFeeBurn as bps (300 = 3%).
    function feeBurnMaxSlippageBps() external view returns (uint256);

    /// @notice Owner updates protocol flushFeeBurn slippage floor.
    function setFeeBurnMaxSlippageBps(uint256 bps) external;

    /// @notice Max quote amount per permissionless `flushFeeBurn` (0 = unlimited).
    function maxFeeBurnQuotePerFlush() external view returns (uint256);

    /// @notice Owner updates per-flush fee-burn quote cap.
    function setMaxFeeBurnQuotePerFlush(uint256 cap) external;

    /// @notice Max ERC-20 input per `KioskRoyaltySwapRouter.swapToEth` when router is wired to config (0 = unlimited).
    function maxRoyaltySwapInputPerTx() external view returns (uint256);

    /// @notice Owner updates royalty swap input cap.
    function setMaxRoyaltySwapInputPerTx(uint256 cap) external;

    /// @notice ERC-20 tokens that may use `KioskRoyaltySwapRouter` / `flushViaSwap` (kiosk royalty).
    function isRoyaltySwapTokenAllowed(address token) external view returns (bool);

    /// @notice Owner allowlists a royalty swap token (e.g. USDC, WETH).
    function setRoyaltySwapTokenAllowed(address token, bool allowed) external;

    /// @notice Protocol launch fee in wei (native ETH), read at each `TokenLaunchFactory.launch()`.
  /// @dev Default 0.0005 ETH at deploy; owner may change for future launches only. `0` disables the fee.
    function launchFeeWei() external view returns (uint256);

    /// @notice Owner updates the protocol launch fee for future `launch()` calls.
    function setLaunchFeeWei(uint256 feeWei) external;

    /// @notice Owner updates per-ERC20 minimum bondingQuoteTarget for new launches only.
    function setMinBondingQuoteTargetForQuote(address token, uint256 target) external;

    /// @notice Max successful SVG FIFO steps per `advanceQueue()` / trading transfer (instant seed + layer reveal).
    /// @dev Runtime; applies to all live queues. Default 20. `advanceQueue(maxCount)` is not clamped to this.
    function svgAdvanceBatchCap() external view returns (uint256);

    /// @notice Owner updates SVG FIFO auto-drain batch size (1..100) for all launches.
    function setSvgAdvanceBatchCap(uint256 cap) external;

    /// @notice Default HTTPS base for layer kiosk `tokenURI` when a collection has no per-launch override.
    function kioskLayerMetadataBaseUri() external view returns (string memory);

    /// @notice Owner updates the default layer kiosk metadata base URI.
    function setKioskLayerMetadataBaseUri(string calldata uri) external;

    /// @notice V4 pool tick spacing, as in Uniswap V4 PoolKey.tickSpacing (ctor: 1..16384).
    function v4TickSpacing() external view returns (int24);

    /// @notice Network Uniswap V4 PoolManager.
    function poolManager() external view returns (address);

    /// @notice Uniswap V4 PositionManager (mints LP NFT on migration).
    function positionManager() external view returns (address);

    /// @notice Permit2 — for token approvals when adding liquidity via PositionManager.
    function permit2() external view returns (address);

    /// @notice Uniswap Universal Router for quote→ETH tax swaps.
    function universalRouter() external view returns (address);

    /// @notice Singleton that swaps ETH→ERC20 quote for GraduationPool.buyWithEth.
    function quoteEthSwapper() external view returns (address);

    /// @notice Uniswap V4 Quoter for on-chain ETH→ERC20 quote estimates (`QuoteEthSwapper.quoteEthForQuoteOut`).
    function v4Quoter() external view returns (address);

    /// @notice Whether ERC20 quote token is allowed for new launches (ETH always allowed).
    function allowedQuoteTokens(address quoteToken) external view returns (bool);

    /// @notice Returns true for native ETH or allowed ERC20 quote tokens.
    function isQuoteTokenAllowed(address quoteToken) external view returns (bool);

    /// @notice Owner sets allowlist flags and per-token min floors for ERC20 quote tokens (batch).
    function setAllowedQuoteTokens(
        address[] calldata tokens, bool[] calldata allowed, uint256[] calldata minTargets
    ) external;

    /// @notice Owner sets allowlist flag and per-token min floor for a single ERC20 quote token.
    function setQuoteTokenAllowed(address token, bool allowed, uint256 minTarget) external;

    /// @notice One-time Universal Router address for tax swaps.
    function setUniversalRouter(address router_) external;

    /// @notice True when wired Universal Router uses hop-price field in V4 exact-in struct.
    function universalRouterHasHopPriceParam() external view returns (bool);

    /// @notice One-time hop-encoding flag after `setUniversalRouter`.
    function setUniversalRouterHopEncoding(bool hasHopPriceParam_) external;

    /// @notice One-time QuoteEthSwapper for bonding ETH→ERC20 quote buys.
    function setQuoteEthSwapper(address swapper_) external;

    /// @notice One-time LaunchFeeBurnRouter for post-graduation creator-fee burn.
    function setLaunchFeeBurnRouter(address router_) external;

    /// @notice One-time V4 Quoter for on-chain ETH→quote estimates.
    function setV4Quoter(address quoter_) external;

    /// @notice LaunchTaxHook singleton — collects swap tax on V4 after graduation.
    function launchTaxHook() external view returns (address);

    /// @notice Helper that migrates liquidity from GraduationPool into a V4 position (LP NFT is burned to the burn address).
    function v4LiquidityHelper() external view returns (address);

    /// @notice V4 quote→token swap helper for creator-fee burn after graduation.
    function launchFeeBurnRouter() external view returns (address);

    /// @notice TokenLaunchFactory — main launch factory; used by the helper and hook to resolve owners.
    function factory() external view returns (address);

    /// @notice Global AbtMarketplace singleton (one-time).
    function abtMarketplace() external view returns (address);

    /// @notice Global AbtOffers singleton (one-time).
    function abtOffers() external view returns (address);

    /// @notice One-time onlyOwner wiring of ABT marketplace and offers venues.
    function setAbtVenues(address marketplace_, address offers_) external;

    /// @notice True when `account` is an `AbtPosition` or `AbtOfferEscrow` of the wired venues.
    function isAbtEscrow(address account) external view returns (bool);

    /// @notice Whether an ERC20 provider id may list on AbtMarketplace / AbtOffers.
    function isAbtVenueProvider(bytes32 providerId) external view returns (bool);

    /// @notice Owner enables or disables an ABT provider id for marketplace/offers venues.
    function setAbtVenueProvider(bytes32 providerId, bool allowed) external;

    /// @notice Batch update of ABT venue provider allowlist.
    function setAbtVenueProviders(bytes32[] calldata providerIds, bool[] calldata allowed) external;
}

project/contracts/core/interfaces/ITokenLaunchFactory.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.37;

import {CommonTokenParams, CreatorFeeAllocation, LaunchInfo} from "./LaunchTypes.sol";

/// @title ITokenLaunchFactory
/// @notice Entry point for creating token launches with bonding graduation to V4.
interface ITokenLaunchFactory {
    /// @notice Emitted after prepareLaunch (token created, trading not open yet).
    event LaunchPrepared(
        uint256 indexed launchId,
        address indexed token,
        address indexed owner,
        bytes32 providerId,
        uint256 creatorAllocBps
    );

    /// @notice Emitted when trading opens (launch).
    event LaunchStarted(
        uint256 indexed launchId,
        address indexed token,
        address indexed owner,
        address graduationPool,
        uint256 tradingStartsAt
    );

    /// @notice Emitted when a launch graduates from the custom pool to V4.
    event Graduated(uint256 indexed launchId, address indexed token, address poolManager);

    /// @notice Emitted when protocol launch fee is collected in `launch()`.
    event LaunchFeePaid(uint256 indexed launchId, uint256 amount);

    /// @notice System configuration contract.
    function systemConfig() external view returns (address);

    /// @notice Tax collector address.
    function taxCollector() external view returns (address);

    /// @notice Creator fee recipient registry (swap tax / marketplace royalties).
    function creatorFeeRegistry() external view returns (address);

    /// @notice Total number of created launches.
    function totalLaunches() external view returns (uint256);

    /// @notice Launch controller for a token (who prepared / may call launch). Not the fee recipient.
    function ownerOfToken(address token) external view returns (address);

    /// @notice Creator fee recipient for a token (via CreatorFeeRegistry).
    function feeRecipientOfToken(address token) external view returns (address);

    /// @notice Returns the launch id for a token.
    function getLaunchId(address token) external view returns (uint256);

    /// @notice Returns launch info by id.
    function getLaunch(uint256 launchId) external view returns (LaunchInfo memory);

    /// @notice Platform share of swap tax snapshotted at prepareLaunch (0 if not a launch token).
    function systemFeeShareBpsOfToken(address token) external view returns (uint256);

    /// @notice Unix timestamp when trading opens for a token (0 before launch).
    function tradingStartsAtOfToken(address token) external view returns (uint256);

    /// @notice Seconds until trading opens (0 if already open or launch not called).
    function timeUntilTradingStart(uint256 launchId) external view returns (uint256);

    /// @notice Unix timestamp when time-graduation becomes eligible (0 = disabled or before launch).
    function graduationDeadlineAtOfToken(address token) external view returns (uint256);

    /// @notice Seconds until time-graduation deadline (0 if disabled, already passed, or graduated).
    function timeUntilGraduation(uint256 launchId) external view returns (uint256);

    /// @notice Immutable creator swap-tax share split snapshotted at prepareLaunch.
    function creatorFeeAllocationOfToken(address token) external view returns (CreatorFeeAllocation memory);

    /// @notice Per-launch holder tax distributor (address(0) when disabled).
    function holderTaxDistributorOfToken(address token) external view returns (address);

    /// @notice Bps of creator share routed to holder tax distributor (0 when disabled).
    function holderDistributorBpsOfToken(address token) external view returns (uint16);

    /// @notice Registers an ERC20 provider implementation.
    function registerProvider(bytes32 providerId, address provider) external;

    /// @notice Returns the address of a registered provider.
    function providers(bytes32 providerId) external view returns (address);

    /// @notice Sets CreatorFeeRegistry once after deploy.
    function setCreatorFeeRegistry(address registry) external;

    /// @notice Sets HolderTaxDistributorDeployer once after deploy.
    function setHolderTaxDistributorDeployer(address deployer) external;

    /// @notice Returns the configured holder tax distributor deployer.
    function holderTaxDistributorDeployer() external view returns (address);

    /// @notice Reverts when ERC20 quote token is not on SystemConfig allowlist.
    error QuoteTokenNotAllowed();

    /// @notice Reverts when `decimals` is outside 1..18.
    error InvalidDecimals();

    /// @notice Reverts when `totalSupply` is 0 or either `totalSupply` / `bondingQuoteTarget` exceeds `MAX_LAUNCH_AMOUNT`.
    error InvalidLaunchAmount();

    /// @notice Reverts when derived `virtualQuoteReserve` floors to 0 (bondingQuoteTarget too small for current graduationLpBps).
    error ZeroVirtualQuoteReserve();

    /// @notice Reverts when `bondingQuoteTarget` is below `SystemConfig.minBondingQuoteTargetForQuote(quoteToken)`.
    error BondingQuoteTargetTooLow();

    /// @notice Reverts when `graduationDurationSeconds` is outside SystemConfig bounds.
    error InvalidGraduationDuration();

    /// @notice Reverts when `fixedSupply` is false but time-graduation is disabled.
    error FixedSupplyRequiresTimeGraduation();

    /// @notice Reverts when `creatorFeeAllocation` does not sum to 10_000 bps.
    error InvalidCreatorFeeAllocation();

    /// @notice Reverts when `holderDistributorBps` exceeds `MAX_HOLDER_DISTRIBUTOR_BPS`.
    error InvalidHolderDistributorBps();

    /// @notice Reverts when creatorAllocBps exceeds maxBuy.startBps while fair maxBuy is ON.
    error CreatorAllocExceedsMaxBuy();

    /// @notice Reverts when holder tax is enabled for tokens with fewer than 4 decimals.
    error InvalidHolderTaxDecimals();

    /// @notice Reverts when holder distributor is requested but deployer is not configured.
    error HolderDistributorDeployerNotSet();

    /// @notice Step 1: deploy the token; swap tax is a protocol constant in SystemConfig.
    /// @param feeRecipient Creator fee recipient (`address(0)` → msg.sender). Stored in CreatorFeeRegistry.
    function prepareLaunch(
        bytes32 providerId,
        CommonTokenParams calldata params,
        bytes calldata providerParams,
        address feeRecipient
    ) external returns (uint256 launchId, address token);

    /// @notice Launch quote currency for a token (address(0) = ETH; 0 if not a launch token).
    function quoteTokenOfToken(address token) external view returns (address);

    /// @notice Step 2: starts the countdown to trading (0 = immediately). Finalizes content and renounces token Ownable.
    /// @dev Payable: `requiredLaunchEth(launchId)` minimum ETH (launch fee + optional creator initial buy for ETH quote).
    function launch(uint256 launchId, uint256 minutesUntilStart) external payable returns (address graduationPool);

    /// @notice One-step plain ERC20 launch: prepare + launch in a single tx (no content upload window).
    /// @dev Only `PLAIN_ERC20_V1`; content providers revert `LaunchRequiresContentStep`.
    function prepareAndLaunch(
        bytes32 providerId,
        CommonTokenParams calldata params,
        bytes calldata providerParams,
        address feeRecipient,
        uint256 minutesUntilStart
    ) external payable returns (uint256 launchId, address token, address graduationPool);

    /// @notice Reverts when `prepareAndLaunch` is called for a provider that needs a content step.
    error LaunchRequiresContentStep();

    /// @notice Gross quote (incl. tax) required for the creator initial buy at launch (0 if no alloc).
    function requiredCreatorInitialBuyQuote(uint256 launchId) external view returns (uint256);

    /// @notice Minimum native ETH for `launch()` (protocol fee + creator initial buy when ETH quote).
    /// @dev Non-view when ERC20 quote uses `quoteEthForQuoteOut` (v4 Quoter is not staticcall-safe).
    function requiredLaunchEth(uint256 launchId) external returns (uint256);

    /// @notice Reverts when `launch` is called without enough ETH for launch fee + creator initial buy.
    error InsufficientLaunchEth();
    error InsufficientLaunchQuote();

    /// @notice Called by the graduation pool after migrating to V4.
    function notifyBondingComplete(address token, address graduationPool) external;

    /// @notice Syncs the launch-controller registry with token ownership (callable only by the token, before renounce).
    function syncLaunchOwner(address token) external;

    /// @notice Emitted when a stuck/stale pending deploy context is cleared by the owner.
    event DeployContextCleared(bytes32 kind, address indexed clearedBy);

    /// @notice Stages ABI-encoded deploy payload for the next CREATE (one pending slot).
    /// @dev Only a registered IERC20Provider. `GRADUATION_POOL` is rejected here (factory stages it
    ///      internally in `launch`). Reverts if a context is already pending. Stale leftover contexts
    ///      are auto-cleared at the start of `prepareLaunch` / `launch`.
    function stageDeployContext(bytes32 kind, bytes calldata data) external;

    /// @notice Consumes the staged deploy payload from a contract constructor (`msg.sender.code.length == 0`).
    function consumeDeployContext(bytes32 kind) external returns (bytes memory data);

    /// @notice Owner escape hatch: clears a stuck pending deploy-context slot.
    function clearDeployContext() external;

    /// @notice Reverts when deploy context is staged while another is still pending.
    error DeployContextPending();

    /// @notice Reverts when staged kind/data is missing or kind mismatches on consume.
    error DeployContextKindMismatch();

    /// @notice Reverts when consume is called outside construction.
    error OnlyDuringConstruction();

    /// @notice Reverts when stage caller is not a registered provider, or when staging GRADUATION_POOL externally.
    error UnauthorizedDeployContextStager();

    /// @notice Reverts when staged kind is zero or data is empty.
    error InvalidDeployContext();

    /// @notice Reverts when resolving fee split for an address that is not a launch token.
    error UnknownLaunchToken();
}

project/contracts/core/interfaces/LaunchTypes.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.37;

/// @notice Shared launch configuration types for the token launch system.

enum LaunchPhase {
    Created,
    Graduating,
    Graduated
}

/// @notice Off-chain metadata links stored on-chain for the UI.
struct TokenMetadata {
    string description;
    string iconUri;
    string websiteUri;
    string telegramUri;
    string twitterUri;
}

/// @dev Denominator for fair-cap fractions of totalSupply (not 1e4-bps).
uint256 constant FAIR_LIMIT_PRECISION = 100_000;
/// @dev Fair-launch floor: 0.01% of totalSupply at T=0 (`startBps / FAIR_LIMIT_PRECISION`).
uint256 constant MIN_FAIR_CAP_START_BPS = 10;
/// @dev Fair-launch floor: 0.003%/s (`growthBpsPerSec / FAIR_LIMIT_PRECISION`).
uint256 constant MIN_FAIR_CAP_GROWTH_BPS_PER_SEC = 3;
/// @dev Fair-launch ceiling: 0.01%/s (`growthBpsPerSec / FAIR_LIMIT_PRECISION`).
uint256 constant MAX_FAIR_CAP_GROWTH_BPS_PER_SEC = 10;
/// @dev maxBuy ON ceiling at T=0: 0.5% of totalSupply.
uint256 constant MAX_MAX_BUY_START_BPS = 500;
/// @dev maxWallet ON ceiling at T=0: 0.5% of totalSupply.
uint256 constant MAX_MAX_WALLET_START_BPS = 500;
/// @dev OFF sentinel `startBps`: `startBps == FAIR_CAP_DISABLED_START_BPS && growthBpsPerSec == 0` disables a fair cap.
uint256 constant FAIR_CAP_DISABLED_START_BPS = FAIR_LIMIT_PRECISION;
/// @dev Alias for maxBuy OFF sentinel (same as `FAIR_CAP_DISABLED_START_BPS`).
uint256 constant MAX_BUY_DISABLED_START_BPS = FAIR_CAP_DISABLED_START_BPS;
/// @dev Alias for maxWallet OFF sentinel (same as `FAIR_CAP_DISABLED_START_BPS`).
uint256 constant MAX_WALLET_DISABLED_START_BPS = FAIR_CAP_DISABLED_START_BPS;

/// @notice Buyer whitelist mode for bonding-curve sniper protection.
enum BuyerWhitelistMode {
    Disabled,
    Individual,
    SharedPool
}

/// @notice Why the buyer whitelist was permanently disabled.
enum BuyerWhitelistDisableReason {
    Fulfilled,
    Graduation
}

/// @dev Default per-wallet alloc when `addBuyerWhitelistWallet` passes `allocBps = 0` (1% of supply).
uint256 constant DEFAULT_BUYER_WHITELIST_ALLOC_BPS = 100;
/// @dev Max per-wallet alloc in Individual mode (10% of supply).
uint256 constant MAX_BUYER_WHITELIST_ALLOC_BPS = 1_000;
/// @dev Max shared pool alloc in SharedPool mode (90% of supply).
uint256 constant MAX_BUYER_WHITELIST_SHARED_BPS = 9_000;
/// @dev Max whitelisted wallets per launch.
uint256 constant MAX_BUYER_WHITELIST_WALLETS = 200;
/// @dev Min WL-only bonding buy window after tradingStartsAt.
uint32 constant MIN_BUYER_WHITELIST_MINUTES = 1;
/// @dev Default WL-only bonding buy window when creator adds wallets without setting minutes.
uint32 constant DEFAULT_BUYER_WHITELIST_MINUTES = 60;
/// @dev Max WL-only bonding buy window after tradingStartsAt (72h).
uint32 constant MAX_BUYER_WHITELIST_MINUTES = 4_320;
/// @dev Absolute min guaranteed time-graduation window (21 minutes).
uint32 constant MIN_GRADUATION_DURATION_SECONDS = 21 minutes;
/// @dev Absolute max guaranteed time-graduation window (3 days).
uint32 constant MAX_GRADUATION_DURATION_SECONDS = 3 days;

/// @notice Growing max-buy parameters during bonding and after V4 graduation.
/// @dev Units are 1/FAIR_LIMIT_PRECISION of totalSupply (e.g. startBps=10 → 0.01% supply), not Uniswap-style 1e4 bps.
///      OFF: `startBps == FAIR_CAP_DISABLED_START_BPS` and `growthBpsPerSec == 0` → `buyCap == totalSupply`.
///      ON: `startBps` in [MIN_FAIR_CAP_START_BPS, MAX_MAX_BUY_START_BPS] and
///      `growthBpsPerSec` in [MIN_FAIR_CAP_GROWTH_BPS_PER_SEC, MAX_FAIR_CAP_GROWTH_BPS_PER_SEC].
///      Factory rejects any other pair (`InvalidMaxBuy`).
struct MaxBuyParams {
    uint256 startBps;
    uint256 growthBpsPerSec;
}

/// @notice Growing per-wallet net-holdings cap during bonding and after V4 graduation.
/// @dev Same units as `MaxBuyParams`. OFF sentinel identical. ON start max is 0.5% (see `MAX_MAX_WALLET_START_BPS`).
struct MaxWalletParams {
    uint256 startBps;
    uint256 growthBpsPerSec;
}

/// @dev Max bps of creator swap-tax share routed to HolderTaxDistributor (0 = disabled).
uint16 constant MAX_HOLDER_DISTRIBUTOR_BPS = 10_000;

/// @notice Immutable split of the launch creator's swap-tax share (not platform share).
/// @dev `devBps + burnBps` must equal 10_000. Burn share is used for quote buyback + token burn.
struct CreatorFeeAllocation {
    uint16 devBps;
    uint16 burnBps;
}

/// @notice Shared token parameters for every provider implementation.
/// @dev `maxBuy` / `maxWallet`: OFF `{FAIR_CAP_DISABLED_START_BPS, 0}` or ON fair-launch ranges.
struct CommonTokenParams {
    string name;
    string symbol;
    uint8 decimals;
    uint256 totalSupply;
    TokenMetadata metadata;
    MaxBuyParams maxBuy;
    MaxWalletParams maxWallet;
    address quoteToken;
    uint256 bondingQuoteTarget;
    /// @dev Guaranteed time-graduation window after tradingStartsAt; 0 = disabled.
    uint32 graduationDurationSeconds;
    uint256 creatorAllocBps;
    CreatorFeeAllocation creatorFeeAllocation;
    /// @dev Bps of creator swap-tax share routed to HolderTaxDistributor; 0 = disabled.
    uint16 holderDistributorBps;
    /// @dev true: time-path LP excess sent to `address(0)` (Solady-safe lock). false: `burnBondingExcess` at time-graduation.
    bool fixedSupply;
}

/// @notice Context passed to the ERC20 provider when deploying a token.
struct DeployContext {
    address owner;
    uint256 launchId;
    address graduationPool;
    address factory;
    CommonTokenParams common;
    bytes providerParams;
}

/// @notice Snapshot of a created launch returned by the factory.
struct LaunchInfo {
    address token;
    address graduationPool;
    address owner;
    bytes32 providerId;
    LaunchPhase phase;
    address quoteToken;
    uint256 bondingQuoteTarget;
    uint256 virtualQuoteReserve;
    uint256 virtualTokenReserveStart;
    uint256 virtualTokenPadding;
    uint256 tradingStartsAt;
    /// @dev Guaranteed time-graduation window after tradingStartsAt; 0 = disabled.
    uint32 graduationDurationSeconds;
    /// @dev Unix timestamp when time-graduation becomes eligible; 0 = disabled.
    uint256 graduationDeadlineAt;
    uint256 creatorAllocBps;
    uint256 systemFeeShareBps; // platform share of swap tax, snapshotted at prepareLaunch
    CreatorFeeAllocation creatorFeeAllocation;
    address holderTaxDistributor;
    uint16 holderDistributorBps;
    bool fixedSupply;
}

project/contracts/core/token/LaunchableTokenBase.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.37;

import {ERC20} from "solady/src/tokens/ERC20.sol";
import {LaunchPhase, CommonTokenParams, BuyerWhitelistMode} from "../interfaces/LaunchTypes.sol";
import {DeployContextKinds} from "../interfaces/DeployContextKinds.sol";
import {ILaunchableERC20} from "../interfaces/ILaunchableERC20.sol";
import {ITokenLaunchFactory} from "../interfaces/ITokenLaunchFactory.sol";
import {ISystemConfig} from "../interfaces/ISystemConfig.sol";
import {IAbtMarketplace} from "../../marketplace/IAbtMarketplace.sol";
import {IERC20ABT} from "../../svg/interfaces/IERC20ABT.sol";
import {LaunchBuyerWhitelist} from "./mixin/LaunchBuyerWhitelist.sol";

/// @title LaunchableTokenBase
/// @notice Base ERC20 with a launch phase, ownership transfer, and fair-launch anti-sniper limits.
abstract contract LaunchableTokenBase is ERC20, ILaunchableERC20, LaunchBuyerWhitelist {
    uint256 private constant BPS = 10_000;

    address internal _factory;
    address internal _v4LiquidityHelper;
    address internal _owner;
    address internal _pendingOwner;
    address internal _tradingPool;
    /// @dev PoolManager address known from fund/launch; used to block V4 before graduation.
    address internal _poolManagerAddr;
    address internal _abtMarketplaceAddr;
    uint256 internal _creatorAllocBps;
    uint256 internal _creatorAllocAmount;

    // Temporary boot payload for concrete token constructors (cleared by _takeBootPayload).
    CommonTokenParams private _bootCommon;
    bytes private _bootExtension;
    bool private _bootLive;

    error OnlyFactory();
    error OnlyFactoryOrPool();
    error OnlyGraduationPool();
    error ZeroAddress();
    error NotPendingOwner();
    /// @notice Token cannot touch PoolManager while still in Graduating (blocks competing V4 pools).
    error V4BeforeGraduation();
    error BootPayloadMissing();
    error OnlyFeeBurnSink();

    modifier onlyOwner() {
        require(msg.sender == _owner, "not owner");
        _;
    }

    modifier onlyFactoryOrPool() {
        if (msg.sender != _factory && msg.sender != _graduationPoolAddr) revert OnlyFactoryOrPool();
        _;
    }

    /// @dev Consumes TOKEN deploy context from factory; concrete tokens call `_takeBootPayload`.
    constructor(address factory_) {
        if (factory_ == address(0)) revert ZeroAddress();
        _factory = factory_;
        bytes memory data = ITokenLaunchFactory(factory_).consumeDeployContext(DeployContextKinds.TOKEN);
        (address owner_, CommonTokenParams memory params, bytes memory extension) =
            abi.decode(data, (address, CommonTokenParams, bytes));
        _owner = owner_;
        _creatorAllocBps = params.creatorAllocBps;
        _creatorAllocAmount = (params.totalSupply * params.creatorAllocBps) / BPS;
        _initFairLaunchLimits(params.maxBuy, params.maxWallet, params.totalSupply, address(0));
        _mint(address(this), params.totalSupply);
        _bootCommon = params;
        _bootExtension = extension;
        _bootLive = true;
    }

    /// @dev Child constructor reads and clears boot payload after base construction.
    function _takeBootPayload() internal returns (CommonTokenParams memory common, bytes memory extension) {
        if (!_bootLive) revert BootPayloadMissing();
        common = _bootCommon;
        extension = _bootExtension;
        delete _bootCommon;
        delete _bootExtension;
        _bootLive = false;
    }

    function launchPhase() external view returns (LaunchPhase) {
        return _launchPhase;
    }

    function bondingPool() external view returns (address) {
        return _graduationPoolAddr;
    }

    function tradingPool() external view returns (address) {
        return _tradingPool;
    }

    function buyCap() external view returns (uint256) {
        return _maxBuyLimit();
    }

    function walletCap() external view returns (uint256) {
        return _maxWalletLimit();
    }

    function launchCreator() external view returns (address) {
        return _launchCreator;
    }

    function walletBaseline(address wallet) external view returns (uint256) {
        return _walletBaseline[wallet];
    }

    function effectiveHoldings(address wallet) external view returns (uint256) {
        return _effectiveHoldings(wallet);
    }

    function creatorAllocBps() external view returns (uint256) {
        return _creatorAllocBps;
    }

    function creatorAllocAmount() external view returns (uint256) {
        return _creatorAllocAmount;
    }

    function buyerWhitelistActive() external view returns (bool) {
        return _buyerWhitelistActive();
    }

    function buyerWhitelistMode() external view returns (BuyerWhitelistMode) {
        return _buyerWhitelistMode;
    }

    function isBuyerWhitelisted(address wallet) external view returns (bool) {
        return _isBuyerWhitelisted[wallet];
    }

    function buyerWhitelistAllocBps(address wallet) external view returns (uint256) {
        return _buyerWhitelistAllocBps[wallet];
    }

    function buyerWhitelistBought(address wallet) external view returns (uint256) {
        return _buyerWhitelistBought[wallet];
    }

    function buyerWhitelistRemaining(address wallet) external view returns (uint256) {
        return _buyerWhitelistRemaining(wallet);
    }

    function buyerWhitelistSharedPoolBps() external view returns (uint256) {
        return _buyerWhitelistSharedPoolBps;
    }

    function buyerWhitelistTotalBought() external view returns (uint256) {
        return _buyerWhitelistTotalBought;
    }

    function buyerWhitelistWalletCount() external view returns (uint256) {
        return _buyerWhitelistWallets.length;
    }

    function buyerWhitelistMinutes() external view returns (uint32) {
        return _buyerWhitelistMinutes;
    }

    function buyerWhitelistUntil() external view returns (uint256) {
        return _buyerWhitelistUntil();
    }

    function setBuyerWhitelistMode(BuyerWhitelistMode mode) external {
        _setBuyerWhitelistMode(mode);
    }

    function setBuyerWhitelistSharedPoolBps(uint256 sharedPoolBps) external {
        _setBuyerWhitelistSharedPoolBps(sharedPoolBps);
    }

    function setBuyerWhitelistMinutes(uint32 whitelistMinutes) external {
        _setBuyerWhitelistMinutes(whitelistMinutes);
    }

    function addBuyerWhitelistWallet(address wallet, uint256 allocBps) external {
        _addBuyerWhitelistWallet(wallet, allocBps);
    }

    function setBuyerWhitelistWallets(
        bool whitelisted,
        address[] calldata wallets,
        uint256[] calldata allocBps
    ) external {
        _setBuyerWhitelistWallets(whitelisted, wallets, allocBps);
    }

    function owner() external view returns (address) {
        return _owner;
    }

    function pendingOwner() external view returns (address) {
        return _pendingOwner;
    }

    function transferOwnership(address newOwner) external onlyOwner {
        if (newOwner == address(0)) revert ZeroAddress();
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(_owner, newOwner);
    }

    function acceptOwnership() external virtual {
        if (msg.sender != _pendingOwner) revert NotPendingOwner();
        address old = _owner;
        _owner = _pendingOwner;
        _pendingOwner = address(0);
        emit OwnershipTransferred(old, _owner);
        ITokenLaunchFactory(_factory).syncLaunchOwner(address(this));
        _afterAcceptOwnership(old, _owner);
    }

    function _afterAcceptOwnership(address, address) internal virtual {}

    /// @inheritdoc ILaunchableERC20
    function finalizeContent() external {
        // only factory during launch()
        if (msg.sender != _factory) revert OnlyFactory();
        _finalizeContent();
    }

    /// @dev Content providers lock sidecars; plain tokens leave this empty.
    function _finalizeContent() internal virtual {}

    /// @inheritdoc ILaunchableERC20
    function renounceOwnership() external {
        // only factory at end of launch(); does not sync factory launcher mapping
        if (msg.sender != _factory) revert OnlyFactory();
        address old = _owner;
        _owner = address(0);
        _pendingOwner = address(0);
        emit OwnershipTransferred(old, address(0));
    }

    function burnFeeTokens(uint256 amount) external {
        ISystemConfig cfg = ISystemConfig(ITokenLaunchFactory(_factory).systemConfig());
        address hook = cfg.launchTaxHook();
        address router = cfg.launchFeeBurnRouter();
        if (msg.sender != hook && msg.sender != router) revert OnlyFeeBurnSink();
        _burn(msg.sender, amount);
    }

    function burnBondingExcess(uint256 amount) external {
        if (msg.sender != _graduationPoolAddr) revert OnlyGraduationPool();
        _burn(_graduationPoolAddr, amount);
    }

    /// @notice Sends tradable supply to the graduation pool (creator buys via factory initial buy).
    function fundBondingPool(
        address pool,
        uint256 /* tradingStartsAt_ */,
        address v4LiquidityHelper_,
        address poolManager_,
        address universalRouter_
    ) external {
        require(msg.sender == _factory, "only factory");
        if (poolManager_ == address(0)) revert ZeroAddress();
        if (universalRouter_ == address(0)) revert ZeroAddress();
        _v4LiquidityHelper = v4LiquidityHelper_;
        _poolManagerAddr = poolManager_;
        _graduationPoolAddr = pool;
        _universalRouter = universalRouter_;
        _abtMarketplaceAddr = ISystemConfig(ITokenLaunchFactory(_factory).systemConfig()).abtMarketplace();
        _transfer(address(this), pool, balanceOf(address(this)));
    }

    /// @inheritdoc ILaunchableERC20
    function activateGraduatingPhase(uint256 tradingStartsAt_) external {
        if (msg.sender != _factory) revert OnlyFactory();
        require(_launchPhase == LaunchPhase.Created, "bad phase");
        _requireBuyerWhitelistLaunchReady();
        _launchPhase = LaunchPhase.Graduating;
        _snapshotCreatorWalletBaseline(_owner);
        _startFairLimitClock(tradingStartsAt_);
        emit PhaseChanged(LaunchPhase.Created, LaunchPhase.Graduating);
    }

    function onTradingStarted(address poolManager_) external onlyFactoryOrPool {
        if (poolManager_ == address(0)) revert ZeroAddress();
        LaunchPhase old = _launchPhase;
        _tradingPool = poolManager_;
        _poolManagerAddr = poolManager_;
        _setTradingPoolAddr(poolManager_);
        require(_launchPhase == LaunchPhase.Graduating, "bad phase");
        _launchPhase = LaunchPhase.Graduated;
        _disableBuyerWhitelistOnGraduation();
        emit PhaseChanged(old, _launchPhase);
    }

    function _buyerWhitelistOwner() internal view override returns (address) {
        return _owner;
    }

    function _buyerWhitelistFactory() internal view override returns (address) {
        return _factory;
    }

    function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual override {
        _enforceNoV4BeforeGraduation(from, to);
        _enforceBuyerWhitelist(from, to, amount);
        _shrinkCreatorBaseline(from);
        _enforceFairLimits(from, to, amount);
        _onPoolTransfer(from, to, amount);
    }

    /// @dev Blocks seeding/swapping on any V4 pool before Graduated (Created + Graduating); helper migration settles exempt.
    function _enforceNoV4BeforeGraduation(address from, address to) internal view {
        if (_launchPhase == LaunchPhase.Graduated) return;
        if (_poolManagerAddr == address(0)) return;
        if (from != _poolManagerAddr && to != _poolManagerAddr) return;
        if (from == _v4LiquidityHelper || to == _v4LiquidityHelper) return;
        revert V4BeforeGraduation();
    }

    function _onPoolTransfer(address from, address to, uint256 amount) internal virtual {}

    function _extraEffectiveHoldings(address wallet) internal view returns (uint256) {
        if (_abtMarketplaceAddr == address(0)) return 0;
        (bool ok, bytes memory data) =
            address(this).staticcall(abi.encodeWithSelector(IERC20ABT.assetBackedTokenUnit.selector));
        if (!ok || data.length == 0) return 0;
        uint256 unit = abi.decode(data, (uint256));
        if (unit == 0) return 0;
        return IAbtMarketplace(_abtMarketplaceAddr).escrowedFungibleBalance(wallet, address(this));
    }

    function _effectiveHoldings(address wallet) internal view override returns (uint256) {
        return super._effectiveHoldings(wallet) + _extraEffectiveHoldings(wallet);
    }

    function _isExcludedFromWalletCap(address addr) internal view override returns (bool) {
        address holderTax = ITokenLaunchFactory(_factory).holderTaxDistributorOfToken(address(this));
        return _onlyExcludedFromAssetBackedTokens(addr)
            || addr == _universalRouter
            || addr == _launchTaxHookAddr()
            || (holderTax != address(0) && addr == holderTax);
    }

    function _isBuyerWhitelistTransferAllowed(address to) internal view override returns (bool) {
        if (to == address(0) || to == _graduationPoolAddr || to == _tradingPoolAddr) return true;
        return ISystemConfig(ITokenLaunchFactory(_factory).systemConfig()).isAbtEscrow(to);
    }

    function _launchTaxHookAddr() internal view returns (address) {
        return ISystemConfig(ITokenLaunchFactory(_factory).systemConfig()).launchTaxHook();
    }

    function _isBondingBuyWhitelistExempt(address to) internal view override returns (bool) {
        return to == _launchTaxHookAddr();
    }

    function _isBondingBuyMaxBuyExempt(address to) internal view override returns (bool) {
        return to == _launchTaxHookAddr();
    }

    function _walletBalance(address wallet) internal view override returns (uint256) {
        return balanceOf(wallet);
    }

    /// @dev Infra recipients for ABT mint/sync (pool, PM, helper, zero — not Universal Router).
    function _onlyExcludedFromAssetBackedTokens(address addr) internal view returns (bool) {
        return addr == address(0)
            || addr == _graduationPoolAddr
            || addr == _tradingPool
            || addr == _poolManagerAddr
            || addr == _v4LiquidityHelper;
    }
}

project/contracts/core/token/mixin/FairLaunchLimits.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.37;

import {
    FAIR_CAP_DISABLED_START_BPS,
    FAIR_LIMIT_PRECISION,
    LaunchPhase,
    MaxBuyParams,
    MaxWalletParams
} from "../../interfaces/LaunchTypes.sol";

/// @title FairLaunchLimits
/// @notice Growing maxBuy (per pool push) and maxWallet (net holdings) anti-sniper limits.
abstract contract FairLaunchLimits {
    LaunchPhase internal _launchPhase;
    MaxBuyParams internal _maxBuyParams;
    MaxWalletParams internal _maxWalletParams;
    uint256 internal _totalSupplyForLimit;
    uint256 internal _fairLimitStartTime;
    address internal _graduationPoolAddr;
    address internal _tradingPoolAddr;
    address internal _universalRouter;
    address internal _launchCreator;
    mapping(address => uint256) internal _walletBaseline;

    error MaxBuyExceeded();
    error MaxWalletExceeded();

    function _initFairLaunchLimits(
        MaxBuyParams memory maxBuy,
        MaxWalletParams memory maxWallet,
        uint256 totalSupply,
        address graduationPool
    ) internal {
        _maxBuyParams = maxBuy;
        _maxWalletParams = maxWallet;
        _totalSupplyForLimit = totalSupply;
        _graduationPoolAddr = graduationPool;
    }

    function _startFairLimitClock(uint256 tradingStartsAt_) internal {
        _fairLimitStartTime = tradingStartsAt_;
    }

    function _setTradingPoolAddr(address tradingPool_) internal {
        _tradingPoolAddr = tradingPool_;
    }

    function _snapshotCreatorWalletBaseline(address creator) internal {
        _launchCreator = creator;
        _walletBaseline[creator] = _walletBalance(creator);
    }

    function _growingCap(uint256 startBps, uint256 growthBpsPerSec) internal view returns (uint256) {
        if (_launchPhase == LaunchPhase.Created || _fairLimitStartTime == 0) return 0;
        uint256 elapsed = block.timestamp <= _fairLimitStartTime ? 0 : block.timestamp - _fairLimitStartTime;
        uint256 combined = startBps + elapsed * growthBpsPerSec;
        uint256 count = (_totalSupplyForLimit * combined) / FAIR_LIMIT_PRECISION;
        return count > _totalSupplyForLimit ? _totalSupplyForLimit : count;
    }

    function _maxBuyLimit() internal view returns (uint256) {
        return _growingCap(_maxBuyParams.startBps, _maxBuyParams.growthBpsPerSec);
    }

    function _maxWalletLimit() internal view returns (uint256) {
        return _growingCap(_maxWalletParams.startBps, _maxWalletParams.growthBpsPerSec);
    }

    function _effectiveHoldings(address wallet) internal view virtual returns (uint256) {
        uint256 bal = _walletBalance(wallet);
        uint256 baseline = _walletBaseline[wallet];
        return bal > baseline ? bal - baseline : 0;
    }

    function _shrinkCreatorBaseline(address from) internal {
        if (from != _launchCreator || _launchCreator == address(0)) return;
        uint256 baseline = _walletBaseline[from];
        uint256 newBal = _walletBalance(from);
        if (baseline > newBal) {
            _walletBaseline[from] = newBal;
        }
    }

    function _fairLimitsActive() internal view returns (bool) {
        return _launchPhase != LaunchPhase.Created && _fairLimitStartTime != 0 && block.timestamp >= _fairLimitStartTime;
    }

    /// @dev Protocol infra (e.g. LaunchTaxHook fee-burn sink) skips maxBuy on pool→recipient bonding buys.
    function _isBondingBuyMaxBuyExempt(address /*to*/) internal view virtual returns (bool) {
        return false;
    }

    function _enforceFairLimits(address from, address to, uint256 amount) internal virtual {
        if (!_fairLimitsActive() || to == address(0)) return;

        if (_maxBuyParams.startBps != FAIR_CAP_DISABLED_START_BPS || _maxBuyParams.growthBpsPerSec != 0) {
            bool bondingBuy = _launchPhase == LaunchPhase.Graduating && from == _graduationPoolAddr
                && msg.sender == _graduationPoolAddr;
            bool v4Buy = _tradingPoolAddr != address(0) && from == _tradingPoolAddr && msg.sender == _tradingPoolAddr;
            if (bondingBuy || v4Buy) {
                if (!(bondingBuy && _isBondingBuyMaxBuyExempt(to)) && amount > _maxBuyLimit()) revert MaxBuyExceeded();
            }
        }

        if (
            (_maxWalletParams.startBps != FAIR_CAP_DISABLED_START_BPS || _maxWalletParams.growthBpsPerSec != 0)
                && !_isExcludedFromWalletCap(to)
        ) {
            if (_effectiveHoldings(to) > _maxWalletLimit()) revert MaxWalletExceeded();
        }
    }

    function _isExcludedFromWalletCap(address addr) internal view virtual returns (bool) {
        return addr == address(0) || addr == _graduationPoolAddr || addr == _tradingPoolAddr;
    }

    function _walletBalance(address wallet) internal view virtual returns (uint256);
}

project/contracts/core/token/mixin/LaunchBuyerWhitelist.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.37;

import {
    BuyerWhitelistMode,
    DEFAULT_BUYER_WHITELIST_ALLOC_BPS,
    DEFAULT_BUYER_WHITELIST_MINUTES,
    BuyerWhitelistDisableReason,
    LaunchPhase,
    MAX_BUYER_WHITELIST_ALLOC_BPS,
    MAX_BUYER_WHITELIST_MINUTES,
    MAX_BUYER_WHITELIST_SHARED_BPS,
    MAX_BUYER_WHITELIST_WALLETS,
    MIN_BUYER_WHITELIST_MINUTES
} from "../../interfaces/LaunchTypes.sol";
import {FairLaunchLimits} from "./FairLaunchLimits.sol";

/// @title LaunchBuyerWhitelist
/// @notice Optional bonding-curve buyer allowlist with per-wallet or shared-pool supply caps.
abstract contract LaunchBuyerWhitelist is FairLaunchLimits {
    uint256 private constant BPS = 10_000;

    BuyerWhitelistMode internal _buyerWhitelistMode;
    uint32 internal _buyerWhitelistMinutes; // 0 = unset until first wallet or explicit set
    bool internal _buyerWhitelistDisabled;
    uint256 internal _buyerWhitelistSharedPoolBps;
    uint256 internal _buyerWhitelistTotalBought;
    uint256 internal _buyerWhitelistFulfilledCount;
    address[] internal _buyerWhitelistWallets;
    mapping(address => bool) internal _isBuyerWhitelisted;
    mapping(address => uint256) internal _buyerWhitelistAllocBps;
    mapping(address => uint256) internal _buyerWhitelistBought;
    mapping(address => bool) internal _buyerWhitelistCapReached;

    event BuyerWhitelistModeSet(BuyerWhitelistMode mode);
    event BuyerWhitelistMinutesSet(uint32 whitelistMinutes);
    event BuyerWhitelistSharedPoolBpsSet(uint256 sharedPoolBps);
    event BuyerWhitelistWalletAdded(address indexed wallet, uint256 allocBps);
    event BuyerWhitelistWalletRemoved(address indexed wallet);
    event BuyerWhitelistDisabled(BuyerWhitelistDisableReason reason);

    error BuyerNotWhitelisted();
    error WhitelistCapExceeded();
    error InvalidWhitelistConfig();
    error WhitelistNotConfigurable();
    error DuplicateWhitelistWallet();
    error WhitelistWalletNotFound();
    error ArrayLengthMismatch();
    error WhitelistWalletLimitExceeded();
    error BuyerWhitelistAlreadyDisabled();
    error WhitelistTransferLocked();

    function _buyerWhitelistOwner() internal view virtual returns (address);

    function _buyerWhitelistFactory() internal view virtual returns (address);

    function _requireBuyerWhitelistConfigurable() internal view {
        if (_launchPhase != LaunchPhase.Created) revert WhitelistNotConfigurable();
    }

    function _ensureBuyerWhitelistMinutes() internal {
        if (_buyerWhitelistMinutes != 0) return;
        if (_buyerWhitelistWallets.length == 0) return;
        _buyerWhitelistMinutes = DEFAULT_BUYER_WHITELIST_MINUTES;
        emit BuyerWhitelistMinutesSet(DEFAULT_BUYER_WHITELIST_MINUTES);
    }

    function _requireBuyerWhitelistLaunchReady() internal view {
        if (_buyerWhitelistMode == BuyerWhitelistMode.Disabled) return;
        if (_buyerWhitelistWallets.length == 0) return;
        if (_buyerWhitelistMinutes == 0) revert InvalidWhitelistConfig();
        if (_buyerWhitelistMode == BuyerWhitelistMode.SharedPool) {
            if (_buyerWhitelistSharedPoolBps == 0) revert InvalidWhitelistConfig();
        }
    }

    function _setBuyerWhitelistMode(BuyerWhitelistMode mode) internal {
        _requireBuyerWhitelistConfigurable();
        if (msg.sender != _buyerWhitelistOwner()) revert("not owner");
        if (uint8(mode) > uint8(BuyerWhitelistMode.SharedPool)) revert InvalidWhitelistConfig();
        _buyerWhitelistMode = mode;
        if (mode != BuyerWhitelistMode.Disabled) {
            _ensureBuyerWhitelistMinutes();
        }
        emit BuyerWhitelistModeSet(mode);
    }

    function _setBuyerWhitelistMinutes(uint32 whitelistMinutes) internal {
        _requireBuyerWhitelistConfigurable();
        if (msg.sender != _buyerWhitelistOwner()) revert("not owner");
        if (
            whitelistMinutes < MIN_BUYER_WHITELIST_MINUTES
                || whitelistMinutes > MAX_BUYER_WHITELIST_MINUTES
        ) {
            revert InvalidWhitelistConfig();
        }
        _buyerWhitelistMinutes = whitelistMinutes;
        emit BuyerWhitelistMinutesSet(whitelistMinutes);
    }

    function _setBuyerWhitelistSharedPoolBps(uint256 sharedPoolBps) internal {
        _requireBuyerWhitelistConfigurable();
        if (msg.sender != _buyerWhitelistOwner()) revert("not owner");
        if (sharedPoolBps == 0 || sharedPoolBps > MAX_BUYER_WHITELIST_SHARED_BPS) {
            revert InvalidWhitelistConfig();
        }
        _buyerWhitelistSharedPoolBps = sharedPoolBps;
        emit BuyerWhitelistSharedPoolBpsSet(sharedPoolBps);
    }

    function _addBuyerWhitelistWallet(address wallet, uint256 allocBps) internal {
        _requireBuyerWhitelistConfigurable();
        if (msg.sender != _buyerWhitelistOwner()) revert("not owner");
        if (wallet == address(0)) revert InvalidWhitelistConfig();
        if (_isBuyerWhitelisted[wallet]) revert DuplicateWhitelistWallet();
        if (_buyerWhitelistWallets.length >= MAX_BUYER_WHITELIST_WALLETS) {
            revert WhitelistWalletLimitExceeded();
        }

        uint256 alloc = allocBps;
        if (_buyerWhitelistMode == BuyerWhitelistMode.Individual) {
            if (alloc == 0) alloc = DEFAULT_BUYER_WHITELIST_ALLOC_BPS;
            if (alloc > MAX_BUYER_WHITELIST_ALLOC_BPS) revert InvalidWhitelistConfig();
        } else if (alloc != 0) {
            revert InvalidWhitelistConfig();
        }

        if (_buyerWhitelistMinutes == 0) {
            _buyerWhitelistMinutes = DEFAULT_BUYER_WHITELIST_MINUTES;
            emit BuyerWhitelistMinutesSet(DEFAULT_BUYER_WHITELIST_MINUTES);
        }

        _isBuyerWhitelisted[wallet] = true;
        _buyerWhitelistAllocBps[wallet] = alloc;
        _buyerWhitelistWallets.push(wallet);
        emit BuyerWhitelistWalletAdded(wallet, alloc);
    }

    function _setBuyerWhitelistWallets(bool whitelisted, address[] calldata wallets, uint256[] calldata allocBps)
        internal
    {
        _requireBuyerWhitelistConfigurable();
        if (msg.sender != _buyerWhitelistOwner()) revert("not owner");
        if (whitelisted) {
            if (wallets.length != allocBps.length) revert ArrayLengthMismatch();
            for (uint256 i = 0; i < wallets.length; ++i) {
                address wallet = wallets[i];
                if (wallet == address(0)) revert InvalidWhitelistConfig();
                if (_isBuyerWhitelisted[wallet]) {
                    _updateBuyerWhitelistAlloc(wallet, allocBps[i]);
                } else {
                    _addBuyerWhitelistWallet(wallet, allocBps[i]);
                }
            }
        } else {
            for (uint256 i = 0; i < wallets.length; ++i) {
                _removeBuyerWhitelistWallet(wallets[i]);
            }
        }
    }

    function _updateBuyerWhitelistAlloc(address wallet, uint256 allocBps) internal {
        uint256 alloc = allocBps;
        if (_buyerWhitelistMode == BuyerWhitelistMode.Individual) {
            if (alloc == 0) alloc = DEFAULT_BUYER_WHITELIST_ALLOC_BPS;
            if (alloc > MAX_BUYER_WHITELIST_ALLOC_BPS) revert InvalidWhitelistConfig();
        } else if (alloc != 0) {
            revert InvalidWhitelistConfig();
        }
        _buyerWhitelistAllocBps[wallet] = alloc;
        emit BuyerWhitelistWalletAdded(wallet, alloc);
    }

    function _removeBuyerWhitelistWallet(address wallet) internal {
        if (!_isBuyerWhitelisted[wallet]) revert WhitelistWalletNotFound();
        uint256 len = _buyerWhitelistWallets.length;
        for (uint256 i = 0; i < len; ++i) {
            if (_buyerWhitelistWallets[i] != wallet) continue;
            _buyerWhitelistWallets[i] = _buyerWhitelistWallets[len - 1];
            _buyerWhitelistWallets.pop();
            break;
        }
        delete _isBuyerWhitelisted[wallet];
        delete _buyerWhitelistAllocBps[wallet];
        delete _buyerWhitelistBought[wallet];
        delete _buyerWhitelistCapReached[wallet];
        emit BuyerWhitelistWalletRemoved(wallet);
    }

    function _buyerWhitelistActive() internal view returns (bool) {
        if (_buyerWhitelistDisabled) return false;
        if (_buyerWhitelistMode == BuyerWhitelistMode.Disabled) return false;
        if (_buyerWhitelistWallets.length == 0) return false;
        if (_buyerWhitelistMinutes == 0) return false;
        if (_launchPhase != LaunchPhase.Graduating) return false;
        if (_fairLimitStartTime == 0 || block.timestamp < _fairLimitStartTime) return false;
        if (block.timestamp >= _fairLimitStartTime + uint256(_buyerWhitelistMinutes) * 60) {
            return false;
        }
        return true;
    }

    function _buyerWhitelistUntil() internal view returns (uint256) {
        if (_buyerWhitelistMinutes == 0 || _fairLimitStartTime == 0) return 0;
        return _fairLimitStartTime + uint256(_buyerWhitelistMinutes) * 60;
    }

    function _buyerWhitelistCap(address wallet) internal view returns (uint256) {
        if (_buyerWhitelistMode == BuyerWhitelistMode.Individual) {
            return (_totalSupplyForLimit * _buyerWhitelistAllocBps[wallet]) / BPS;
        }
        uint256 count = _buyerWhitelistWallets.length;
        if (count == 0) return 0;
        uint256 sharedCap = _buyerWhitelistSharedCap();
        uint256 perWallet = sharedCap / count;
        if (_buyerWhitelistWallets[count - 1] == wallet) {
            return sharedCap - perWallet * (count - 1);
        }
        return perWallet;
    }

    function _buyerWhitelistSharedCap() internal view returns (uint256) {
        return (_totalSupplyForLimit * _buyerWhitelistSharedPoolBps) / BPS;
    }

    function _buyerWhitelistRemaining(address wallet) internal view returns (uint256) {
        if (!_isBuyerWhitelisted[wallet]) return 0;
        uint256 cap = _buyerWhitelistCap(wallet);
        uint256 bought = _buyerWhitelistBought[wallet];
        return cap > bought ? cap - bought : 0;
    }

    function _isBuyerWhitelistTransferAllowed(address to) internal view virtual returns (bool) {
        return to == address(0) || to == _graduationPoolAddr || to == _tradingPoolAddr;
    }

    /// @dev Protocol infra (e.g. LaunchTaxHook fee-burn sink) skips whitelist caps on pool→recipient bonding buys.
    function _isBondingBuyWhitelistExempt(address /*to*/) internal view virtual returns (bool) {
        return false;
    }

    function _enforceBuyerWhitelist(address from, address to, uint256 amount) internal {
        if (!_buyerWhitelistActive()) return;

        bool bondingBuy = from == _graduationPoolAddr && msg.sender == _graduationPoolAddr;
        if (bondingBuy) {
            if (to == address(0)) return;
            if (_isBondingBuyWhitelistExempt(to)) return;
            if (!_isBuyerWhitelisted[to]) revert BuyerNotWhitelisted();

            uint256 newBought = _buyerWhitelistBought[to] + amount;
            if (newBought > _buyerWhitelistCap(to)) revert WhitelistCapExceeded();

            _buyerWhitelistBought[to] = newBought;
            _buyerWhitelistTotalBought += amount;

            if (_buyerWhitelistMode == BuyerWhitelistMode.Individual) {
                if (!_buyerWhitelistCapReached[to] && newBought >= _buyerWhitelistCap(to)) {
                    _buyerWhitelistCapReached[to] = true;
                    _buyerWhitelistFulfilledCount++;
                    if (_buyerWhitelistFulfilledCount == _buyerWhitelistWallets.length) {
                        _disableBuyerWhitelist(BuyerWhitelistDisableReason.Fulfilled);
                    }
                }
            } else if (_buyerWhitelistTotalBought >= _buyerWhitelistSharedCap()) {
                _disableBuyerWhitelist(BuyerWhitelistDisableReason.Fulfilled);
            }
            return;
        }

        bool bondingSell = to == _graduationPoolAddr && msg.sender == _graduationPoolAddr;
        if (bondingSell) return;

        if (from != address(0) && _isBuyerWhitelisted[from] && _buyerWhitelistBought[from] > 0) {
            if (!_isBuyerWhitelistTransferAllowed(to)) revert WhitelistTransferLocked();
        }
    }

    function _disableBuyerWhitelist(BuyerWhitelistDisableReason reason) internal {
        if (_buyerWhitelistDisabled) revert BuyerWhitelistAlreadyDisabled();
        _buyerWhitelistDisabled = true;
        emit BuyerWhitelistDisabled(reason);
    }

    function _disableBuyerWhitelistOnGraduation() internal {
        if (_buyerWhitelistDisabled) return;
        if (_buyerWhitelistMode == BuyerWhitelistMode.Disabled) return;
        if (_buyerWhitelistWallets.length == 0) return;
        _buyerWhitelistDisabled = true;
        emit BuyerWhitelistDisabled(BuyerWhitelistDisableReason.Graduation);
    }
}

project/contracts/marketplace/IAbtMarketplace.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.37;

/// @dev Position does not exist.
uint8 constant STATUS_NOT_EXISTS = 0;
/// @dev Position is public and can become buyable when ABTs are transferred to escrow.
uint8 constant STATUS_OPEN = 1;
/// @dev Position was bought and ABTs await buyer withdrawal.
uint8 constant STATUS_COMPLETED = 2;

/// @notice Marketplace position data stored on-chain.
struct PositionData {
    address positionContract;
    address owner;
    address buyer;
    address token;
    address paymentToken;
    uint256 price;
    uint8 status;
    uint256 feeShare;
}

/// @notice Full position view returned by pagination/read helpers.
struct PositionView {
    uint256 positionId;
    address positionContract;
    address owner;
    address buyer;
    address token;
    address paymentToken;
    uint256 price;
    uint8 status;
    uint256 feeShare;
    uint256 assetCount;
    bool isReady;
    bytes32 contentHash;
}

/// @notice Listed collection with open positions (for frontend discovery).
struct ListedTokenView {
    address token;
    string name;
    string symbol;
    uint256 openPositionCount;
}

/// @title IAbtMarketplace
/// @notice Global P2P marketplace for launchable SVG ABT collections (ETH payment only).
interface IAbtMarketplace {
    error PositionNotExists();
    error NotOpen();
    error NotCompleted();
    error NotPositionOwner();
    error OnlyBuyer();
    error SellerCannotBuy();
    error PositionNotReady();
    error PriceMustBePositive();
    error InsufficientPayment();
    error FeeShareTooHigh();
    error InvalidPaymentToken();
    error PriceTooHigh();
    error AssetCountTooLow();
    /// @notice Buy expected escrow content hash does not match current tracked ABTs.
    error ContentHashMismatch();
    /// @notice `registerDepositedAssets` — asset is not held by the position escrow.
    error AssetNotInEscrow();
    error InvalidAssetDepositor();
    error TokenNotFromFactory();
    error TokenNotAbt();
    error InvalidFactory();
    error NoRefund();
    /// @notice `count` must be greater than zero.
    error ZeroCount();

    event PositionCreated(
        uint256 indexed positionId,
        address indexed owner,
        address indexed token,
        address positionContract,
        address paymentToken,
        uint256 price,
        uint256 feeShare
    );
    event PositionParamsSet(uint256 indexed positionId, address paymentToken, uint256 price);
    event PositionBought(uint256 indexed positionId, address indexed buyer);
    event AssetsClaimed(uint256 indexed positionId, address indexed buyer, uint256 count);
    event AssetsWithdrawn(uint256 indexed positionId, address indexed seller, uint256 count);
    event BuyerPositionFinalized(uint256 indexed positionId);
    event PositionDeleted(uint256 indexed positionId);
    event CompletedPositionDismissed(uint256 indexed positionId);
    event FeeShareUpdated(uint256 feeShare);
    event RefundClaimed(address indexed account, uint256 amount);
    event FeeDistributed(
        uint256 indexed positionId,
        address indexed creator,
        uint256 platformFee,
        uint256 creatorFee
    );

    function factory() external view returns (address);

    /// @notice TaxCollector that receives the platform share of marketplace fees (same as factory.taxCollector).
    function taxCollector() external view returns (address);

    /// @notice Alias of `taxCollector()` for existing UI that reads platform fee sink as feeAddress.
    function feeAddress() external view returns (address);

    /// @dev Monotonic counter; includes closed/deleted positions (tombstones).
    function positionsTotal() external view returns (uint256);

    /// @dev Count of OPEN positions only; decreases on buy/delete.
    function openTotal() external view returns (uint256);

    function listedTokensTotal() external view returns (uint256);

    function feeShare() external view returns (uint256);

    function feePrecision() external pure returns (uint256);

    function platformFeeShareBps() external pure returns (uint256);

    function pendingRefundOf(address account) external view returns (uint256);

    /// @dev After close/delete, entry remains with `status == STATUS_NOT_EXISTS` (tombstone).
    function getPosition(uint256 positionId) external view returns (PositionData memory);

    function getPositionView(uint256 positionId) external view returns (PositionView memory);

    function isPositionReady(uint256 positionId) external view returns (bool);

    /// @notice True for an `AbtPosition` deployed by this marketplace.
    function isPositionEscrow(address account) external view returns (bool);

    /// @notice Keccak256 of packed tracked ABT ids for the position escrow (sorted ascending).
    function escrowContentHash(uint256 positionId) external view returns (bytes32);

    /// @notice Seller of an OPEN marketplace listing for `assetId`, or `address(0)` if not listed.
    function listingOwnerOf(address token, uint256 assetId) external view returns (address);

    function getOpenPositionsByOwner(
        address owner,
        uint256 startIndex,
        uint256 count
    ) external view returns (PositionView[] memory positions, uint256 total);

    function getOpenPositionsByToken(
        address token,
        uint256 startIndex,
        uint256 count
    ) external view returns (PositionView[] memory positions, uint256 total);

    function getAllOpenPositions(
        uint256 startIndex,
        uint256 count
    ) external view returns (PositionView[] memory positions, uint256 total);

    function getCompletedPositions(
        address owner,
        uint256 startIndex,
        uint256 count
    ) external view returns (PositionView[] memory positions, uint256 total);

    function getPurchasedPositions(
        address buyer,
        uint256 startIndex,
        uint256 count
    ) external view returns (PositionView[] memory positions, uint256 total);

    function getListedTokens(
        uint256 startIndex,
        uint256 count
    ) external view returns (ListedTokenView[] memory tokens, uint256 total);

    /// @notice Create an OPEN position. `paymentToken` must be `address(0)` (ETH only).
    function createTrade(
        address token,
        address paymentToken,
        uint256 price
    ) external returns (uint256 positionId);

    /// @notice Update price / payment token. `paymentToken` must be `address(0)` (ETH only).
    function setPositionParams(uint256 positionId, address paymentToken, uint256 price) external;

    /// @notice Buy an OPEN position for ETH.
    /// @dev Reverts on low tracked count or when escrow content hash mismatches `expectedContentHash`.
    function buy(
        uint256 positionId,
        address expectedPaymentToken,
        uint256 maxPrice,
        uint256 expectedAssetCount,
        bytes32 expectedContentHash
    ) external payable;

    /// @notice Buy and claim all escrowed ABTs in one tx (large escrow may OOG).
    function buyAndClaimAll(
        uint256 positionId,
        address expectedPaymentToken,
        uint256 maxPrice,
        uint256 expectedAssetCount,
        bytes32 expectedContentHash
    ) external payable;

    function claimAssets(uint256 positionId, uint256 count) external;

    function claimAllAssets(uint256 positionId) external;

    /// @notice Seller withdraws up to `count` ABTs from an OPEN position (partial cancel).
    function withdrawAssets(uint256 positionId, uint256 count) external;

    /// @notice Seller pulls ABTs into an OPEN position via asset operator approval and tracks them.
    function depositAssets(uint256 positionId, uint256[] calldata assetIds) external;

    /// @notice Seller registers ABTs already pushed to the position escrow (tracked accounting).
    /// @dev Direct `transferAssetBackedToken(position, id)` without this call leaves an orphan (ignored on release).
    function registerDepositedAssets(uint256 positionId, uint256[] calldata assetIds) external;

    function deletePosition(uint256 positionId) external;

    function claimRefund() external;

    function setFeeShare(uint256 newFeeShare) external;

    /// @notice Sum of `token` ERC20 exposure on marketplace escrows for `owner` (OPEN seller pending+tracked, COMPLETED buyer unclaimed).
    function escrowedFungibleBalance(address owner, address token) external view returns (uint256);
}

project/contracts/svg/interfaces/IERC20ABT.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.37;

/// @title IERC20ABT
/// @notice Optional ABT support for launch ERC20s.
/// @dev Providers without ABT do not implement this interface.
/// New ABT ids are minted only on ERC20 transfer from the bonding pool or V4 trading pool.
interface IERC20ABT {
    /// @notice Emitted when a new ABT is minted.
    event AssetBackedTokenMinted(address indexed owner, uint256 indexed assetBackedTokenId, uint256 seed);

    /// @notice Emitted when an ABT is burned.
    event AssetBackedTokenBurned(address indexed owner, uint256 indexed assetBackedTokenId);

    /// @notice Emitted when an ABT is transferred between owners.
    event AssetBackedTokenTransferred(
        address indexed from,
        address indexed to,
        uint256 indexed assetBackedTokenId
    );

    /// @notice Caller is not the asset owner and not an approved asset operator.
    error NotAssetOperator();

    /// @notice Raw ERC20 amount that backs one ABT (`10**decimals` of the launch token).
    function assetBackedTokenUnit() external view returns (uint256);

    /// @notice Recommended UI batch size for pool-buy ABT mint / move / burn (not enforced on-chain).
    function MAX_ASSETS_PER_TX() external view returns (uint256);

    /// @notice Number of ABTs held by an address.
    function ownerAssetBackedTokenCount(address owner) external view returns (uint256);

    /// @notice ABT id by index for an owner.
    function ownerAssetBackedTokenId(address owner, uint256 index) external view returns (uint256);

    /// @notice Whether `owner` currently holds ABT `id` (O(1)).
    function isAssetOwner(address owner, uint256 id) external view returns (bool);

    /// @notice Packed appearance seed for ABT id.
    /// @dev Instant SVG may revert until materialize; reveal until full layer reveal.
    function assetBackedTokenSeed(uint256 assetBackedTokenId) external view returns (uint256);

    /// @notice Whether `operator` may transfer ABTs on behalf of `owner`.
    function isAssetOperator(address owner, address operator) external view returns (bool);

    /// @notice Approve or revoke `operator` for msg.sender's ABTs.
    function setAssetOperator(address operator, bool approved) external;

    /// @notice Transfers one ABT to another address (moves the backing tokens).
    function transferAssetBackedToken(address to, uint256 assetBackedTokenId) external;

    /// @notice Transfers one ABT from `from` when caller is `from` or an approved operator.
    function transferAssetBackedTokenFrom(address from, address to, uint256 assetBackedTokenId) external;

    /// @notice Burns excess ABTs for msg.sender (counts above balance / unit).
    function syncAssetBackedTokens() external;
}
Compiler settingsShow
{
  "viaIR": true,
  "libraries": {},
  "optimizer": {
    "runs": 1,
    "enabled": true
  },
  "remappings": [
    "npm/@openzeppelin/[email protected]/:@uniswap/v4-core/=npm/@uniswap/[email protected]/",
    "project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/",
    "project/:@openzeppelin/uniswap-hooks/=npm/@openzeppelin/[email protected]/",
    "project/:@tokensk/uniswap/=npm/@tokensk/uniswap@local/",
    "project/:@uniswap/v4-core/=npm/@uniswap/[email protected]/",
    "project/:solady/=npm/[email protected]/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.