Skip to content
Verified contractExactMIT

EthXDirectV3SingleRouter

Address0x5e9bd50a1abbe501ce0c85469cd720b925fbfd3c
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.37

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.37+commit.f401782d
Language
solidity
Optimization
Yes, 500 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,104,074
Creation transaction
0x433b312270…f913d17e13

EthXDirectV3Single.sol

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {EthXDirectToken,EthXDirectTokenDeployer} from "./EthXDirectToken.sol";

interface ISingleV3Vault { function depositFor(bytes32 identity,address source) external payable; }
interface ISingleV3WETH is IERC20 {
    function deposit() external payable;
    function withdraw(uint256 amount) external;
}
interface ISingleV3Pool { function slot0() external view returns(uint160,int24,uint16,uint16,uint16,uint8,bool); }
interface ISingleV3UniFactory { function getPool(address,address,uint24) external view returns(address); }
interface ISingleV3PositionManager {
    struct MintParams {
        address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper;
        uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min;
        address recipient; uint256 deadline;
    }
    function factory() external view returns(address);
    function createAndInitializePoolIfNecessary(address,address,uint24,uint160) external payable returns(address);
    function mint(MintParams calldata) external payable returns(uint256,uint128,uint256,uint256);
    function transferFrom(address,address,uint256) external;
}
interface ISingleV3SwapRouter {
    struct ExactInputSingleParams {
        address tokenIn; address tokenOut; uint24 fee; address recipient;
        uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96;
    }
    function exactInputSingle(ExactInputSingleParams calldata) external payable returns(uint256);
}
interface ISingleV3TaxRegistrar {
    function registerFromFactory(address token,bytes32 identity,uint16 taxBps) external;
}

