// File: src/RaceManager.sol



// SPDX-License-Identifier: UNLICENSED

pragma solidity >=0.8.18;

import "solmate/auth/Owned.sol";
import "solmate/tokens/ERC20.sol";
import "solmate/utils/SafeTransferLib.sol";
import "./interfaces/IHotWheels.sol";

// Errors
error NoActiveRace();
error ActiveRace();
error RaceDataMismatch();
error BettingStillActive();
error AlreadyPlacedBet();
error AlreadyClaimed();
error DidntParticipate();
error DidntWin();
error InvalidLane();
error MissingTokenApproval();
error NotEnoughTokens();
error BettingEndedAlready();
error InvalidRaceId();
error InvalidToken();
error InvalidHouse();
error NotEnoughInPool();

// Data structures
struct BetData {
    bool claimed;
    uint8 lane;
    uint256 amount;
}

struct RaceData {
    bool active;
    bool bettingActive;
    bool houseWithdrew;
    uint8 winningLane;
    uint256 totalBet;
}

contract RaceManager is Owned {
    // Constants
    IHotWheels public immutable token;
    address public immutable house;

    // Race data
    uint32 public currentRace = 0;
    uint32 public lastRace = 0;
    RaceData[] public raceData;

    // Betting data
    mapping(uint32 => mapping(address => BetData)) public betData;
    mapping(uint32 => address[]) public bettors;
    mapping(address => uint32) public totalBetsMade;
    mapping(uint32 => mapping(uint8 => uint256)) public betPerRacePerLane;

    // Winnings data
    uint256 public totalAmountWon = 0;

    // Events
    event RaceStarted(uint32 raceId);
    event BetAdded(uint32 raceId, address addr, uint8 lane, uint256 amount);
    event BettingEnded(uint32 raceId);
    event RaceEnded(uint32 raceId, uint8 winningLane);

    // Modifiers
    modifier needsActiveRace() {
        if (currentRace == 0) revert NoActiveRace();
        _;
    }

    modifier noActiveRace() {
        if (currentRace > 0) revert ActiveRace();
        _;
    }

    // Functionality
    constructor(address tokenContract, address houseWallet) Owned(msg.sender) {
        if (tokenContract == address(0x0)) revert InvalidToken();
        if (houseWallet == address(0x0)) revert InvalidHouse();

        // Initialize bettors to fix slither uninitialized-state
        bettors[0] = [address(0)];

        token = IHotWheels(payable(tokenContract));
        house = houseWallet;
    }

    receive() external payable {}
    fallback() external payable {}

    function betRace(uint8 lane, uint256 amount) external needsActiveRace {
        if (token.balanceOf(msg.sender) < amount) revert NotEnoughTokens();
        if (token.allowance(msg.sender, address(this)) < amount) revert MissingTokenApproval();
        if (lane == 0 || lane > 6) revert InvalidLane();

        address bettor = msg.sender;
        uint32 raceId = currentRace;

        address[] storage raceBettors = bettors[raceId - 1];
        BetData storage data = betData[raceId - 1][bettor];
        RaceData storage race = raceData[raceId - 1];

        if (!race.bettingActive) revert BettingEndedAlready();
        if (data.lane > 0 || data.amount > 0) revert AlreadyPlacedBet();

        betData[raceId - 1][bettor] = BetData(false, lane, amount);
        betPerRacePerLane[raceId - 1][lane] += amount;
        race.totalBet += amount;

        totalBetsMade[msg.sender] += 1;
        raceBettors.push(msg.sender);

        SafeTransferLib.safeTransferFrom(ERC20(address(token)), bettor, address(this), amount);

        emit BetAdded(raceId, bettor, lane, amount);
    }

    function claimWinnings(uint32 raceId) public {
        if (raceId > raceData.length) revert InvalidRaceId();

        address bettor = msg.sender;
        BetData storage data = betData[raceId - 1][bettor];
        RaceData storage race = raceData[raceId - 1];

        uint8 lane = data.lane;

        if (data.claimed) revert AlreadyClaimed();
        if (data.amount == 0) revert DidntParticipate();
        if (data.lane != race.winningLane) revert DidntWin();

        data.claimed = true;

        uint256 totalWinBet = betPerRacePerLane[raceId - 1][lane];
        uint256 totalLoseBet = 0;
        for (uint8 otherLane = 1; otherLane <= 6; otherLane++) {
            if (otherLane == lane) continue;

            totalLoseBet += betPerRacePerLane[raceId - 1][otherLane];
        }

        uint256 winnings = _calculateWinnings(data.amount, totalLoseBet, totalWinBet);

        // This only triggers costly-loop warning if called from claimAllWinnings
        //slither-disable-next-line costly-loop
        totalAmountWon += winnings;

        // pay out tokens for race
        SafeTransferLib.safeTransfer(ERC20(address(token)), bettor, winnings);
    }

    function claimAllWinnings() external {
        address bettor = msg.sender;
        for (uint32 raceId = 1; raceId <= raceData.length; raceId++) {
            RaceData storage race = raceData[raceId - 1];
            BetData storage data = betData[raceId - 1][bettor];

            if (data.amount == 0) continue;
            if (data.claimed) continue;
            if (data.lane != race.winningLane) continue;

            claimWinnings(raceId);
        }
    }

    // Admin functions
    function startRace() external onlyOwner noActiveRace {
        currentRace = lastRace + 1;

        uint32 raceId = currentRace;

        raceData.push(RaceData(true, true, false, 0, 0));

        if (raceData.length != raceId) revert RaceDataMismatch();

        emit RaceStarted(raceId);
    }

    function endBetting() external onlyOwner needsActiveRace {
        uint32 raceId = currentRace;
        RaceData storage data = raceData[raceId - 1];

        if (!data.bettingActive) revert BettingEndedAlready();

        data.bettingActive = false;

        emit BettingEnded(raceId);
    }

    function endRace(uint8 winningLane) external onlyOwner needsActiveRace {
        uint32 raceId = currentRace;
        RaceData storage data = raceData[raceId - 1];

        if (data.bettingActive) revert BettingStillActive();

        data.active = false;
        data.winningLane = winningLane;
        lastRace = raceId;
        currentRace = 0;

        emit RaceEnded(raceId, winningLane);
    }

    function sweep() external onlyOwner noActiveRace {
        // Transfer all funds into the house wallet
        SafeTransferLib.safeTransfer(ERC20(address(token)), house, token.balanceOf(address(this)));
        // if for some reason there are native tokens in the contract
        SafeTransferLib.safeTransferETH(house, address(this).balance);
    }

    function swapTokensForEth(address wallet, uint256 tokenAmount) private {
        // generate the uniswap pair path of token -> weth
        address[] memory path = new address[](2);
        path[0] = address(token);
        path[1] = token.uniswapV2Router().WETH();
        token.approve(address(token.uniswapV2Router()), tokenAmount);
        // make the swap
        token.uniswapV2Router().swapExactTokensForETHSupportingFeeOnTransferTokens(
            tokenAmount,
            0, // accept any amount of ETH
            path,
            wallet,
            block.timestamp
        );
    }

    // Withdraw house winnings, this is going to be expensive.
    function houseWithdraw(uint32 raceId) external onlyOwner {
        if (raceId > raceData.length) revert InvalidRaceId();

        RaceData storage race = raceData[raceId - 1];
        if (race.active) revert ActiveRace();
        if (race.houseWithdrew) revert AlreadyClaimed();

        uint8 lane = race.winningLane;
        uint256 totalLoseBet = 0;
        for (uint8 otherLane = 1; otherLane <= 6; otherLane++) {
            if (otherLane == lane) continue;

            totalLoseBet += betPerRacePerLane[raceId - 1][otherLane];
        }

        uint256 houseWinnings = totalLoseBet / 10;

        swapTokensForEth(house, houseWinnings);

        race.houseWithdrew = true;
    }

    // View functions
    function unclaimedWinnings(address bettor) public view returns (uint32[] memory) {
        uint32[] memory unclaimed;
        uint256 length = raceData.length;

        for (uint32 raceId; raceId < length; raceId++) {
            BetData storage data = betData[raceId][bettor];
            RaceData storage race = raceData[raceId];

            if (race.active) continue;
            if (race.winningLane != data.lane) continue;
            if (data.amount == 0) continue;
            if (data.claimed) continue;

            unclaimed[unclaimed.length] = raceId;
        }

        return unclaimed;
    }

    function getUnclaimedBalance(address bettor) public view returns (uint256) {
        uint256 unclaimed = 0;
        uint256 length = raceData.length;

        for (uint32 raceId; raceId < length; raceId++) {
            BetData storage data = betData[raceId][bettor];
            RaceData storage race = raceData[raceId];

            uint8 lane = data.lane;

            if (race.active) continue;
            if (race.winningLane != lane) continue;
            if (data.amount == 0) continue;
            if (data.claimed) continue;

            uint256 totalWinBet = betPerRacePerLane[raceId][lane];
            uint256 totalLoseBet = 0;
            for (uint8 otherLane = 1; otherLane <= 6; otherLane++) {
                if (otherLane == lane) continue;

                totalLoseBet += betPerRacePerLane[raceId][otherLane];
            }

            unclaimed += _calculateWinnings(data.amount, totalLoseBet, totalWinBet);
        }

        return unclaimed;
    }

    function participatedInRaces(address bettor) public view returns (uint32[] memory) {
        uint32 counter = 0;
        uint32[] memory participated = new uint32[](totalBetsMade[bettor]);
        uint256 length = raceData.length;

        for (uint32 raceId; raceId < length; raceId++) {
            BetData storage data = betData[raceId][bettor];

            if (data.amount == 0) continue;

            participated[counter] = raceId;
            counter++;
        }

        return participated;
    }

    function _totalRaces() public view returns (uint256) {
        uint256 racesComplete = raceData.length;
        if (currentRace > 0) racesComplete -= 1;

        return racesComplete;
    }

    function getRaceBets(uint32 index) public view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
        return (
            betPerRacePerLane[index][1],
            betPerRacePerLane[index][2],
            betPerRacePerLane[index][3],
            betPerRacePerLane[index][4],
            betPerRacePerLane[index][5],
            betPerRacePerLane[index][6]
        );
    }

    // Pure functions
    function _calculateWinnings(uint256 amount, uint256 totalLoseBet, uint256 totalWinBet)
        internal
        pure
        returns (uint256)
    {
        uint256 winAmount = 0;
        if (totalLoseBet > 0) {
            uint256 houseTax = totalLoseBet / 10; // Deduct from winnings 10% for house tax
            winAmount = (amount * (totalLoseBet - houseTax)) / totalWinBet;
        }

        return amount + winAmount;
    }
}

