// File: src/MemeAltar.sol



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

import {Bloodline} from "./Bloodline.sol";
import "./interfaces/IERC20.sol";
import "./interfaces/ILiquidityOwner.sol";
import "./interfaces/IRewardLocker.sol";
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";

/// Attempt to access admin functionality from unauthorized address.
error NotAdmin();
/// LiquidityOwner initialization is one time action.
error LiquidityOwnerAlreadyInitialized();
/// Provided arrays must be the same length.
error ArraysHaveDifferentLength();
/// Meme cannot be removed, because it is not in a list.
error MemeIsNotInAList();
/// Uniswap V2 pool address cannot be switched for a not set meme.
error SwitchRequiresMemeBeSet();
/// Token is not accepted to be a sacrificable.
error TokenIsNotInSacrificableList();
/// Amount provided to be sacrificed equal 0.
error NothingToSacrifice();
/// Unfortunately, the uniswap pool `uniV2Pool` is out of liquidity.
error UniV2PoolWithoutLiquidity(address uniV2Pool);
/// Attempt to sell sacrificed meme resulted in receiving less ETH than was initially expected.
error InsufficientOutputAmount();
/// Reward did not registered.
error RewardRegistrationFailed();
/// Cycle completed did not registered.
error CycleCompletedRegistrationFailed();
/// Next cycle did not registered.
error NextCycleRegistrationFailed();
/// Liquidity Owner trigger call failed.
error LiquidityOwnerTriggerFailed();
/// Swaps entirely within 0-liquidity regions are not supported
error SwapWithinZeroLiquidity();
/// Attempt to call uniswap v3 swap callback.
error SwapCallbackCanBeCalledOnlyByPool();
/// Attempt to buy BDL resulted in receiving less BDL than was initially expected.
error TooLittleReceived();
/// Attempt to buy BDL resulted in requesting different WETH amount than was initially expected.
error NotExactInput();
/// Goal cannot be set to zero value, breaks invariants.
error GoalCannotBeZero();

/**
 * @title MemeAltar - Place, users come to sacrifice their meme tokens to and get
 *                    rewarded. Admin is able to add/remove meme tokens; adjust
 *                    default goal, cycle duration limit, reward defining points.
 */