/// @notice EthXPay direct V3 launch: token-only concentrated liquidity at ~1 ETH opening FDV.
/// @dev The creator ETH is an actual first swap, not paired liquidity. Initial dev buy is creator-tax exempt.
contract EthXDirectV3SingleFactory is ReentrancyGuard {
    uint256 public constant TOTAL_SUPPLY=1_000_000_000 ether;
    uint256 public constant START_FDV_ETH=1 ether;
    uint256 public constant MIN_DEV_BUY=0.001 ether;
    uint256 public constant MAX_DEV_BUY=0.1 ether;
    uint24 public constant POOL_FEE=3000;
    int24 public constant START_TICK_ABS=207240;
    int24 public constant TICK_MIN=-887220;
    int24 public constant TICK_MAX=887220;
    address public constant DEAD=0x000000000000000000000000000000000000dEaD;

    ISingleV3PositionManager public immutable positionManager;
    ISingleV3WETH public immutable weth;
    EthXDirectTokenDeployer public immutable tokenDeployer;
    address public immutable vault;
    address public immutable canonicalSwapRouter;
    address public immutable setupAdmin;
    address public taxRouter;
    bool public routerFinalized;

    struct Launch {
        address token; address pool; address launcher; bytes32 identity;
        string handle; string xUserId; uint16 taxBps;
        uint256 positionTokenId; uint256 devBuyEth; uint256 devTokens;
        uint256 initialLpTokens; uint64 launchedAt;
    }
    Launch[] private _launches;
    mapping(address=>uint256) public launchIndexPlusOne;

    event RouterFinalized(address indexed router);
    event V3SingleLaunched(
        uint256 indexed index,address indexed token,address indexed pool,address launcher,
        bytes32 identity,string handle,string xUserId,uint16 taxBps,uint256 positionTokenId,
        uint256 devBuyEth,uint256 devTokens,uint256 initialLpTokens,uint256 startFdvEth
    );

    constructor(address pm,address weth_,address deployer,address vault_,address swapRouter,address admin){
        require(pm!=address(0)&&weth_!=address(0)&&deployer!=address(0),"zero");
        require(vault_!=address(0)&&swapRouter!=address(0)&&admin!=address(0),"zero");
        positionManager=ISingleV3PositionManager(pm);weth=ISingleV3WETH(weth_);
        tokenDeployer=EthXDirectTokenDeployer(deployer);vault=vault_;
        canonicalSwapRouter=swapRouter;setupAdmin=admin;
    }
    function finalizeTaxRouter(address router_) external {
        require(msg.sender==setupAdmin&&!routerFinalized&&router_!=address(0),"finalize");
        taxRouter=router_;routerFinalized=true;emit RouterFinalized(router_);
    }
    function tokenCount() external view returns(uint256){return _launches.length;}
    function getLaunch(uint256 i) external view returns(Launch memory){return _launches[i];}
    function getLaunchByToken(address token) external view returns(Launch memory){
        uint256 p=launchIndexPlusOne[token];require(p>0,"unknown");return _launches[p-1];
    }
    function isAllowedTax(uint16 bps) public pure returns(bool){return bps<=500&&bps%100==0;}

    function launch(string calldata name_,string calldata symbol_,string calldata handle_,
        string calldata xUserId_,uint16 taxBps_)
        external payable nonReentrant returns(address token,address pool,uint256 positionTokenId)
    {
        require(routerFinalized,"router");
        require(msg.value>=MIN_DEV_BUY&&msg.value<=MAX_DEV_BUY,"dev buy");
        require(bytes(name_).length>0&&bytes(name_).length<=32,"name");
        require(bytes(symbol_).length>0&&bytes(symbol_).length<=10,"symbol");
        require(isAllowedTax(taxBps_),"tax");
        string memory handle=_normalizeHandle(handle_);
        string memory xUserId=_normalizeXUserId(xUserId_);
        bytes32 identity=keccak256(abi.encodePacked("x:",xUserId));

        bytes32 salt=keccak256(abi.encode(block.prevrandao,msg.sender,_launches.length,name_,symbol_,xUserId));
        token=tokenDeployer.deploy(salt,name_,symbol_,msg.sender,1);
        EthXDirectToken t=EthXDirectToken(token);
        address w=address(weth);
        address token0=token<w?token:w;
        address token1=token<w?w:token;
        bool tokenIs0=token0==token;
        int24 startTick=tokenIs0?-START_TICK_ABS:START_TICK_ABS;
        int24 tickLower=tokenIs0?startTick:TICK_MIN;
        int24 tickUpper=tokenIs0?TICK_MAX:startTick;
        uint160 sqrtPriceX96=TickMath.getSqrtPriceAtTick(startTick);

        address existing=ISingleV3UniFactory(positionManager.factory()).getPool(token0,token1,POOL_FEE);
        if(existing!=address(0)){
            (uint160 beforeSqrt,,,,,,)=ISingleV3Pool(existing).slot0();
            require(beforeSqrt==0||beforeSqrt==sqrtPriceX96,"V3 occupied");
        }
        pool=positionManager.createAndInitializePoolIfNecessary(token0,token1,POOL_FEE,sqrtPriceX96);
        (uint160 actual,,,,,,)=ISingleV3Pool(pool).slot0();
        require(actual==sqrtPriceX96,"V3 price");

        require(t.approve(address(positionManager),TOTAL_SUPPLY),"token approve");
        uint256 amount0=tokenIs0?TOTAL_SUPPLY:0;
        uint256 amount1=tokenIs0?0:TOTAL_SUPPLY;
        uint256 used0;uint256 used1;
        (positionTokenId,,used0,used1)=positionManager.mint(
            ISingleV3PositionManager.MintParams({
                token0:token0,token1:token1,fee:POOL_FEE,tickLower:tickLower,tickUpper:tickUpper,
                amount0Desired:amount0,amount1Desired:amount1,
                amount0Min:tokenIs0?TOTAL_SUPPLY*99/100:0,
                amount1Min:tokenIs0?0:TOTAL_SUPPLY*99/100,
                recipient:address(this),deadline:block.timestamp
            })
        );
        require(positionTokenId>0,"V3 mint");
        positionManager.transferFrom(address(this),DEAD,positionTokenId);
        uint256 initialLpTokens=tokenIs0?used0:used1;
        require(initialLpTokens>=TOTAL_SUPPLY*99/100&&initialLpTokens<=TOTAL_SUPPLY,"token LP");
        require((tokenIs0?used1:used0)==0,"ETH LP");

        // Atomic creator buy. It is a real swap through the new pool and intentionally happens
        // before creator-tax registration, so "0.1 ETH dev buy" behaves like an actual buy.
        weth.deposit{value:msg.value}();
        require(weth.approve(canonicalSwapRouter,0),"approve reset");
        require(weth.approve(canonicalSwapRouter,msg.value),"approve");
        uint256 devTokens=ISingleV3SwapRouter(canonicalSwapRouter).exactInputSingle(
            ISingleV3SwapRouter.ExactInputSingleParams({
                tokenIn:w,tokenOut:token,fee:POOL_FEE,recipient:msg.sender,
                amountIn:msg.value,amountOutMinimum:1,sqrtPriceLimitX96:0
            })
        );
        require(devTokens>0&&devTokens<=100_000_000 ether,"dev cap");

        address[] memory exempt=new address[](5);
        exempt[0]=pool;exempt[1]=vault;exempt[2]=taxRouter;
        exempt[3]=address(positionManager);exempt[4]=canonicalSwapRouter;
        t.activate(exempt);
        ISingleV3TaxRegistrar(taxRouter).registerFromFactory(token,identity,taxBps_);

        uint256 burnAmount=t.balanceOf(address(this));
        if(burnAmount>0)require(t.transfer(DEAD,burnAmount),"burn dust");

        _launches.push(Launch(
            token,pool,msg.sender,identity,handle,xUserId,taxBps_,
            positionTokenId,msg.value,devTokens,initialLpTokens,uint64(block.timestamp)
        ));
        launchIndexPlusOne[token]=_launches.length;
        emit V3SingleLaunched(
            _launches.length-1,token,pool,msg.sender,identity,handle,xUserId,taxBps_,
            positionTokenId,msg.value,devTokens,initialLpTokens,START_FDV_ETH
        );
    }

    function _normalizeHandle(string memory raw) internal pure returns(string memory){
        bytes memory b=bytes(raw);require(b.length>=2&&b.length<=16&&b[0]==0x40,"handle");
        for(uint256 i=1;i<b.length;i++){uint8 c=uint8(b[i]);if(c>=65&&c<=90){b[i]=bytes1(c+32);continue;}require((c>=97&&c<=122)||(c>=48&&c<=57)||c==95,"handle chars");}
        return string(b);
    }
    function _normalizeXUserId(string memory raw) internal pure returns(string memory){
        bytes memory b=bytes(raw);require(b.length>=1&&b.length<=32,"x id");
        for(uint256 i=0;i<b.length;i++){uint8 c=uint8(b[i]);require(c>=48&&c<=57,"x chars");}
        return string(b);
    }
    receive() external payable {}
}