// File: lib/solmate/src/auth/Owned.sol



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

/// @notice Simple single owner authorization mixin.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Owned.sol)
abstract contract Owned {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

    event OwnershipTransferred(address indexed user, address indexed newOwner);

    /*//////////////////////////////////////////////////////////////
                            OWNERSHIP STORAGE
    //////////////////////////////////////////////////////////////*/

    address public owner;

    modifier onlyOwner() virtual {
        require(msg.sender == owner, "UNAUTHORIZED");

        _;
    }

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

    constructor(address _owner) {
        owner = _owner;

        emit OwnershipTransferred(address(0), _owner);
    }

    /*//////////////////////////////////////////////////////////////
                             OWNERSHIP LOGIC
    //////////////////////////////////////////////////////////////*/

    function transferOwnership(address newOwner) public virtual onlyOwner {
        owner = newOwner;

        emit OwnershipTransferred(msg.sender, newOwner);
    }
}

// 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/solmate/src/utils/SafeTransferLib.sol



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

import {ERC20} from "../tokens/ERC20.sol";

/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
/// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.
library SafeTransferLib {
    /*//////////////////////////////////////////////////////////////
                             ETH OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function safeTransferETH(address to, uint256 amount) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Transfer the ETH and store if it succeeded or not.
            success := call(gas(), to, amount, 0, 0, 0, 0)
        }

        require(success, "ETH_TRANSFER_FAILED");
    }

    /*//////////////////////////////////////////////////////////////
                            ERC20 OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function safeTransferFrom(
        ERC20 token,
        address from,
        address to,
        uint256 amount
    ) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "from" argument.
            mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
            mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.

            success := and(
                // Set success to whether the call reverted, if not we check it either
                // returned exactly 1 (can't just be non-zero data), or had no return data.
                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                // We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.
                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                // Counterintuitively, this call must be positioned second to the or() call in the
                // surrounding and() call or else returndatasize() will be zero during the computation.
                call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)
            )
        }

        require(success, "TRANSFER_FROM_FAILED");
    }

    function safeTransfer(
        ERC20 token,
        address to,
        uint256 amount
    ) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
            mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.

            success := and(
                // Set success to whether the call reverted, if not we check it either
                // returned exactly 1 (can't just be non-zero data), or had no return data.
                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                // Counterintuitively, this call must be positioned second to the or() call in the
                // surrounding and() call or else returndatasize() will be zero during the computation.
                call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
            )
        }

        require(success, "TRANSFER_FAILED");
    }

    function safeApprove(
        ERC20 token,
        address to,
        uint256 amount
    ) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
            mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.

            success := and(
                // Set success to whether the call reverted, if not we check it either
                // returned exactly 1 (can't just be non-zero data), or had no return data.
                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                // Counterintuitively, this call must be positioned second to the or() call in the
                // surrounding and() call or else returndatasize() will be zero during the computation.
                call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
            )
        }

        require(success, "APPROVE_FAILED");
    }
}