contract MemeAltar {
    struct SacrificedMeme {
        uint112 achieved;
        bool cycleParticipant;
    }

    struct Cycle {
        uint112 goal;
        /// @notice total amount of ETH used to buy BDL from Uniswap v3 pool to recover the price in a cycle.
        uint112 ethUsedToBuy;
        uint32 expirationTimestamp;
        mapping(address => SacrificedMeme) sacrificedMemes;
    }

    /*//////////////////////////////////////////////////////////////
                               EVENTS
    //////////////////////////////////////////////////////////////*/
    event NewAdmin(address indexed newAdmin);

    event MemeAddedToSacrificableList(
        uint256 indexed cycleNumber, address indexed meme, address indexed memeMarket
    );

    event MemeRemovedFromSacrificableList(uint256 indexed cycleNumber, address indexed meme);

    event NewDefaultCycleGoal(uint256 indexed newDefaultGoal);

    event NewCycleDurationLimit(uint256 indexed newDurationLimit);

    event NewBM(uint64 indexed b, uint64 indexed m);

    event MemeSacrificed(
        address indexed sacrificer,
        address indexed sacrificedToken,
        uint256 indexed sacrificedAmount
    );

    /*//////////////////////////////////////////////////////////////
                              CONSTANTS
    //////////////////////////////////////////////////////////////*/

    /// @dev The minimum sqrt price value. Equivalent to MIN_TICK = -887200.
    uint160 internal constant MIN_SQRT_RATIO = 4_310_618_293;
    /// @dev The maximum sqrt price value. Equivalent to MAX_TICK = 887200.
    uint160 internal constant MAX_SQRT_RATIO =
        1_456_195_216_270_955_103_206_513_029_158_776_779_468_408_838_535;

    /*//////////////////////////////////////////////////////////////
                        MEME ALTAR STORAGE
    //////////////////////////////////////////////////////////////*/
    /// @notice Contract WETH9 - ERC20 Wrapped Ether.
    address public weth;
    /// @notice ERC20 which is a reward token.
    Bloodline public bloodline;
    /// @notice Uniswap V3 pool: WETH and Bloodline.
    address public uniV3Pool;
    /// @notice Contract that stores the rewards and is triggered when cycle is completed.
    address public rewardLocker;
    /// @notice Contract that stores weth (weth is transfered to) and provides liquidity.
    address public liquidityOwner;
    /// @notice Address, which is allowed to call onlyAdmin functions.
    address public admin;

    /// @notice The number of the current cycle.
    uint112 public currentCycle = 1;
    /// @notice The value used as a cycle goal, if no cycle goal was set.
    uint112 public defaultGoal;
    /// @notice Cycle completes without a winner after this duration limit is expired.
    uint32 public cycleDurationLimit = 7 days;
    /// @notice Stores the data related to the cycles.
    /// @dev cycleNumber -> Cycle struct
    mapping(uint112 => Cycle) public cycles;
    /// @notice Stores uniswap v2 pair (WETH-Meme) addresses.
    /// @dev meme -> uniV2 pair
    mapping(address => address) public memesUniV2Pools;
    /// @notice Stores a list of meme addresses, which are sacrificable in a next cycle.
    address[] public memeList;
    /// @notice y-intercept of linear functions, which defines the reward factor.
    uint64 public b = 95;
    /// @notice Slope of linear functions, which defines the reward factor.
    uint64 public m = 30;
    /// @notice a ratio between BLOOD token and ETH, used as a base to calculate reward.
    uint128 public issuancePrice = 32_000;

    modifier onlyAdmin() {
        if (msg.sender != admin) {
            revert NotAdmin();
        }
        _;
    }

    /*//////////////////////////////////////////////////////////////
                            CONSTRUCTOR
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Constructor sets storage values, initialize rewardLocker, registers first cycle.
     * @param sacrificableList an array of ERC20 meme addresses, which are sacrificable.
     * @param uniV2pools an array of uniswap v2 pair (WETH-Meme) addresses related to list above.
     * @param _weth WETH9 (ERC20 Wrapped Ether) contract address.
     * @param _admin address, which is allowed to adjust memeList, defaultGoal, cycle duration limit, BM.
     * @param _rewardLocker RewardLocker contract address.
     * @param _bloodline ERC20 reward token address.
     * @param _devLiquidityHolder Receiver of minted 3% BLOOD developer fee.
     * @param _defaultGoal a cycle goal competitors have to achieve, denominated in ETH.
     */
    constructor(
        address[] memory sacrificableList,
        address[] memory uniV2pools,
        address _weth,
        address _admin,
        address _rewardLocker,
        address _bloodline,
        address _devLiquidityHolder,
        uint112 _defaultGoal
    ) {
        if (sacrificableList.length != uniV2pools.length) {
            revert ArraysHaveDifferentLength();
        }

        weth = _weth;
        defaultGoal = _defaultGoal;
        admin = _admin;
        rewardLocker = _rewardLocker;
        memeList = sacrificableList;
        bloodline = Bloodline(_bloodline);
        uniV3Pool = bloodline.uniV3Pool();

        Cycle storage cycle = cycles[1];
        cycle.expirationTimestamp = uint32(block.timestamp) + 7 days;
        cycle.goal = _defaultGoal;

        for (uint256 i = 0; i < sacrificableList.length; i++) {
            memesUniV2Pools[sacrificableList[i]] = uniV2pools[i];
            SacrificedMeme storage meme = cycle.sacrificedMemes[sacrificableList[i]];
            meme.cycleParticipant = true;
            emit MemeAddedToSacrificableList(currentCycle, sacrificableList[i], uniV2pools[i]);
        }

        IRewardLocker(_rewardLocker).init(address(this), _bloodline, _devLiquidityHolder);
        IRewardLocker(_rewardLocker).registerNextCycle(currentCycle, sacrificableList);
    }

    /**
     * @notice Method initialize liquidityOwner.
     * @param _liquidityOwner address of LiquidityOwner contract.
     */
    function setLiquidityOwner(address _liquidityOwner) external {
        if (liquidityOwner != address(0)) {
            revert LiquidityOwnerAlreadyInitialized();
        }
        liquidityOwner = _liquidityOwner;
    }

    /*//////////////////////////////////////////////////////////////
                        ADMINISTRATION LOGIC
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Method switches `admin` to 'newAdmin' admin address.
     * @param newAdmin address of new admin.
     * @return True
     */
    function switchAdmin(address newAdmin) external onlyAdmin returns (bool) {
        admin = newAdmin;
        emit NewAdmin(newAdmin);
        return true;
    }

    /**
     * @notice Method adds new meme token to a list of sacrificable tokens.
     *         Applied in the next cycles.
     * @param meme address of meme token, which will become sacrificable in next cycles.
     * @param uniV2Pool uniswap v2 pair (WETH-Meme) address.
     * @return True
     */
    function addMemeToList(
        address meme,
        address uniV2Pool
    )
        external
        onlyAdmin
        returns (bool)
    {
        memesUniV2Pools[meme] = uniV2Pool;

        uint256 lastSacrificableIndex = memeList.length - 1;
        while (memesUniV2Pools[memeList[lastSacrificableIndex]] == address(0)) {
            lastSacrificableIndex--;
        }

        memeList.push(meme);

        if (lastSacrificableIndex != memeList.length - 2) {
            // need to replace
            memeList[memeList.length - 1] = memeList[lastSacrificableIndex + 1];
            memeList[lastSacrificableIndex + 1] = meme;
        }

        emit MemeAddedToSacrificableList(currentCycle + 1, meme, uniV2Pool);
        return true;
    }

    /**
     * @notice Method removes meme token from a list of sacrificable tokens.
     *         Applied in the next cycles.
     * @param meme address of meme token, which is not sacrificable in next cycles.
     * @return True
     */
    function removeMemeFromList(address meme) external onlyAdmin returns (bool) {
        // define last sacrificable index
        uint256 lastSacrificableIndex = memeList.length - 1;
        while (memesUniV2Pools[memeList[lastSacrificableIndex]] == address(0)) {
            lastSacrificableIndex--;
        }
        if (memeList[lastSacrificableIndex] != meme) {
            // try to find array index
            uint256 indexId;
            for (uint256 index = 0; index < lastSacrificableIndex + 1; index++) {
                if (memeList[index] == meme) {
                    indexId = index;
                    break;
                }
            }
            // check if element exist
            if (memeList[indexId] != meme) {
                revert MemeIsNotInAList();
            }
            // replace last
            memeList[indexId] = memeList[lastSacrificableIndex];
            memeList[lastSacrificableIndex] = meme;
        }

        memesUniV2Pools[meme] = address(0);
        emit MemeRemovedFromSacrificableList(currentCycle, meme);
        return true;
    }

    /**
     * @notice Method replaces meme uniswap v2 pool to new one.
     *         Applied immidiately.
     * @param meme address of meme token, which pool should be switched.
     * @param newUniV2Pool uniswap v2 pair (WETH-Meme) address.
     * @return True
     */
    function switchUniV2Pool(
        address meme,
        address newUniV2Pool
    )
        external
        onlyAdmin
        returns (bool)
    {
        if (memesUniV2Pools[meme] == address(0)) {
            revert SwitchRequiresMemeBeSet();
        }
        memesUniV2Pools[meme] = newUniV2Pool;
        return true;
    }

    /// @notice Method adjust y-intercept and slope of linear functions. Applied immidiately.
    function adjustBM(uint64 newB, uint64 newM) external onlyAdmin returns (bool) {
        b = newB;
        m = newM;
        emit NewBM(newB, newM);
        return true;
    }

    /**
     * @notice Method adjust default goal value. Applied in the next cycles.
     * @param newDefaultGoal new value of a default goal.
     * @return True
     */
    function adjustDefaultGoal(uint112 newDefaultGoal) external onlyAdmin returns (bool) {
        if (newDefaultGoal == uint112(0)) {
            revert GoalCannotBeZero();
        }
        defaultGoal = newDefaultGoal;
        emit NewDefaultCycleGoal(newDefaultGoal);
        return true;
    }

    /**
     * @notice Method adjust cycles duration limit. Applied in the next cycles.
     * @param newDurationLimit duration in seconds.
     * @return True
     */
    function adjustCycleDurationLimit(uint32 newDurationLimit)
        external
        onlyAdmin
        returns (bool)
    {
        cycleDurationLimit = newDurationLimit;
        emit NewCycleDurationLimit(newDurationLimit);
        return true;
    }

    /*//////////////////////////////////////////////////////////////
              SACRIFICE LOGIC: sacrificeMeme and internals
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Method sacrifices `memeToSacrifice` tokens and rewards with Bloodline tokens.
     *         `memeToSacrifice` token preapproval is required.
     * @param memeToSacrifice address of meme token from the sacrificable list.
     * @param amountToSacrifice amount of sacrificable meme token to be sacrificed.
     * @param minETH minimum amount of ETH to receive for selling meme.
     * @return reward amount for sacrificing in Bloodline tokens.
     */
    function sacrificeMeme(
        address memeToSacrifice,
        uint256 amountToSacrifice,
        uint112 minETH
    )
        external
        returns (uint128 reward)
    {
        if (amountToSacrifice == 0) {
            revert NothingToSacrifice();
        }
        Cycle storage cycle = cycles[currentCycle];
        if (!cycle.sacrificedMemes[memeToSacrifice].cycleParticipant) {
            revert TokenIsNotInSacrificableList();
        }

        uint112 amountOfWETH = _sellToUniV2(memeToSacrifice, amountToSacrifice, minETH);
        uint112 amountWithoutDevFee = amountOfWETH * 97 / 100;

        // calculate reward
        bool cycleCompleted;
        uint112 extraAmount;
        (reward, extraAmount, cycleCompleted) =
            _calculateRewardFor(memeToSacrifice, amountWithoutDevFee);

        if (!IRewardLocker(rewardLocker).registerReward(msg.sender, memeToSacrifice, reward)) {
            revert RewardRegistrationFailed();
        }

        if (cycleCompleted) {
            if (
                !IRewardLocker(rewardLocker).registerCycleCompleted(
                    currentCycle, memeToSacrifice
                )
            ) {
                revert CycleCompletedRegistrationFailed();
            }
        }

        if (!cycleCompleted && cycle.expirationTimestamp <= block.timestamp) {
            // complete cycle without winner
            if (!IRewardLocker(rewardLocker).registerCycleCompleted(currentCycle, address(0)))
            {
                revert CycleCompletedRegistrationFailed();
            }
        }

        if (cycleCompleted || cycle.expirationTimestamp <= block.timestamp) {
            (uint112 nextCycleNumber, uint112 collectedEthInCycle) =
                _registerCycleCompleted(cycle);

            if (!IRewardLocker(rewardLocker).registerNextCycle(nextCycleNumber, memeList)) {
                revert NextCycleRegistrationFailed();
            }

            issuancePrice =
                uint128(ILiquidityOwner(liquidityOwner).provideLiquidity(collectedEthInCycle));

            // cover extra amount
            if (extraAmount > 0) {
                reward += _handleExtraAmount(memeToSacrifice, extraAmount);
            }
        }

        // ask liquidity owner to pay developer fee
        ILiquidityOwner(liquidityOwner).payDeveloperFee(amountOfWETH - amountWithoutDevFee);

        emit MemeSacrificed(msg.sender, memeToSacrifice, amountToSacrifice);
    }

    /// @notice sells meme `memeToSell` token to `uniV2Pool` uniswap v2 pool for ETH.
    function _sellToUniV2(
        address memeToSell,
        uint256 amountToSell,
        uint112 minETH
    )
        internal
        returns (uint112)
    {
        address uniV2Pool = memesUniV2Pools[memeToSell];
        if (uniV2Pool == address(0)) {
            revert TokenIsNotInSacrificableList();
        }
        bool token0 = memeToSell < weth;
        (uint256 reserve0, uint256 reserve1,) = IUniswapV2Pair(uniV2Pool).getReserves();

        if (reserve0 == 0 || reserve1 == 0) {
            revert UniV2PoolWithoutLiquidity(uniV2Pool);
        }

        uint256 amountInWithFee = amountToSell * 997;
        uint256 numerator = amountInWithFee * (token0 ? reserve1 : reserve0);
        uint256 denominator = amountInWithFee + ((token0 ? reserve0 : reserve1) * 1000);
        uint256 amountOut = numerator / denominator;

        if (minETH > amountOut) {
            revert InsufficientOutputAmount();
        }

        // transfer tokens directly from msg.sender to uniswapV2 pool
        /// @dev requires memeToSacrifice transferFrom returns bool.
        require(IERC20(memeToSell).transferFrom(msg.sender, uniV2Pool, amountToSell));

        // make a swap, transfer ETH to LiquidityOwner
        token0
            ? IUniswapV2Pair(uniV2Pool).swap(0, amountOut, liquidityOwner, "")
            : IUniswapV2Pair(uniV2Pool).swap(amountOut, 0, liquidityOwner, "");

        return uint112(amountOut);
    }

    /**
     * @notice Calculates reward amount based on a cycle goal, ETH received for
     *         selling meme tokens and this `memeToSacrifice` token previous achievements.
     * @param memeToSacrifice address of meme token from the sacrificable list.
     * @param amountOfWETH ETH amount received for selling, minus developer fee.
     * @return reward calculated amount of BLOOD tokens.
     * @return extraAmount If amountOfWETH is enough to complete two cycles in a row,
     *         only one cycle is completed, next cycle achieved is set 95%, extra amount is returned in meme.
     * @return cycleCompleted True, if amount of ETH was enough to reach a cycle goal.
     */
    function _calculateRewardFor(
        address memeToSacrifice,
        uint112 amountOfWETH
    )
        internal
        returns (uint128 reward, uint112 extraAmount, bool cycleCompleted)
    {
        Cycle storage cycle = cycles[currentCycle];
        SacrificedMeme storage sacrificedMeme = cycle.sacrificedMemes[memeToSacrifice];

        uint112 achievement = amountOfWETH;
        if (sacrificedMeme.achieved + amountOfWETH >= cycle.goal) {
            achievement = cycle.goal - sacrificedMeme.achieved;
            extraAmount = amountOfWETH - achievement;
            cycleCompleted = true;
        }

        reward = _calculateReward(cycle.goal, sacrificedMeme.achieved, achievement);
        sacrificedMeme.achieved += achievement;
    }

    /// @notice general function to calculate reward
    function _calculateReward(
        uint256 goal,
        uint256 achieved,
        uint256 amount
    )
        internal
        view
        returns (uint128)
    {
        return
            uint128(_calculateTripleLinearReward(goal, achieved, amount, issuancePrice, b, m));
    }

    /// @notice Sets current cycle, defines total collected ETH in a completed cycle,
    /// removes removed memes from a meme list, sets expiration timestamp, goal, and participants in a coming cycle.
    function _registerCycleCompleted(Cycle storage cycleCompleted)
        internal
        returns (uint112 nextCycleNumber, uint112 ethCollectedInCycle)
    {
        // storage write
        currentCycle += 1;
        nextCycleNumber = currentCycle;

        Cycle storage cycleComing = cycles[nextCycleNumber];
        uint256 numberOfMemes = memeList.length;
        bool sacrificable = false;
        // loop through a list of completed cycle memes
        for (uint256 i = numberOfMemes; i > 0; i--) {
            address meme = memeList[i - 1];
            SacrificedMeme storage memeCompletedCycle = cycleCompleted.sacrificedMemes[meme];
            // add meme ETH achievement to totalCollectedETH in a completed cycle
            ethCollectedInCycle += memeCompletedCycle.achieved;
            // remove from list memes, which were removed by admin
            if (!sacrificable) {
                if (memesUniV2Pools[meme] == address(0)) {
                    memeList.pop();
                } else {
                    sacrificable = true;
                }
            }
            // set as participants in coming cycle all sacrificable memes (all not removed and newly added memes by admin)
            if (sacrificable) {
                SacrificedMeme storage memeComingCycle = cycleComing.sacrificedMemes[meme];
                memeComingCycle.cycleParticipant = true;
            }
        }
        // subtract ETH used to buy BLOOD from totalCollectedETH in a completed cycle
        ethCollectedInCycle -= cycleCompleted.ethUsedToBuy;

        // set coming cycle state
        cycleComing.expirationTimestamp = uint32(block.timestamp) + cycleDurationLimit;
        cycleComing.goal = defaultGoal;
    }

    /// @notice Handle extra ETH over required to complete cycle.
    /// Returns extra reward, which is registered for a next cycle, if meme is its participant.
    //  Buys meme back, if meme is not participant or extra amount is enough to complete next cycle (complete two cycles in 1 tx is dissalowed).
    function _handleExtraAmount(
        address meme,
        uint112 extraAmount
    )
        internal
        returns (uint128 extraReward)
    {
        // no extraReward, if extraAmount is less than gas cost spent on extraReward
        if (extraAmount < 100_000 * (tx.gasprice > 120 gwei ? 120 gwei : tx.gasprice)) {
            return extraReward;
        }
        // check meme participant in coming cycle
        Cycle storage cycle = cycles[currentCycle];
        SacrificedMeme storage sacrificedMeme = cycle.sacrificedMemes[meme];
        if (sacrificedMeme.cycleParticipant) {
            uint112 achievement = extraAmount;
            if (extraAmount >= cycle.goal) {
                // consume only 95%
                achievement = cycle.goal * 95 / 100;
                _buyBack(extraAmount - achievement, meme);
            }
            extraReward = _calculateReward(cycle.goal, sacrificedMeme.achieved, achievement);
            // storage write
            sacrificedMeme.achieved += achievement;
            if (!IRewardLocker(rewardLocker).registerReward(msg.sender, meme, extraReward)) {
                revert RewardRegistrationFailed();
            }
        } else {
            _buyBack(extraAmount, meme);
        }
    }

    /// @notice Expected to be a rare case. Buys sacrificed meme tokens back and returns them to msg.sender.
    ///  Case 1. Amount received from selling was bigger than required to complete cycle and sacrificed meme is not a participant in next cycle.
    ///  Case 2. Amount received from selling was bigger than required to complete two cycles in a row.
    function _buyBack(uint256 extraAmount, address memeToBuy) internal {
        bool token0 = memeToBuy < weth;
        address uniV2Pool = memesUniV2Pools[memeToBuy];
        (uint256 reserve0, uint256 reserve1,) = IUniswapV2Pair(uniV2Pool).getReserves();

        uint256 amountInWithFee = extraAmount * 997;
        uint256 numerator = amountInWithFee * (token0 ? reserve0 : reserve1);
        uint256 denominator = amountInWithFee + ((token0 ? reserve1 : reserve0) * 1000);
        uint256 amountOut = numerator / denominator;

        ILiquidityOwner(liquidityOwner).payWETHToUniswapPool(uniV2Pool, extraAmount);

        // make a swap and transfer tokens directly to sacrificer
        token0
            ? IUniswapV2Pair(uniV2Pool).swap(amountOut, 0, msg.sender, "")
            : IUniswapV2Pair(uniV2Pool).swap(0, amountOut, msg.sender, "");
    }

    /*//////////////////////////////////////////////////////////////
        SACRIFICE LOGIC: sacrificeMemeAndBuyBLOOD and internals
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Method sacrifice `memeToSacrifice` tokens and buys Bloodline reward tokens
     *         from Uniswap V3 pool to maximize user profit and to recover the price, burns bought amount and register
     *         the same reward amount for a user in a current cycle, increases meme cycle achievements.
     *         `memeToSacrifice` token preapproval is required.
     * @param memeToSacrifice address of meme token from the sacrificable list.
     * @param amountToSacrifice amount of sacrificeable meme token to be sacrificed.
     * @param minBLOOD minimum amount of BDL, which should be received by buying from a pool (includes slippage - calculated on frontend side).
     * @return reward amount of the default reward for sacrificing in Bloodline tokens.
     */
    function sacrificeMemeAndBuyBLOOD(
        address memeToSacrifice,
        uint256 amountToSacrifice,
        uint256 minBLOOD
    )
        external
        returns (uint256 reward)
    {
        if (amountToSacrifice == 0) {
            revert NothingToSacrifice();
        }
        Cycle storage cycle = cycles[currentCycle];
        if (!cycle.sacrificedMemes[memeToSacrifice].cycleParticipant) {
            revert TokenIsNotInSacrificableList();
        }
        // set minETH 0, because we have minBLOOD protecting against sandwitch attack, which implicitly includes a minETH value - no need to double check
        uint112 amountOfWETH = _sellToUniV2(memeToSacrifice, amountToSacrifice, 0);
        uint112 amountWithoutDevFee = amountOfWETH * 97 / 100;

        // buy BLOOD from Uniswap v3
        reward = _buyBloodline(amountWithoutDevFee, minBLOOD);

        (bool cycleCompleted, uint256 burnAmount, uint256 transferAmount) =
            _increaseAchievedCompareGoal(memeToSacrifice, amountWithoutDevFee, reward, cycle);

        // burn BLOOD received from a pool to register it as a reward
        require(bloodline.burn(burnAmount));

        if (transferAmount > 0) {
            // transfer extra BLOOD bought for ETH over required to complete cycle
            bloodline.transfer(msg.sender, transferAmount);
        }

        // register reward
        if (
            !IRewardLocker(rewardLocker).registerReward(msg.sender, memeToSacrifice, burnAmount)
        ) {
            revert RewardRegistrationFailed();
        }

        if (cycleCompleted) {
            if (
                !IRewardLocker(rewardLocker).registerCycleCompleted(
                    currentCycle, memeToSacrifice
                )
            ) {
                revert CycleCompletedRegistrationFailed();
            }
        }

        if (!cycleCompleted && cycle.expirationTimestamp <= block.timestamp) {
            // complete cycle without winner
            if (!IRewardLocker(rewardLocker).registerCycleCompleted(currentCycle, address(0)))
            {
                revert CycleCompletedRegistrationFailed();
            }
        }

        if (cycleCompleted || cycle.expirationTimestamp <= block.timestamp) {
            (uint112 nextCycleNumber, uint112 collectedEthInCycle) =
                _registerCycleCompleted(cycle);

            if (!IRewardLocker(rewardLocker).registerNextCycle(nextCycleNumber, memeList)) {
                revert NextCycleRegistrationFailed();
            }

            issuancePrice =
                uint128(ILiquidityOwner(liquidityOwner).provideLiquidity(collectedEthInCycle));
        }

        // ask liquidity owner to pay developer fee
        ILiquidityOwner(liquidityOwner).payDeveloperFee(amountOfWETH - amountWithoutDevFee);

        emit MemeSacrificed(msg.sender, memeToSacrifice, amountToSacrifice);
    }

    function _buyBloodline(
        uint256 ethIn,
        uint256 minBDLOut
    )
        internal
        returns (uint256 bdlOut)
    {
        bytes memory callbackData = abi.encode(ethIn, minBDLOut);
        bool wethToken0 = weth < address(bloodline);
        (int256 amount0, int256 amount1) = IUniswapV3Pool(uniV3Pool).swap(
            address(this),
            wethToken0,
            int256(ethIn),
            wethToken0 ? MIN_SQRT_RATIO : MAX_SQRT_RATIO,
            callbackData
        );

        bdlOut = wethToken0 ? uint256(-amount1) : uint256(-amount0);
    }

    /// @notice Adds ETH to meme achievements, defines if cycle is completed,
    /// based on result defines amounts of BLOOD to burn and to transfer to sacrificer.
    function _increaseAchievedCompareGoal(
        address meme,
        uint112 amountOfWETH,
        uint256 reward,
        Cycle storage cycle
    )
        internal
        returns (bool cycleCompleted, uint256 burnAmount, uint256 transferAmount)
    {
        SacrificedMeme storage sacrificedMeme = cycle.sacrificedMemes[meme];
        uint112 achievement = amountOfWETH;
        if (sacrificedMeme.achieved + amountOfWETH >= cycle.goal) {
            achievement = cycle.goal - sacrificedMeme.achieved;
            cycleCompleted = true;
            burnAmount = reward * achievement / amountOfWETH;
            transferAmount = reward - burnAmount;
        } else {
            burnAmount = reward;
        }
        // storage writes
        sacrificedMeme.achieved += achievement;
        cycle.ethUsedToBuy += achievement;
    }

    /*//////////////////////////////////////////////////////////////
                            VIEW FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice View method returns meme token participation and already achieved
     *         amount on its way to a cycle `cycleNumber` goal.
     * @param cycleNumber token data is requested for.
     * @param meme address of a meme token, data is requested for.
     * @return participation True, if token is eligable participant in a cycle `cycleNumber`.
     * @return amountAchieved amount in ETH, achived already on a token way to a cycle goal.
     */
    function getSacrificedMeme(
        uint112 cycleNumber,
        address meme
    )
        external
        view
        returns (bool participation, uint256 amountAchieved)
    {
        Cycle storage cycle = cycles[cycleNumber];
        SacrificedMeme storage sacrificedMeme = cycle.sacrificedMemes[meme];
        participation = sacrificedMeme.cycleParticipant;
        amountAchieved = sacrificedMeme.achieved;
    }

    /**
     * @notice View method returns giving reward amount for sacrificing this amount
     *         `amountToSacrifice` of this `memeToSacrifice` meme token now (time/action sensitive data).
     * @param memeToSacrifice address of meme token from the sacrificable list.
     * @param amountToSacrifice amount of sacrificable meme token to calculate current reward for.
     * @return rewardCurrentCycle reward amount for sacrificing in Bloodline tokens in current cycle.
     * @return rewardNextCycle reward amount for sacrificing in Bloodline tokens in next cycle (not accurate, as doesn't consider issuancePrice adjustments).
     */
    function getRewardForSacrifice(
        address memeToSacrifice,
        uint256 amountToSacrifice
    )
        external
        view
        returns (uint256 rewardCurrentCycle, uint256 rewardNextCycle)
    {
        Cycle storage cycle = cycles[currentCycle];
        SacrificedMeme storage sacrificedMeme = cycle.sacrificedMemes[memeToSacrifice];
        (uint256 amountETHBase,) = getAmountETHBase(
            memeToSacrifice, amountToSacrifice, sacrificedMeme.cycleParticipant
        );
        rewardCurrentCycle =
            _calculateReward(cycle.goal, sacrificedMeme.achieved, amountETHBase);
        if (amountETHBase > cycle.goal - sacrificedMeme.achieved) {
            uint256 amountForCurrentCycle = cycle.goal - sacrificedMeme.achieved;
            rewardCurrentCycle =
                _calculateReward(cycle.goal, sacrificedMeme.achieved, amountForCurrentCycle);
            amountETHBase -= amountForCurrentCycle;
            if (amountETHBase >= defaultGoal) {
                amountETHBase = defaultGoal * 95 / 100;
            }
            rewardNextCycle = _calculateReward(defaultGoal, 0, amountETHBase);
        }
    }

    /**
     * @notice View method returns useful amount of ETH for sacrificing this amount
     *         `amountToSacrifice` of this `memeToSacrifice` meme token now (time/action sensitive data).
     *         Useful ETH is an ETH, which is used as a base to calculate reward or buy BLOOD from Uniswap V3 Pool, amount excludes developer fee.
     * @param memeToSacrifice address of meme token from the sacrificable list.
     * @param amountToSacrifice amount of sacrificable meme token to calculate current reward for.
     * @param cycleParticipant True, if meme token is participant of current cycle.
     */
    function getAmountETHBase(
        address memeToSacrifice,
        uint256 amountToSacrifice,
        bool cycleParticipant
    )
        public
        view
        returns (uint256 amountETHBase, uint256 amountETHForSelling)
    {
        bool token0 = memeToSacrifice < weth;
        address uniV2Pool = memesUniV2Pools[memeToSacrifice];

        if (uniV2Pool == address(0)) {
            return (amountETHBase, amountETHForSelling);
        }

        (uint256 reserve0, uint256 reserve1,) = IUniswapV2Pair(uniV2Pool).getReserves();

        if (!cycleParticipant || (reserve0 == 0 || reserve1 == 0)) {
            return (amountETHBase, amountETHForSelling);
        }

        uint256 amountInWithFee = amountToSacrifice * 997;
        uint256 numerator = amountInWithFee * (token0 ? reserve1 : reserve0);
        uint256 denominator = amountInWithFee + ((token0 ? reserve0 : reserve1) * 1000);
        amountETHForSelling = numerator / denominator;
        amountETHBase = amountETHForSelling * 97 / 100;
    }

    /// @notice Returns a cycle `cycleNumber` goal denominated in BLOOD (reward) tokens.
    function getGoalInBLOOD(uint112 cycleNumber) external view returns (uint256) {
        Cycle storage cycle = cycles[cycleNumber];
        if (cycle.goal == uint112(0)) {
            return 0;
        }
        return _calculateReward(cycle.goal, 0, cycle.goal);
    }

    /**
     * @notice View method returns required amount of meme `memeToSacrifice` token
     *         to sacrifice to complete cycle.
     * @param memeToSacrifice address of meme token from the sacrificable list.
     */
    function getAmountToReachGoal(address memeToSacrifice) public view returns (uint256) {
        Cycle storage cycle = cycles[currentCycle];
        SacrificedMeme storage sacrificedMeme = cycle.sacrificedMemes[memeToSacrifice];
        if (!sacrificedMeme.cycleParticipant) {
            return 0;
        }
        bool token0 = memeToSacrifice < weth;
        address uniV2Pool = memesUniV2Pools[memeToSacrifice];
        if (uniV2Pool == address(0)) {
            return 0;
        }
        (uint256 reserve0, uint256 reserve1,) = IUniswapV2Pair(uniV2Pool).getReserves();

        if (reserve0 == 0 || reserve1 == 0) {
            return 0;
        }

        uint256 amountOut = 1 + ((cycle.goal - sacrificedMeme.achieved) * 100 / 97);
        uint256 numerator = amountOut * 1000 * (token0 ? reserve0 : reserve1);
        uint256 denominator = ((token0 ? reserve1 : reserve0) - amountOut) * 997;
        uint256 amountIn = (numerator / denominator) + 1;

        return amountIn;
    }

    /*//////////////////////////////////////////////////////////////
                  REWARD CALCULATION INTERNAL LOGIC
    //////////////////////////////////////////////////////////////*/

    /// @notice Triple LINEAR function. 3 lines - 3 sectors.
    /// sector 1: 0-5% goal range. decreasing line.
    /// sector 2: 5-95% goal range. straight line.
    /// sector 3: 95%-100% goal range. increasing line.
    /// @dev b = 95, m = 30 -> mints 96.5% - 3.5% deflation against issuancePrice.
    /// @dev rewardFactors must be divided by 10 ** 18 after multiplied by price and amount
    function _calculateTripleLinearReward(
        uint256 goal,
        uint256 achieved,
        uint256 amount,
        uint256 price,
        uint256 _b,
        uint256 _m
    )
        internal
        pure
        returns (uint256 reward)
    {
        // start and finish points can be in same or different sectors.
        uint256 startPoint = achieved * 100 / goal;
        uint256 finishPoint = (achieved + amount) * 100 / goal;

        uint256 rewardFactor;
        uint256 tempGoal = 5 * goal / 100;
        uint256 tempAmount = amount;

        if (startPoint < 5) {
            if (finishPoint >= 5) {
                // start: sector 1. finish: sector 2, sector 3.
                // fully filled 0-5% goal range, add reward for that, move to next sector.
                tempAmount = tempGoal - achieved;
                amount -= tempAmount;
                rewardFactor = (_b + _m) * 10 ** 16
                    - (_m * 10 ** 16 * (achieved + (achieved + tempAmount)) / tempGoal)
                        / uint256(2);
                reward += rewardFactor * tempAmount * price / 10 ** 18;
                achieved += tempAmount;
            } else {
                // start: sector 1. finish: sector 1.
                // return reward for a partially filling 0-5% goal range.
                rewardFactor = (_b + _m) * 10 ** 16
                    - (_m * 10 ** 16 * (achieved + (achieved + tempAmount)) / tempGoal)
                        / uint256(2);
                reward += rewardFactor * tempAmount * price / 10 ** 18;
                return reward;
            }
        }

        if (finishPoint < 95) {
            // start: sector 1, sector 2. finish: sector 2.
            // return reward for a partially filling 5-95% goal range.
            rewardFactor = _b * 10 ** 16;
            reward += rewardFactor * amount * price / 10 ** 18;
            return reward;
        } else if (startPoint < 95) {
            // start: sector 1, sector 2. finish: sector 3.
            // fully filled 5-95% goal range, add reward, move to next sector.
            tempGoal = 95 * goal / 100;
            tempAmount = tempGoal - achieved;
            amount -= tempAmount;
            achieved += tempAmount;
            rewardFactor = _b * 10 ** 16;
            reward += rewardFactor * tempAmount * price / 10 ** 18;
        }
        // start: sector 1, sector 2, sector 3. finish: sector 3.
        // fully or partially fill 95%-100% goal range, add reward.
        achieved -= 95 * goal / 100;
        tempGoal = 5 * goal / 100;
        rewardFactor = _b * 10 ** 16
            + (_m * 10 ** 16 * (achieved + (achieved + amount)) / tempGoal) / uint256(2);
        reward += rewardFactor * amount * price / 10 ** 18;
    }

    /*//////////////////////////////////////////////////////////////
                                CALLBACKS
    //////////////////////////////////////////////////////////////*/

    function uniswapV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata _data
    )
        external
    {
        if (amount0Delta <= 0 && amount1Delta <= 0) {
            revert SwapWithinZeroLiquidity();
        }
        if (msg.sender != uniV3Pool) {
            revert SwapCallbackCanBeCalledOnlyByPool();
        }

        (uint256 ethIn, uint256 minBDLOut) = abi.decode(_data, (uint256, uint256));
        (bool isExactInput, uint256 amountToPay, uint256 amountReceived) = amount0Delta > 0
            ? (weth < address(bloodline), uint256(amount0Delta), uint256(-amount1Delta))
            : (address(bloodline) < weth, uint256(amount1Delta), uint256(-amount0Delta));

        // check input amount
        if (!isExactInput || amountToPay != ethIn) {
            revert NotExactInput();
        }
        // check the output amount
        if (amountReceived < minBDLOut) {
            revert TooLittleReceived();
        }
        // transfer eth to univ3 pool
        ILiquidityOwner(liquidityOwner).payWETHToUniswapPool(msg.sender, amountToPay);
    }
}