/// @notice Taxed V3 router for post-launch trades. Initial atomic dev buy bypasses this router.
contract EthXDirectV3SingleRouter is ReentrancyGuard {
    uint16 public constant BPS=10_000;
    uint24 public constant POOL_FEE=3000;
    ISingleV3SwapRouter public immutable router;
    ISingleV3WETH public immutable weth;
    ISingleV3Vault public immutable vault;
    address public immutable launchFactory;
    struct TaxConfig {bytes32 identity;uint16 taxBps;bool registered;}
    mapping(address=>TaxConfig) public tokenConfig;
    event TokenRegistered(address indexed token,bytes32 indexed identity,uint16 taxBps);
    event Bought(address indexed user,address indexed token,uint256 grossEth,uint256 creatorTax,uint256 swapEth,uint256 tokenOut);
    event Sold(address indexed user,address indexed token,uint256 tokenIn,uint256 grossEthOut,uint256 creatorTax,uint256 netEthOut);

    constructor(address router_,address weth_,address vault_,address factory_){
        require(router_!=address(0)&&weth_!=address(0)&&vault_!=address(0)&&factory_!=address(0),"zero");
        router=ISingleV3SwapRouter(router_);weth=ISingleV3WETH(weth_);vault=ISingleV3Vault(vault_);launchFactory=factory_;
    }
    function registerFromFactory(address token,bytes32 identity,uint16 taxBps) external {
        require(msg.sender==launchFactory,"factory");require(token!=address(0)&&identity!=bytes32(0),"args");require(taxBps<=500&&taxBps%100==0,"tax");
        TaxConfig storage c=tokenConfig[token];require(!c.registered,"registered");c.identity=identity;c.taxBps=taxBps;c.registered=true;emit TokenRegistered(token,identity,taxBps);
    }
    function buy(address token,uint256 minTokenOut,uint256 deadline) external payable nonReentrant returns(uint256 tokenOut){
        require(block.timestamp<=deadline,"deadline");TaxConfig memory c=tokenConfig[token];require(c.registered&&msg.value>0,"input");
        uint256 creatorTax=msg.value*c.taxBps/BPS;
        uint256 swapEth=msg.value-creatorTax;
        if(creatorTax>0)vault.depositFor{value:creatorTax}(c.identity,token);
        weth.deposit{value:swapEth}();require(weth.approve(address(router),0),"approve reset");require(weth.approve(address(router),swapEth),"approve");
        tokenOut=router.exactInputSingle(ISingleV3SwapRouter.ExactInputSingleParams({tokenIn:address(weth),tokenOut:token,fee:POOL_FEE,recipient:msg.sender,amountIn:swapEth,amountOutMinimum:minTokenOut,sqrtPriceLimitX96:0}));
        emit Bought(msg.sender,token,msg.value,creatorTax,swapEth,tokenOut);
    }
    function sell(address token,uint256 amountIn,uint256 minEthOut,uint256 deadline) external nonReentrant returns(uint256 ethOut){
        require(block.timestamp<=deadline,"deadline");TaxConfig memory c=tokenConfig[token];require(c.registered&&amountIn>0,"input");
        require(IERC20(token).transferFrom(msg.sender,address(this),amountIn),"transfer in");require(IERC20(token).approve(address(router),0),"approve reset");require(IERC20(token).approve(address(router),amountIn),"approve");
        uint256 grossMin=c.taxBps==0?minEthOut:(minEthOut*BPS+(BPS-c.taxBps)-1)/(BPS-c.taxBps);
        uint256 wethOut=router.exactInputSingle(ISingleV3SwapRouter.ExactInputSingleParams({tokenIn:token,tokenOut:address(weth),fee:POOL_FEE,recipient:address(this),amountIn:amountIn,amountOutMinimum:grossMin,sqrtPriceLimitX96:0}));
        uint256 creatorTax=wethOut*c.taxBps/BPS;ethOut=wethOut-creatorTax;require(ethOut>=minEthOut,"slippage");weth.withdraw(wethOut);
        if(creatorTax>0)vault.depositFor{value:creatorTax}(c.identity,token);(bool ok,)=payable(msg.sender).call{value:ethOut}("");require(ok,"ETH");
        emit Sold(msg.sender,token,amountIn,wethOut,creatorTax,ethOut);
    }
    receive() external payable {require(msg.sender==address(weth),"direct ETH");}
}