// File: src/interfaces/IHotWheels.sol



// SPDX-License-Identifier: UNLICENSED

pragma solidity >=0.8.18;
pragma abicoder v2;

import "./IUniswapV2Factory.sol";
import "./IUniswapV2Pair.sol";
import "./IUniswapV2Router.sol";

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

    function totalSupply() external view returns (uint256);
    function balanceOf(address account) external view returns (uint256);
    function transfer(address to, uint256 value) external returns (bool);
    function allowance(address owner, address spender) external view returns (uint256);
    function approve(address spender, uint256 value) external returns (bool);
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

interface IHotWheels is IERC20 {
    function uniswapV2Router() external view returns (IUniswapV2Router02);
}

// File: src/interfaces/IUniswapV2Factory.sol



pragma solidity >=0.8.18;

interface IUniswapV2Factory {
    event PairCreated(address indexed token0, address indexed token1, address pair, uint256);

    function feeTo() external view returns (address);
    function feeToSetter() external view returns (address);

    function getPair(address tokenA, address tokenB) external view returns (address pair);
    function allPairs(uint256) external view returns (address pair);
    function allPairsLength() external view returns (uint256);

    function createPair(address tokenA, address tokenB) external returns (address pair);

    function setFeeTo(address) external;
    function setFeeToSetter(address) external;
}