// File: src/Bloodline.sol



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

import {ERC20} from "solmate/tokens/ERC20.sol";
import "@uniswap/v3-periphery/contracts/interfaces/IPoolInitializer.sol";

/// Permission to mint tokens is not exist.
error NotAllowedToMint();

/**
 * @title Bloodline - an ERC20 token that is allowed to be minted only by `rewardLocker`.
 */
contract Bloodline is ERC20 {
    /// @notice Contract which is allowed to mint tokens.
    address public rewardLocker;
    /// @notice Uniswap V3 pool with 1% fee, underlying tokens: WETH and this.
    address public uniV3Pool;

    /**
     * @notice Constructor initialize solmate ERC20 and deploys Uniswap V3 pool.
     * @param _weth address of WETH9 contract.
     * @param _nfPositionManager address of NonfungiblePositionManager (Uniswap V3) contract.
     * @param _sqrtPricesX96 an array of 2 initial prices for Uniswap V3 pool:
     *                       first price is picked if WETH9 is token1,
     *                       second price is picked if WETH9 is token0.
     */
    constructor(
        address _rewardLocker,
        address _weth,
        address _nfPositionManager,
        uint160[2] memory _sqrtPricesX96
    )
        ERC20("Bloodline", "BLOOD", uint8(18))
    {
        rewardLocker = _rewardLocker;
        if (address(this) < _weth) {
            uniV3Pool = IPoolInitializer(_nfPositionManager).createAndInitializePoolIfNecessary(
                address(this), _weth, uint24(10_000), _sqrtPricesX96[0]
            );
        } else {
            uniV3Pool = IPoolInitializer(_nfPositionManager).createAndInitializePoolIfNecessary(
                _weth, address(this), uint24(10_000), _sqrtPricesX96[1]
            );
        }
        require(uniV3Pool != address(0));
    }

    /**
     * @notice Method mints tokens.
     * @dev Method could be called only by `rewardLocker`.
     * @param account address which should receive newly minted tokens.
     * @param amount of tokens which should be minted.
     */
    function mintBloodline(address account, uint256 amount) external {
        if (msg.sender != rewardLocker) {
            revert NotAllowedToMint();
        }
        _mint(account, amount);
    }

    /**
     * @notice Method burns tokens.
     * @param amount of tokens which should be burned.
     */
    function burn(uint256 amount) external returns (bool) {
        _burn(msg.sender, amount);
        return true;
    }
}