@openzeppelin/contracts/security/ReentrancyGuard.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == _ENTERED;
    }
}

@openzeppelin/contracts/token/ERC20/ERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20 is Context, IERC20, IERC20Metadata {
    mapping(address => uint256) private _balances;

    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual override returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `amount`.
     */
    function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, allowance(owner, spender) + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        address owner = _msgSender();
        uint256 currentAllowance = allowance(owner, spender);
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(address from, address to, uint256 amount) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
            // decrementing then incrementing.
            _balances[to] += amount;
        }

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        unchecked {
            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
            _balances[account] += amount;
        }
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
            // Overflow not possible: amount <= accountBalance <= totalSupply.
            _totalSupply -= amount;
        }

        emit Transfer(account, address(0), amount);

        _afterTokenTransfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(address owner, address spender, uint256 amount) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
     *
     * Does not update the allowance amount in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Might emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC20: insufficient allowance");
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    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.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}

@openzeppelin/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}

@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

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

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

@openzeppelin/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

@uniswap/v4-core/src/libraries/BitMath.sol

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

/// @title BitMath
/// @dev This library provides functionality for computing bit properties of an unsigned integer
/// @author Solady (https://github.com/Vectorized/solady/blob/8200a70e8dc2a77ecb074fc2e99a2a0d36547522/src/utils/LibBit.sol)
library BitMath {
    /// @notice Returns the index of the most significant bit of the number,
    ///     where the least significant bit is at index 0 and the most significant bit is at index 255
    /// @param x the value for which to compute the most significant bit, must be greater than 0
    /// @return r the index of the most significant bit
    function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
        require(x > 0);

        assembly ("memory-safe") {
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // forgefmt: disable-next-item
            r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                0x0706060506020500060203020504000106050205030304010505030400000000))
        }
    }

    /// @notice Returns the index of the least significant bit of the number,
    ///     where the least significant bit is at index 0 and the most significant bit is at index 255
    /// @param x the value for which to compute the least significant bit, must be greater than 0
    /// @return r the index of the least significant bit
    function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
        require(x > 0);

        assembly ("memory-safe") {
            // Isolate the least significant bit.
            x := and(x, sub(0, x))
            // For the upper 3 bits of the result, use a De Bruijn-like lookup.
            // Credit to adhusson: https://blog.adhusson.com/cheap-find-first-set-evm/
            // forgefmt: disable-next-item
            r := shl(5, shr(252, shl(shl(2, shr(250, mul(x,
                0xb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff))),
                0x8040405543005266443200005020610674053026020000107506200176117077)))
            // For the lower 5 bits of the result, use a De Bruijn lookup.
            // forgefmt: disable-next-item
            r := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f),
                0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))
        }
    }
}