// File: src/interfaces/IUniswapV2Pair.sol



pragma solidity >=0.8.18;

interface IUniswapV2Pair {
    event Approval(address indexed owner, address indexed spender, uint256 value);
    event Transfer(address indexed from, address indexed to, uint256 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 (uint256);
    function balanceOf(address owner) external view returns (uint256);
    function allowance(address owner, address spender) external view returns (uint256);

    function approve(address spender, uint256 value) external returns (bool);
    function transfer(address to, uint256 value) external returns (bool);
    function transferFrom(address from, address to, uint256 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 (uint256);

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

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

    function MINIMUM_LIQUIDITY() external pure returns (uint256);
    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 (uint256);
    function price1CumulativeLast() external view returns (uint256);
    function kLast() external view returns (uint256);

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

    function initialize(address, address) external;
}

// File: src/interfaces/IUniswapV2Router.sol



pragma solidity >=0.8.18;

interface IUniswapV2Router01 {
    function factory() external pure returns (address);
    function WETH() external pure returns (address);

    function addLiquidity(
        address tokenA,
        address tokenB,
        uint256 amountADesired,
        uint256 amountBDesired,
        uint256 amountAMin,
        uint256 amountBMin,
        address to,
        uint256 deadline
    ) external returns (uint256 amountA, uint256 amountB, uint256 liquidity);
    function addLiquidityETH(
        address token,
        uint256 amountTokenDesired,
        uint256 amountTokenMin,
        uint256 amountETHMin,
        address to,
        uint256 deadline
    ) external payable returns (uint256 amountToken, uint256 amountETH, uint256 liquidity);
    function removeLiquidity(
        address tokenA,
        address tokenB,
        uint256 liquidity,
        uint256 amountAMin,
        uint256 amountBMin,
        address to,
        uint256 deadline
    ) external returns (uint256 amountA, uint256 amountB);
    function removeLiquidityETH(
        address token,
        uint256 liquidity,
        uint256 amountTokenMin,
        uint256 amountETHMin,
        address to,
        uint256 deadline
    ) external returns (uint256 amountToken, uint256 amountETH);
    function removeLiquidityWithPermit(
        address tokenA,
        address tokenB,
        uint256 liquidity,
        uint256 amountAMin,
        uint256 amountBMin,
        address to,
        uint256 deadline,
        bool approveMax,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external returns (uint256 amountA, uint256 amountB);
    function removeLiquidityETHWithPermit(
        address token,
        uint256 liquidity,
        uint256 amountTokenMin,
        uint256 amountETHMin,
        address to,
        uint256 deadline,
        bool approveMax,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external returns (uint256 amountToken, uint256 amountETH);
    function swapExactTokensForTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);
    function swapTokensForExactTokens(
        uint256 amountOut,
        uint256 amountInMax,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);
    function swapExactETHForTokens(uint256 amountOutMin, address[] calldata path, address to, uint256 deadline)
        external
        payable
        returns (uint256[] memory amounts);
    function swapTokensForExactETH(
        uint256 amountOut,
        uint256 amountInMax,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);
    function swapExactTokensForETH(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);
    function swapETHForExactTokens(uint256 amountOut, address[] calldata path, address to, uint256 deadline)
        external
        payable
        returns (uint256[] memory amounts);

    function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) external pure returns (uint256 amountB);
    function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut)
        external
        pure
        returns (uint256 amountOut);
    function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut)
        external
        pure
        returns (uint256 amountIn);
    function getAmountsOut(uint256 amountIn, address[] calldata path)
        external
        view
        returns (uint256[] memory amounts);
    function getAmountsIn(uint256 amountOut, address[] calldata path)
        external
        view
        returns (uint256[] memory amounts);
}

interface IUniswapV2Router02 is IUniswapV2Router01 {
    function removeLiquidityETHSupportingFeeOnTransferTokens(
        address token,
        uint256 liquidity,
        uint256 amountTokenMin,
        uint256 amountETHMin,
        address to,
        uint256 deadline
    ) external returns (uint256 amountETH);
    function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
        address token,
        uint256 liquidity,
        uint256 amountTokenMin,
        uint256 amountETHMin,
        address to,
        uint256 deadline,
        bool approveMax,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external returns (uint256 amountETH);

    function swapExactTokensForTokensSupportingFeeOnTransferTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external;
    function swapExactETHForTokensSupportingFeeOnTransferTokens(
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external payable;
    function swapExactTokensForETHSupportingFeeOnTransferTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external;
}