// File: src/interfaces/IERC20.sol



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

interface IERC20 {
    /**
     * @dev Burns the `value` of tokens in existence.
     */
    function burn(uint256 value) external;

    /**
     * @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 `recipient`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address recipient, 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 `sender` to `recipient` 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 sender,
        address recipient,
        uint256 amount
    )
        external
        returns (bool);

    /**
     * @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);

    /**
     * @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);
}

// File: src/interfaces/ILiquidityOwner.sol



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

interface ILiquidityOwner {
    function payWETHToUniswapPool(address uniswapPool, uint256 extraAmount) external;
    function payDeveloperFee(uint256 developerFee) external;
    function provideLiquidity(uint112 collectedEthInCycle)
        external
        returns (uint256 issuancePrice);
}

// File: src/interfaces/IRewardLocker.sol



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

interface IRewardLocker {
    function init(
        address _memeAltar,
        address _bloodline,
        address _devLiquidityHolder
    )
        external;
    function registerReward(
        address user,
        address sacrificedToken,
        uint256 reward
    )
        external
        returns (bool);
    function registerNextCycle(
        uint256 cycleIndex,
        address[] calldata sacrificableTokens
    )
        external
        returns (bool);
    function registerCycleCompleted(
        uint256 cycleIndex,
        address winnerToken
    )
        external
        returns (bool);
}

// File: lib/v3-core/contracts/interfaces/IUniswapV3Pool.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {IUniswapV3PoolImmutables} from './pool/IUniswapV3PoolImmutables.sol';
import {IUniswapV3PoolState} from './pool/IUniswapV3PoolState.sol';
import {IUniswapV3PoolDerivedState} from './pool/IUniswapV3PoolDerivedState.sol';
import {IUniswapV3PoolActions} from './pool/IUniswapV3PoolActions.sol';
import {IUniswapV3PoolOwnerActions} from './pool/IUniswapV3PoolOwnerActions.sol';
import {IUniswapV3PoolErrors} from './pool/IUniswapV3PoolErrors.sol';
import {IUniswapV3PoolEvents} from './pool/IUniswapV3PoolEvents.sol';

/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
    IUniswapV3PoolImmutables,
    IUniswapV3PoolState,
    IUniswapV3PoolDerivedState,
    IUniswapV3PoolActions,
    IUniswapV3PoolOwnerActions,
    IUniswapV3PoolErrors,
    IUniswapV3PoolEvents
{

}

// File: lib/v2-core/contracts/interfaces/IUniswapV2Pair.sol



pragma solidity >=0.5.0;

interface IUniswapV2Pair {
    event Approval(address indexed owner, address indexed spender, uint value);
    event Transfer(address indexed from, address indexed to, uint value);

    function name() external pure returns (string memory);
    function symbol() external pure returns (string memory);
    function decimals() external pure returns (uint8);
    function totalSupply() external view returns (uint);
    function balanceOf(address owner) external view returns (uint);
    function allowance(address owner, address spender) external view returns (uint);

    function approve(address spender, uint value) external returns (bool);
    function transfer(address to, uint value) external returns (bool);
    function transferFrom(address from, address to, uint value) external returns (bool);

    function DOMAIN_SEPARATOR() external view returns (bytes32);
    function PERMIT_TYPEHASH() external pure returns (bytes32);
    function nonces(address owner) external view returns (uint);

    function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;

    event Mint(address indexed sender, uint amount0, uint amount1);
    event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
    event Swap(
        address indexed sender,
        uint amount0In,
        uint amount1In,
        uint amount0Out,
        uint amount1Out,
        address indexed to
    );
    event Sync(uint112 reserve0, uint112 reserve1);

    function MINIMUM_LIQUIDITY() external pure returns (uint);
    function factory() external view returns (address);
    function token0() external view returns (address);
    function token1() external view returns (address);
    function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
    function price0CumulativeLast() external view returns (uint);
    function price1CumulativeLast() external view returns (uint);
    function kLast() external view returns (uint);

    function mint(address to) external returns (uint liquidity);
    function burn(address to) external returns (uint amount0, uint amount1);
    function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
    function skim(address to) external;
    function sync() external;

    function initialize(address, address) external;
}

// File: lib/solmate/src/tokens/ERC20.sol



// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
abstract contract ERC20 {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

    event Transfer(address indexed from, address indexed to, uint256 amount);

    event Approval(address indexed owner, address indexed spender, uint256 amount);

    /*//////////////////////////////////////////////////////////////
                            METADATA STORAGE
    //////////////////////////////////////////////////////////////*/