@uniswap/v4-core/src/libraries/CustomRevert.sol

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

/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
    /// @dev ERC-7751 error for wrapping bubbled up reverts
    error WrappedError(address target, bytes4 selector, bytes reason, bytes details);

    /// @dev Reverts with the selector of a custom error in the scratch space
    function revertWith(bytes4 selector) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            revert(0, 0x04)
        }
    }

    /// @dev Reverts with a custom error with an address argument in the scratch space
    function revertWith(bytes4 selector, address addr) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(0, 0x24)
        }
    }

    /// @dev Reverts with a custom error with an int24 argument in the scratch space
    function revertWith(bytes4 selector, int24 value) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            mstore(0x04, signextend(2, value))
            revert(0, 0x24)
        }
    }

    /// @dev Reverts with a custom error with a uint160 argument in the scratch space
    function revertWith(bytes4 selector, uint160 value) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(0, 0x24)
        }
    }

    /// @dev Reverts with a custom error with two int24 arguments
    function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(fmp, selector)
            mstore(add(fmp, 0x04), signextend(2, value1))
            mstore(add(fmp, 0x24), signextend(2, value2))
            revert(fmp, 0x44)
        }
    }

    /// @dev Reverts with a custom error with two uint160 arguments
    function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(fmp, selector)
            mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(fmp, 0x44)
        }
    }

    /// @dev Reverts with a custom error with two address arguments
    function revertWith(bytes4 selector, address value1, address value2) internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(fmp, selector)
            mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(fmp, 0x44)
        }
    }

    /// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
    /// @dev this method can be vulnerable to revert data bombs
    function bubbleUpAndRevertWith(
        address revertingContract,
        bytes4 revertingFunctionSelector,
        bytes4 additionalContext
    ) internal pure {
        bytes4 wrappedErrorSelector = WrappedError.selector;
        assembly ("memory-safe") {
            // Ensure the size of the revert data is a multiple of 32 bytes
            let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)

            let fmp := mload(0x40)

            // Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
            mstore(fmp, wrappedErrorSelector)
            mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(
                add(fmp, 0x24),
                and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
            )
            // offset revert reason
            mstore(add(fmp, 0x44), 0x80)
            // offset additional context
            mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
            // size revert reason
            mstore(add(fmp, 0x84), returndatasize())
            // revert reason
            returndatacopy(add(fmp, 0xa4), 0, returndatasize())
            // size additional context
            mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
            // additional context
            mstore(
                add(fmp, add(0xc4, encodedDataSize)),
                and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
            )
            revert(fmp, add(0xe4, encodedDataSize))
        }
    }
}