    string public name;

    string public symbol;

    uint8 public immutable decimals;

    /*//////////////////////////////////////////////////////////////
                              ERC20 STORAGE
    //////////////////////////////////////////////////////////////*/

    uint256 public totalSupply;

    mapping(address => uint256) public balanceOf;

    mapping(address => mapping(address => uint256)) public allowance;

    /*//////////////////////////////////////////////////////////////
                            EIP-2612 STORAGE
    //////////////////////////////////////////////////////////////*/

    uint256 internal immutable INITIAL_CHAIN_ID;

    bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;

    mapping(address => uint256) public nonces;

    /*//////////////////////////////////////////////////////////////
                               CONSTRUCTOR
    //////////////////////////////////////////////////////////////*/

    constructor(
        string memory _name,
        string memory _symbol,
        uint8 _decimals
    ) {
        name = _name;
        symbol = _symbol;
        decimals = _decimals;

        INITIAL_CHAIN_ID = block.chainid;
        INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
    }

    /*//////////////////////////////////////////////////////////////
                               ERC20 LOGIC
    //////////////////////////////////////////////////////////////*/

    function approve(address spender, uint256 amount) public virtual returns (bool) {
        allowance[msg.sender][spender] = amount;

        emit Approval(msg.sender, spender, amount);

        return true;
    }

    function transfer(address to, uint256 amount) public virtual returns (bool) {
        balanceOf[msg.sender] -= amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(msg.sender, to, amount);

        return true;
    }

    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual returns (bool) {
        uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.

        if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;

        balanceOf[from] -= amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(from, to, amount);

        return true;
    }

    /*//////////////////////////////////////////////////////////////
                             EIP-2612 LOGIC
    //////////////////////////////////////////////////////////////*/

    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual {
        require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");

        // Unchecked because the only math done is incrementing
        // the owner's nonce which cannot realistically overflow.
        unchecked {
            address recoveredAddress = ecrecover(
                keccak256(
                    abi.encodePacked(
                        "\x19\x01",
                        DOMAIN_SEPARATOR(),
                        keccak256(
                            abi.encode(
                                keccak256(
                                    "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
                                ),
                                owner,
                                spender,
                                value,
                                nonces[owner]++,
                                deadline
                            )
                        )
                    )
                ),
                v,
                r,
                s
            );

            require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");

            allowance[recoveredAddress][spender] = value;
        }

        emit Approval(owner, spender, value);
    }

    function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
        return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
    }

    function computeDomainSeparator() internal view virtual returns (bytes32) {
        return
            keccak256(
                abi.encode(
                    keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                    keccak256(bytes(name)),
                    keccak256("1"),
                    block.chainid,
                    address(this)
                )
            );
    }

    /*//////////////////////////////////////////////////////////////
                        INTERNAL MINT/BURN LOGIC
    //////////////////////////////////////////////////////////////*/

    function _mint(address to, uint256 amount) internal virtual {
        totalSupply += amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(address(0), to, amount);
    }

    function _burn(address from, uint256 amount) internal virtual {
        balanceOf[from] -= amount;

        // Cannot underflow because a user's balance
        // will never be larger than the total supply.
        unchecked {
            totalSupply -= amount;
        }

        emit Transfer(from, address(0), amount);
    }
}