@uniswap/v4-core/src/libraries/TickMath.sol

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

import {BitMath} from "./BitMath.sol";
import {CustomRevert} from "./CustomRevert.sol";

/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
    using CustomRevert for bytes4;

    /// @notice Thrown when the tick passed to #getSqrtPriceAtTick is not between MIN_TICK and MAX_TICK
    error InvalidTick(int24 tick);
    /// @notice Thrown when the price passed to #getTickAtSqrtPrice does not correspond to a price between MIN_TICK and MAX_TICK
    error InvalidSqrtPrice(uint160 sqrtPriceX96);

    /// @dev The minimum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**-128
    /// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
    int24 internal constant MIN_TICK = -887272;
    /// @dev The maximum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**128
    /// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
    int24 internal constant MAX_TICK = 887272;

    /// @dev The minimum tick spacing value drawn from the range of type int16 that is greater than 0, i.e. min from the range [1, 32767]
    int24 internal constant MIN_TICK_SPACING = 1;
    /// @dev The maximum tick spacing value drawn from the range of type int16, i.e. max from the range [1, 32767]
    int24 internal constant MAX_TICK_SPACING = type(int16).max;

    /// @dev The minimum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MIN_TICK)
    uint160 internal constant MIN_SQRT_PRICE = 4295128739;
    /// @dev The maximum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MAX_TICK)
    uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342;
    /// @dev A threshold used for optimized bounds check, equals `MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1`
    uint160 internal constant MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE =
        1461446703485210103287273052203988822378723970342 - 4295128739 - 1;

    /// @notice Given a tickSpacing, compute the maximum usable tick
    function maxUsableTick(int24 tickSpacing) internal pure returns (int24) {
        unchecked {
            return (MAX_TICK / tickSpacing) * tickSpacing;
        }
    }

    /// @notice Given a tickSpacing, compute the minimum usable tick
    function minUsableTick(int24 tickSpacing) internal pure returns (int24) {
        unchecked {
            return (MIN_TICK / tickSpacing) * tickSpacing;
        }
    }

    /// @notice Calculates sqrt(1.0001^tick) * 2^96
    /// @dev Throws if |tick| > max tick
    /// @param tick The input tick for the above formula
    /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the price of the two assets (currency1/currency0)
    /// at the given tick
    function getSqrtPriceAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
        unchecked {
            uint256 absTick;
            assembly ("memory-safe") {
                tick := signextend(2, tick)
                // mask = 0 if tick >= 0 else -1 (all 1s)
                let mask := sar(255, tick)
                // if tick >= 0, |tick| = tick = 0 ^ tick
                // if tick < 0, |tick| = ~~|tick| = ~(-|tick| - 1) = ~(tick - 1) = (-1) ^ (tick - 1)
                // either way, |tick| = mask ^ (tick + mask)
                absTick := xor(mask, add(mask, tick))
            }

            if (absTick > uint256(int256(MAX_TICK))) InvalidTick.selector.revertWith(tick);

            // The tick is decomposed into bits, and for each bit with index i that is set, the product of 1/sqrt(1.0001^(2^i))
            // is calculated (using Q128.128). The constants used for this calculation are rounded to the nearest integer

            // Equivalent to:
            //     price = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
            //     or price = int(2**128 / sqrt(1.0001)) if (absTick & 0x1) else 1 << 128
            uint256 price;
            assembly ("memory-safe") {
                price := xor(shl(128, 1), mul(xor(shl(128, 1), 0xfffcb933bd6fad37aa2d162d1a594001), and(absTick, 0x1)))
            }
            if (absTick & 0x2 != 0) price = (price * 0xfff97272373d413259a46990580e213a) >> 128;
            if (absTick & 0x4 != 0) price = (price * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
            if (absTick & 0x8 != 0) price = (price * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
            if (absTick & 0x10 != 0) price = (price * 0xffcb9843d60f6159c9db58835c926644) >> 128;
            if (absTick & 0x20 != 0) price = (price * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
            if (absTick & 0x40 != 0) price = (price * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
            if (absTick & 0x80 != 0) price = (price * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
            if (absTick & 0x100 != 0) price = (price * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
            if (absTick & 0x200 != 0) price = (price * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
            if (absTick & 0x400 != 0) price = (price * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
            if (absTick & 0x800 != 0) price = (price * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
            if (absTick & 0x1000 != 0) price = (price * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
            if (absTick & 0x2000 != 0) price = (price * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
            if (absTick & 0x4000 != 0) price = (price * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
            if (absTick & 0x8000 != 0) price = (price * 0x31be135f97d08fd981231505542fcfa6) >> 128;
            if (absTick & 0x10000 != 0) price = (price * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
            if (absTick & 0x20000 != 0) price = (price * 0x5d6af8dedb81196699c329225ee604) >> 128;
            if (absTick & 0x40000 != 0) price = (price * 0x2216e584f5fa1ea926041bedfe98) >> 128;
            if (absTick & 0x80000 != 0) price = (price * 0x48a170391f7dc42444e8fa2) >> 128;

            assembly ("memory-safe") {
                // if (tick > 0) price = type(uint256).max / price;
                if sgt(tick, 0) { price := div(not(0), price) }

                // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
                // we then downcast because we know the result always fits within 160 bits due to our tick input constraint
                // we round up in the division so getTickAtSqrtPrice of the output price is always consistent
                // `sub(shl(32, 1), 1)` is `type(uint32).max`
                // `price + type(uint32).max` will not overflow because `price` fits in 192 bits
                sqrtPriceX96 := shr(32, add(price, sub(shl(32, 1), 1)))
            }
        }
    }

    /// @notice Calculates the greatest tick value such that getSqrtPriceAtTick(tick) <= sqrtPriceX96
    /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_PRICE, as MIN_SQRT_PRICE is the lowest value getSqrtPriceAtTick may
    /// ever return.
    /// @param sqrtPriceX96 The sqrt price for which to compute the tick as a Q64.96
    /// @return tick The greatest tick for which the getSqrtPriceAtTick(tick) is less than or equal to the input sqrtPriceX96
    function getTickAtSqrtPrice(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
        unchecked {
            // Equivalent: if (sqrtPriceX96 < MIN_SQRT_PRICE || sqrtPriceX96 >= MAX_SQRT_PRICE) revert InvalidSqrtPrice();
            // second inequality must be >= because the price can never reach the price at the max tick
            // if sqrtPriceX96 < MIN_SQRT_PRICE, the `sub` underflows and `gt` is true
            // if sqrtPriceX96 >= MAX_SQRT_PRICE, sqrtPriceX96 - MIN_SQRT_PRICE > MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1
            if ((sqrtPriceX96 - MIN_SQRT_PRICE) > MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE) {
                InvalidSqrtPrice.selector.revertWith(sqrtPriceX96);
            }

            uint256 price = uint256(sqrtPriceX96) << 32;

            uint256 r = price;
            uint256 msb = BitMath.mostSignificantBit(r);

            if (msb >= 128) r = price >> (msb - 127);
            else r = price << (127 - msb);

            int256 log_2 = (int256(msb) - 128) << 64;

            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(63, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(62, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(61, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(60, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(59, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(58, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(57, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(56, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(55, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(54, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(53, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(52, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(51, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(50, f))
            }

            int256 log_sqrt10001 = log_2 * 255738958999603826347141; // Q22.128 number

            // Magic number represents the ceiling of the maximum value of the error when approximating log_sqrt10001(x)
            int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);

            // Magic number represents the minimum value of the error when approximating log_sqrt10001(x), when
            // sqrtPrice is from the range (2^-64, 2^64). This is safe as MIN_SQRT_PRICE is more than 2^-64. If MIN_SQRT_PRICE
            // is changed, this may need to be changed too
            int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);

            tick = tickLow == tickHi ? tickLow : getSqrtPriceAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
        }
    }
}

EthXDirectToken.sol

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

import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";

/// @notice Fixed-supply EthXPay token used by the direct V3/V4 launch engines.
/// @dev 1B fixed supply. The immutable launcher may hold at most 10%; every
///      ordinary wallet may hold at most 2%. Protocol custody is explicitly exempt.
contract EthXDirectToken is ERC20 {
    uint256 public constant TOTAL_SUPPLY = 1_000_000_000 ether;
    uint256 public constant MAX_WALLET = 20_000_000 ether;
    uint256 public constant MAX_DEV_WALLET = 100_000_000 ether;
    address public constant BURN = 0x000000000000000000000000000000000000dEaD;

    address public immutable factory;
    address public immutable launcher;
    uint8 public immutable launchEngine; // 1=V3, 2=V4
    bool public activated;
    mapping(address => bool) public protocolExempt;

    constructor(string memory n,string memory s,address f,address dev,uint8 engine) ERC20(n,s) {
        require(f!=address(0) && dev!=address(0) && (engine==1 || engine==2),"origin");
        factory=f; launcher=dev; launchEngine=engine;
        protocolExempt[f]=true;
        protocolExempt[BURN]=true;
        _mint(f,TOTAL_SUPPLY);
    }    function walletCap(address wallet) public view returns(uint256){
        return wallet==launcher ? MAX_DEV_WALLET : MAX_WALLET;
    }

    /// @notice One-time protocol exemption finalization by the immutable factory.
    /// @dev Exemptions are only protocol custody/pool/router addresses. There is
    ///      no admin method after activation.
    function activate(address[] calldata protocol) external {
        require(msg.sender==factory && !activated,"activate");
        require(protocol.length>0 && protocol.length<=12,"protocol");
        for(uint256 i=0;i<protocol.length;i++){
            address a=protocol[i];
            require(a!=address(0),"zero");
            protocolExempt[a]=true;
        }
        activated=true;
    }

    function _transfer(address from,address to,uint256 amount) internal override {
        // Before atomic launch setup completes, only the immutable factory owns
        // supply and may seed protocol custody. Public transfers are impossible.
        if(activated && from!=to && !protocolExempt[to]){
            require(balanceOf(to)+amount<=walletCap(to),"wallet cap exceeded");
        } else if(!activated && from!=factory) {
            require(balanceOf(to)+amount<=walletCap(to),"wallet cap exceeded");
        }
        super._transfer(from,to,amount);
    }
}

/// @notice Shared namespace-safe CREATE2 child deployer for direct V3/V4 factories.
/// @dev Caller address is mixed into the salt, preventing another factory/user
///      from pre-deploying inside a factory's token namespace.
contract EthXDirectTokenDeployer {
    event TokenDeployed(address indexed factory,address indexed token,bytes32 indexed salt);

    function deploy(bytes32 userSalt,string calldata n,string calldata s,address launcher,uint8 engine)
        external returns(address token)
    {
        bytes32 salt=keccak256(abi.encode(msg.sender,userSalt));
        token=address(new EthXDirectToken{salt:salt}(n,s,msg.sender,launcher,engine));
        emit TokenDeployed(msg.sender,token,salt);
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "optimizer": {
    "runs": 500,
    "enabled": true
  },
  "evmVersion": "cancun"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.