// File: lib/v3-periphery/contracts/interfaces/IPoolInitializer.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;

/// @title Creates and initializes V3 Pools
/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that
/// require the pool to exist.
interface IPoolInitializer {
    /// @notice Creates a new pool if it does not exist, then initializes if not initialized
    /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool
    /// @param token0 The contract address of token0 of the pool
    /// @param token1 The contract address of token1 of the pool
    /// @param fee The fee amount of the v3 pool for the specified token pair
    /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value
    /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary
    function createAndInitializePoolIfNecessary(
        address token0,
        address token1,
        uint24 fee,
        uint160 sqrtPriceX96
    ) external payable returns (address pool);
}

// File: lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolImmutables.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
    /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
    /// @return The contract address
    function factory() external view returns (address);

    /// @notice The first of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token0() external view returns (address);

    /// @notice The second of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token1() external view returns (address);

    /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
    /// @return The fee
    function fee() external view returns (uint24);

    /// @notice The pool tick spacing
    /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
    /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
    /// This value is an int24 to avoid casting even though it is always positive.
    /// @return The tick spacing
    function tickSpacing() external view returns (int24);

    /// @notice The maximum amount of position liquidity that can use any tick in the range
    /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
    /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
    /// @return The max amount of liquidity per tick
    function maxLiquidityPerTick() external view returns (uint128);
}

// File: lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolState.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
    /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
    /// when accessed externally.
    /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
    /// @return tick The current tick of the pool, i.e. according to the last tick transition that was run.
    /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
    /// boundary.
    /// @return observationIndex The index of the last oracle observation that was written,
    /// @return observationCardinality The current maximum number of observations stored in the pool,
    /// @return observationCardinalityNext The next maximum number of observations, to be updated when the observation.
    /// @return feeProtocol The protocol fee for both tokens of the pool.
    /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
    /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
    /// unlocked Whether the pool is currently locked to reentrancy
    function slot0()
        external
        view
        returns (
            uint160 sqrtPriceX96,
            int24 tick,
            uint16 observationIndex,
            uint16 observationCardinality,
            uint16 observationCardinalityNext,
            uint8 feeProtocol,
            bool unlocked
        );

    /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
    /// @dev This value can overflow the uint256
    function feeGrowthGlobal0X128() external view returns (uint256);

    /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
    /// @dev This value can overflow the uint256
    function feeGrowthGlobal1X128() external view returns (uint256);

    /// @notice The amounts of token0 and token1 that are owed to the protocol
    /// @dev Protocol fees will never exceed uint128 max in either token
    function protocolFees() external view returns (uint128 token0, uint128 token1);

    /// @notice The currently in range liquidity available to the pool
    /// @dev This value has no relationship to the total liquidity across all ticks
    /// @return The liquidity at the current price of the pool
    function liquidity() external view returns (uint128);

    /// @notice Look up information about a specific tick in the pool
    /// @param tick The tick to look up
    /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
    /// tick upper
    /// @return liquidityNet how much liquidity changes when the pool price crosses the tick,
    /// @return feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
    /// @return feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
    /// @return tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
    /// @return secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
    /// @return secondsOutside the seconds spent on the other side of the tick from the current tick,
    /// @return initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
    /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
    /// In addition, these values are only relative and must be used only in comparison to previous snapshots for
    /// a specific position.
    function ticks(int24 tick)
        external
        view
        returns (
            uint128 liquidityGross,
            int128 liquidityNet,
            uint256 feeGrowthOutside0X128,
            uint256 feeGrowthOutside1X128,
            int56 tickCumulativeOutside,
            uint160 secondsPerLiquidityOutsideX128,
            uint32 secondsOutside,
            bool initialized
        );

    /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
    function tickBitmap(int16 wordPosition) external view returns (uint256);

    /// @notice Returns the information about a position by the position's key
    /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
    /// @return liquidity The amount of liquidity in the position,
    /// @return feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
    /// @return feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
    /// @return tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
    /// @return tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
    function positions(bytes32 key)
        external
        view
        returns (
            uint128 liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );

    /// @notice Returns data about a specific observation index
    /// @param index The element of the observations array to fetch
    /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
    /// ago, rather than at a specific index in the array.
    /// @return blockTimestamp The timestamp of the observation,
    /// @return tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
    /// @return secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
    /// @return initialized whether the observation has been initialized and the values are safe to use
    function observations(uint256 index)
        external
        view
        returns (
            uint32 blockTimestamp,
            int56 tickCumulative,
            uint160 secondsPerLiquidityCumulativeX128,
            bool initialized
        );
}

// File: lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolDerivedState.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
    /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
    /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
    /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
    /// you must call it with secondsAgos = [3600, 0].
    /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
    /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
    /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
    /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
    /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
    /// timestamp
    function observe(uint32[] calldata secondsAgos)
        external
        view
        returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);

    /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
    /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
    /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
    /// snapshot is taken and the second snapshot is taken.
    /// @param tickLower The lower tick of the range
    /// @param tickUpper The upper tick of the range
    /// @return tickCumulativeInside The snapshot of the tick accumulator for the range
    /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
    /// @return secondsInside The snapshot of seconds per liquidity for the range
    function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
        external
        view
        returns (
            int56 tickCumulativeInside,
            uint160 secondsPerLiquidityInsideX128,
            uint32 secondsInside
        );
}

// File: lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolActions.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
    /// @notice Sets the initial price for the pool
    /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
    /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
    function initialize(uint160 sqrtPriceX96) external;

    /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
    /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
    /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
    /// on tickLower, tickUpper, the amount of liquidity, and the current price.
    /// @param recipient The address for which the liquidity will be created
    /// @param tickLower The lower tick of the position in which to add liquidity
    /// @param tickUpper The upper tick of the position in which to add liquidity
    /// @param amount The amount of liquidity to mint
    /// @param data Any data that should be passed through to the callback
    /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
    /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
    function mint(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount,
        bytes calldata data
    ) external returns (uint256 amount0, uint256 amount1);

    /// @notice Collects tokens owed to a position
    /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
    /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
    /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
    /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
    /// @param recipient The address which should receive the fees collected
    /// @param tickLower The lower tick of the position for which to collect fees
    /// @param tickUpper The upper tick of the position for which to collect fees
    /// @param amount0Requested How much token0 should be withdrawn from the fees owed
    /// @param amount1Requested How much token1 should be withdrawn from the fees owed
    /// @return amount0 The amount of fees collected in token0
    /// @return amount1 The amount of fees collected in token1
    function collect(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);

    /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
    /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
    /// @dev Fees must be collected separately via a call to #collect
    /// @param tickLower The lower tick of the position for which to burn liquidity
    /// @param tickUpper The upper tick of the position for which to burn liquidity
    /// @param amount How much liquidity to burn
    /// @return amount0 The amount of token0 sent to the recipient
    /// @return amount1 The amount of token1 sent to the recipient
    function burn(
        int24 tickLower,
        int24 tickUpper,
        uint128 amount
    ) external returns (uint256 amount0, uint256 amount1);

    /// @notice Swap token0 for token1, or token1 for token0
    /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
    /// @param recipient The address to receive the output of the swap
    /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
    /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
    /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
    /// value after the swap. If one for zero, the price cannot be greater than this value after the swap
    /// @param data Any data to be passed through to the callback
    /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
    /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);

    /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
    /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
    /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
    /// with 0 amount{0,1} and sending the donation amount(s) from the callback
    /// @param recipient The address which will receive the token0 and token1 amounts
    /// @param amount0 The amount of token0 to send
    /// @param amount1 The amount of token1 to send
    /// @param data Any data to be passed through to the callback
    function flash(
        address recipient,
        uint256 amount0,
        uint256 amount1,
        bytes calldata data
    ) external;

    /// @notice Increase the maximum number of price and liquidity observations that this pool will store
    /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
    /// the input observationCardinalityNext.
    /// @param observationCardinalityNext The desired minimum number of observations for the pool to store
    function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}

// File: lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolOwnerActions.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
    /// @notice Set the denominator of the protocol's % share of the fees
    /// @param feeProtocol0 new protocol fee for token0 of the pool
    /// @param feeProtocol1 new protocol fee for token1 of the pool
    function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;

    /// @notice Collect the protocol fee accrued to the pool
    /// @param recipient The address to which collected protocol fees should be sent
    /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
    /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
    /// @return amount0 The protocol fee collected in token0
    /// @return amount1 The protocol fee collected in token1
    function collectProtocol(
        address recipient,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);
}

// File: lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolErrors.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Errors emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolErrors {
    error LOK();
    error TLU();
    error TLM();
    error TUM();
    error AI();
    error M0();
    error M1();
    error AS();
    error IIA();
    error L();
    error F0();
    error F1();
}

// File: lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolEvents.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
    /// @notice Emitted exactly once by a pool when #initialize is first called on the pool
    /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
    /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
    /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
    event Initialize(uint160 sqrtPriceX96, int24 tick);

    /// @notice Emitted when liquidity is minted for a given position
    /// @param sender The address that minted the liquidity
    /// @param owner The owner of the position and recipient of any minted liquidity
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount The amount of liquidity minted to the position range
    /// @param amount0 How much token0 was required for the minted liquidity
    /// @param amount1 How much token1 was required for the minted liquidity
    event Mint(
        address sender,
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Emitted when fees are collected by the owner of a position
    /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
    /// @param owner The owner of the position for which fees are collected
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount0 The amount of token0 fees collected
    /// @param amount1 The amount of token1 fees collected
    event Collect(
        address indexed owner,
        address recipient,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount0,
        uint128 amount1
    );

    /// @notice Emitted when a position's liquidity is removed
    /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
    /// @param owner The owner of the position for which liquidity is removed
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount The amount of liquidity to remove
    /// @param amount0 The amount of token0 withdrawn
    /// @param amount1 The amount of token1 withdrawn
    event Burn(
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Emitted by the pool for any swaps between token0 and token1
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param recipient The address that received the output of the swap
    /// @param amount0 The delta of the token0 balance of the pool
    /// @param amount1 The delta of the token1 balance of the pool
    /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
    /// @param liquidity The liquidity of the pool after the swap
    /// @param tick The log base 1.0001 of price of the pool after the swap
    event Swap(
        address indexed sender,
        address indexed recipient,
        int256 amount0,
        int256 amount1,
        uint160 sqrtPriceX96,
        uint128 liquidity,
        int24 tick
    );

    /// @notice Emitted by the pool for any flashes of token0/token1
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param recipient The address that received the tokens from flash
    /// @param amount0 The amount of token0 that was flashed
    /// @param amount1 The amount of token1 that was flashed
    /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
    /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
    event Flash(
        address indexed sender,
        address indexed recipient,
        uint256 amount0,
        uint256 amount1,
        uint256 paid0,
        uint256 paid1
    );

    /// @notice Emitted by the pool for increases to the number of observations that can be stored
    /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
    /// just before a mint/swap/burn.
    /// @param observationCardinalityNextOld The previous value of the next observation cardinality
    /// @param observationCardinalityNextNew The updated value of the next observation cardinality
    event IncreaseObservationCardinalityNext(
        uint16 observationCardinalityNextOld,
        uint16 observationCardinalityNextNew
    );

    /// @notice Emitted when the protocol fee is changed by the pool
    /// @param feeProtocol0Old The previous value of the token0 protocol fee
    /// @param feeProtocol1Old The previous value of the token1 protocol fee
    /// @param feeProtocol0New The updated value of the token0 protocol fee
    /// @param feeProtocol1New The updated value of the token1 protocol fee
    event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);

    /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
    /// @param sender The address that collects the protocol fees
    /// @param recipient The address that receives the collected protocol fees
    /// @param amount0 The amount of token0 protocol fees that is withdrawn
    /// @param amount0 The amount of token1 protocol fees that is withdrawn
    event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}