// File: lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol



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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

// File: lib/solady/src/auth/Ownable.sol



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

/// @notice Simple single owner authorization mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/auth/Ownable.sol)
///
/// @dev Note:
/// This implementation does NOT auto-initialize the owner to `msg.sender`.
/// You MUST call the `_initializeOwner` in the constructor / initializer.
///
/// While the ownable portion follows
/// [EIP-173](https://eips.ethereum.org/EIPS/eip-173) for compatibility,
/// the nomenclature for the 2-step ownership handover may be unique to this codebase.
abstract contract Ownable {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The caller is not authorized to call the function.
    error Unauthorized();

    /// @dev The `newOwner` cannot be the zero address.
    error NewOwnerIsZeroAddress();

    /// @dev The `pendingOwner` does not have a valid handover request.
    error NoHandoverRequest();

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

    /// @dev The ownership is transferred from `oldOwner` to `newOwner`.
    /// This event is intentionally kept the same as OpenZeppelin's Ownable to be
    /// compatible with indexers and [EIP-173](https://eips.ethereum.org/EIPS/eip-173),
    /// despite it not being as lightweight as a single argument event.
    event OwnershipTransferred(address indexed oldOwner, address indexed newOwner);

    /// @dev An ownership handover to `pendingOwner` has been requested.
    event OwnershipHandoverRequested(address indexed pendingOwner);

    /// @dev The ownership handover to `pendingOwner` has been canceled.
    event OwnershipHandoverCanceled(address indexed pendingOwner);

    /// @dev `keccak256(bytes("OwnershipTransferred(address,address)"))`.
    uint256 private constant _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE =
        0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0;

    /// @dev `keccak256(bytes("OwnershipHandoverRequested(address)"))`.
    uint256 private constant _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE =
        0xdbf36a107da19e49527a7176a1babf963b4b0ff8cde35ee35d6cd8f1f9ac7e1d;

    /// @dev `keccak256(bytes("OwnershipHandoverCanceled(address)"))`.
    uint256 private constant _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE =
        0xfa7b8eab7da67f412cc9575ed43464468f9bfbae89d1675917346ca6d8fe3c92;

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

    /// @dev The owner slot is given by: `not(_OWNER_SLOT_NOT)`.
    /// It is intentionally chosen to be a high value
    /// to avoid collision with lower slots.
    /// The choice of manual storage layout is to enable compatibility
    /// with both regular and upgradeable contracts.
    uint256 private constant _OWNER_SLOT_NOT = 0x8b78c6d8;

    /// The ownership handover slot of `newOwner` is given by:
    /// ```
    ///     mstore(0x00, or(shl(96, user), _HANDOVER_SLOT_SEED))
    ///     let handoverSlot := keccak256(0x00, 0x20)
    /// ```
    /// It stores the expiry timestamp of the two-step ownership handover.
    uint256 private constant _HANDOVER_SLOT_SEED = 0x389a75e1;

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

    /// @dev Initializes the owner directly without authorization guard.
    /// This function must be called upon initialization,
    /// regardless of whether the contract is upgradeable or not.
    /// This is to enable generalization to both regular and upgradeable contracts,
    /// and to save gas in case the initial owner is not the caller.
    /// For performance reasons, this function will not check if there
    /// is an existing owner.
    function _initializeOwner(address newOwner) internal virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // Clean the upper 96 bits.
            newOwner := shr(96, shl(96, newOwner))
            // Store the new value.
            sstore(not(_OWNER_SLOT_NOT), newOwner)
            // Emit the {OwnershipTransferred} event.
            log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
        }
    }

    /// @dev Sets the owner directly without authorization guard.
    function _setOwner(address newOwner) internal virtual {
        /// @solidity memory-safe-assembly
        assembly {
            let ownerSlot := not(_OWNER_SLOT_NOT)
            // Clean the upper 96 bits.
            newOwner := shr(96, shl(96, newOwner))
            // Emit the {OwnershipTransferred} event.
            log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
            // Store the new value.
            sstore(ownerSlot, newOwner)
        }
    }

    /// @dev Throws if the sender is not the owner.
    function _checkOwner() internal view virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // If the caller is not the stored owner, revert.
            if iszero(eq(caller(), sload(not(_OWNER_SLOT_NOT)))) {
                mstore(0x00, 0x82b42900) // `Unauthorized()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Returns how long a two-step ownership handover is valid for in seconds.
    /// Override to return a different value if needed.
    /// Made internal to conserve bytecode. Wrap it in a public function if needed.
    function _ownershipHandoverValidFor() internal view virtual returns (uint64) {
        return 48 * 3600;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  PUBLIC UPDATE FUNCTIONS                   */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Allows the owner to transfer the ownership to `newOwner`.
    function transferOwnership(address newOwner) public payable virtual onlyOwner {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(shl(96, newOwner)) {
                mstore(0x00, 0x7448fbae) // `NewOwnerIsZeroAddress()`.
                revert(0x1c, 0x04)
            }
        }
        _setOwner(newOwner);
    }

    /// @dev Allows the owner to renounce their ownership.
    function renounceOwnership() public payable virtual onlyOwner {
        _setOwner(address(0));
    }

    /// @dev Request a two-step ownership handover to the caller.
    /// The request will automatically expire in 48 hours (172800 seconds) by default.
    function requestOwnershipHandover() public payable virtual {
        unchecked {
            uint256 expires = block.timestamp + _ownershipHandoverValidFor();
            /// @solidity memory-safe-assembly
            assembly {
                // Compute and set the handover slot to `expires`.
                mstore(0x0c, _HANDOVER_SLOT_SEED)
                mstore(0x00, caller())
                sstore(keccak256(0x0c, 0x20), expires)
                // Emit the {OwnershipHandoverRequested} event.
                log2(0, 0, _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE, caller())
            }
        }
    }

    /// @dev Cancels the two-step ownership handover to the caller, if any.
    function cancelOwnershipHandover() public payable virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute and set the handover slot to 0.
            mstore(0x0c, _HANDOVER_SLOT_SEED)
            mstore(0x00, caller())
            sstore(keccak256(0x0c, 0x20), 0)
            // Emit the {OwnershipHandoverCanceled} event.
            log2(0, 0, _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE, caller())
        }
    }

    /// @dev Allows the owner to complete the two-step ownership handover to `pendingOwner`.
    /// Reverts if there is no existing ownership handover requested by `pendingOwner`.
    function completeOwnershipHandover(address pendingOwner) public payable virtual onlyOwner {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute and set the handover slot to 0.
            mstore(0x0c, _HANDOVER_SLOT_SEED)
            mstore(0x00, pendingOwner)
            let handoverSlot := keccak256(0x0c, 0x20)
            // If the handover does not exist, or has expired.
            if gt(timestamp(), sload(handoverSlot)) {
                mstore(0x00, 0x6f5e8818) // `NoHandoverRequest()`.
                revert(0x1c, 0x04)
            }
            // Set the handover slot to 0.
            sstore(handoverSlot, 0)
        }
        _setOwner(pendingOwner);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                   PUBLIC READ FUNCTIONS                    */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the owner of the contract.
    function owner() public view virtual returns (address result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := sload(not(_OWNER_SLOT_NOT))
        }
    }

    /// @dev Returns the expiry timestamp for the two-step ownership handover to `pendingOwner`.
    function ownershipHandoverExpiresAt(address pendingOwner)
        public
        view
        virtual
        returns (uint256 result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the handover slot.
            mstore(0x0c, _HANDOVER_SLOT_SEED)
            mstore(0x00, pendingOwner)
            // Load the handover slot.
            result := sload(keccak256(0x0c, 0x20))
        }
    }

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

    /// @dev Marks a function as only callable by the owner.
    modifier onlyOwner() virtual {
        _checkOwner();
        _;
    }
}

// File: lib/solady/src/utils/SafeTransferLib.sol



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

/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
///
/// @dev Note:
/// - For ETH transfers, please use `forceSafeTransferETH` for gas griefing protection.
/// - For ERC20s, this implementation won't check that a token has code,
/// responsibility is delegated to the caller.
library SafeTransferLib {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The ETH transfer has failed.
    error ETHTransferFailed();

    /// @dev The ERC20 `transferFrom` has failed.
    error TransferFromFailed();

    /// @dev The ERC20 `transfer` has failed.
    error TransferFailed();

    /// @dev The ERC20 `approve` has failed.
    error ApproveFailed();

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

    /// @dev Suggested gas stipend for contract receiving ETH
    /// that disallows any storage writes.
    uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;

    /// @dev Suggested gas stipend for contract receiving ETH to perform a few
    /// storage reads and writes, but low enough to prevent griefing.
    /// Multiply by a small constant (e.g. 2), if needed.
    uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       ETH OPERATIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Sends `amount` (in wei) ETH to `to`.
    /// Reverts upon failure.
    ///
    /// Note: This implementation does NOT protect against gas griefing.
    /// Please use `forceSafeTransferETH` for gas griefing protection.
    function safeTransferETH(address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            // Transfer the ETH and check if it succeeded or not.
            if iszero(call(gas(), to, amount, 0x00, 0x00, 0x00, 0x00)) {
                // Store the function selector of `ETHTransferFailed()`.
                mstore(0x00, 0xb12d13eb)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
    /// The `gasStipend` can be set to a low enough value to prevent
    /// storage writes or gas griefing.
    ///
    /// If sending via the normal procedure fails, force sends the ETH by
    /// creating a temporary contract which uses `SELFDESTRUCT` to force send the ETH.
    ///
    /// Reverts if the current contract has insufficient balance.
    function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
        /// @solidity memory-safe-assembly
        assembly {
            // If insufficient balance, revert.
            if lt(selfbalance(), amount) {
                // Store the function selector of `ETHTransferFailed()`.
                mstore(0x00, 0xb12d13eb)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }
            // Transfer the ETH and check if it succeeded or not.
            if iszero(call(gasStipend, to, amount, 0x00, 0x00, 0x00, 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                // We can directly use `SELFDESTRUCT` in the contract creation.
                // Compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758
                if iszero(create(amount, 0x0b, 0x16)) {
                    // To coerce gas estimation to provide enough gas for the `create` above.
                    if iszero(gt(gas(), 1000000)) { revert(0x00, 0x00) }
                }
            }
        }
    }

    /// @dev Force sends `amount` (in wei) ETH to `to`, with a gas stipend
    /// equal to `GAS_STIPEND_NO_GRIEF`. This gas stipend is a reasonable default
    /// for 99% of cases and can be overridden with the three-argument version of this
    /// function if necessary.
    ///
    /// If sending via the normal procedure fails, force sends the ETH by
    /// creating a temporary contract which uses `SELFDESTRUCT` to force send the ETH.
    ///
    /// Reverts if the current contract has insufficient balance.
    function forceSafeTransferETH(address to, uint256 amount) internal {
        // Manually inlined because the compiler doesn't inline functions with branches.
        /// @solidity memory-safe-assembly
        assembly {
            // If insufficient balance, revert.
            if lt(selfbalance(), amount) {
                // Store the function selector of `ETHTransferFailed()`.
                mstore(0x00, 0xb12d13eb)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }
            // Transfer the ETH and check if it succeeded or not.
            if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, 0x00, 0x00, 0x00, 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                // We can directly use `SELFDESTRUCT` in the contract creation.
                // Compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758
                if iszero(create(amount, 0x0b, 0x16)) {
                    // To coerce gas estimation to provide enough gas for the `create` above.
                    if iszero(gt(gas(), 1000000)) { revert(0x00, 0x00) }
                }
            }
        }
    }

    /// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
    /// The `gasStipend` can be set to a low enough value to prevent
    /// storage writes or gas griefing.
    ///
    /// Simply use `gasleft()` for `gasStipend` if you don't need a gas stipend.
    ///
    /// Note: Does NOT revert upon failure.
    /// Returns whether the transfer of ETH is successful instead.
    function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
        internal
        returns (bool success)
    {
        /// @solidity memory-safe-assembly
        assembly {
            // Transfer the ETH and check if it succeeded or not.
            success := call(gasStipend, to, amount, 0x00, 0x00, 0x00, 0x00)
        }
    }

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

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
    /// Reverts upon failure.
    ///
    /// The `from` account must have at least `amount` approved for
    /// the current contract to manage.
    function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.

            mstore(0x60, amount) // Store the `amount` argument.
            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            // Store the function selector of `transferFrom(address,address,uint256)`.
            mstore(0x0c, 0x23b872dd000000000000000000000000)

            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    // 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(eq(mload(0x00), 1), iszero(returndatasize())),
                    call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
                )
            ) {
                // Store the function selector of `TransferFromFailed()`.
                mstore(0x00, 0x7939f424)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }

            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends all of ERC20 `token` from `from` to `to`.
    /// Reverts upon failure.
    ///
    /// The `from` account must have their entire balance approved for
    /// the current contract to manage.
    function safeTransferAllFrom(address token, address from, address to)
        internal
        returns (uint256 amount)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.

            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            // Store the function selector of `balanceOf(address)`.
            mstore(0x0c, 0x70a08231000000000000000000000000)
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
                )
            ) {
                // Store the function selector of `TransferFromFailed()`.
                mstore(0x00, 0x7939f424)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }

            // Store the function selector of `transferFrom(address,address,uint256)`.
            mstore(0x00, 0x23b872dd)
            // The `amount` is already at 0x60. Load it for the function's return value.
            amount := mload(0x60)

            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    // 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(eq(mload(0x00), 1), iszero(returndatasize())),
                    call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
                )
            ) {
                // Store the function selector of `TransferFromFailed()`.
                mstore(0x00, 0x7939f424)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }

            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
    /// Reverts upon failure.
    function safeTransfer(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            // Store the function selector of `transfer(address,uint256)`.
            mstore(0x00, 0xa9059cbb000000000000000000000000)

            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    // 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(eq(mload(0x00), 1), iszero(returndatasize())),
                    call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                )
            ) {
                // Store the function selector of `TransferFailed()`.
                mstore(0x00, 0x90b8ec18)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }
            // Restore the part of the free memory pointer that was overwritten.
            mstore(0x34, 0)
        }
    }

    /// @dev Sends all of ERC20 `token` from the current contract to `to`.
    /// Reverts upon failure.
    function safeTransferAll(address token, address to) internal returns (uint256 amount) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
            mstore(0x20, address()) // Store the address of the current contract.
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
                )
            ) {
                // Store the function selector of `TransferFailed()`.
                mstore(0x00, 0x90b8ec18)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }

            mstore(0x14, to) // Store the `to` argument.
            // The `amount` is already at 0x34. Load it for the function's return value.
            amount := mload(0x34)
            // Store the function selector of `transfer(address,uint256)`.
            mstore(0x00, 0xa9059cbb000000000000000000000000)

            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    // 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(eq(mload(0x00), 1), iszero(returndatasize())),
                    call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                )
            ) {
                // Store the function selector of `TransferFailed()`.
                mstore(0x00, 0x90b8ec18)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }
            // Restore the part of the free memory pointer that was overwritten.
            mstore(0x34, 0)
        }
    }

    /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
    /// Reverts upon failure.
    function safeApprove(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            // Store the function selector of `approve(address,uint256)`.
            mstore(0x00, 0x095ea7b3000000000000000000000000)

            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    // 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(eq(mload(0x00), 1), iszero(returndatasize())),
                    call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                )
            ) {
                // Store the function selector of `ApproveFailed()`.
                mstore(0x00, 0x3e3f8f73)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }
            // Restore the part of the free memory pointer that was overwritten.
            mstore(0x34, 0)
        }
    }

    /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
    /// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
    /// then retries the approval again (some tokens, e.g. USDT, requires this).
    /// Reverts upon failure.
    function safeApproveWithRetry(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            // Store the function selector of `approve(address,uint256)`.
            mstore(0x00, 0x095ea7b3000000000000000000000000)

            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    // 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(eq(mload(0x00), 1), iszero(returndatasize())),
                    call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                )
            ) {
                mstore(0x34, 0) // Store 0 for the `amount`.
                mstore(0x00, 0x095ea7b3000000000000000000000000) // Store the function selector.
                // We can ignore the result of this call. Just need to check the next call.
                pop(call(gas(), token, 0, 0x10, 0x44, 0x00, 0x00))
                mstore(0x34, amount) // Store back the original `amount`.

                if iszero(
                    and(
                        or(eq(mload(0x00), 1), iszero(returndatasize())),
                        call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                    )
                ) {
                    // Store the function selector of `ApproveFailed()`.
                    mstore(0x00, 0x3e3f8f73)
                    // Revert with (offset, size).
                    revert(0x1c, 0x04)
                }
            }
            // Restore the part of the free memory pointer that was overwritten.
            mstore(0x34, 0)
        }
    }

    /// @dev Returns the amount of ERC20 `token` owned by `account`.
    /// Returns zero if the `token` does not exist.
    function balanceOf(address token, address account) internal view returns (uint256 amount) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, account) // Store the `account` argument.
            // Store the function selector of `balanceOf(address)`.
            mstore(0x00, 0x70a08231000000000000000000000000)
            amount :=
                mul(
                    mload(0x20),
                    and( // The arguments of `and` are evaluated from right to left.
                        gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                        staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
                    )
                )
        }
    }
}

// File: src/interfaces/IVote.sol



// SPDX-License-Identifier: UNLICENSED

pragma solidity 0.8.18;

/**
 * @dev Interface of the VoteShare.
 */
interface IVote {
    struct TierStruct {
        uint256 tokenAmount;
        uint256 revenueShare;
    }

    struct SnapshotStruct {
        uint256[] usersByTier;
        uint256 balance;
        uint256 timestamp;
    }

    struct VoteStruct {
        bool active;
        uint8 choices;
        uint256 balance;
        uint256 timestamp;
    }

    struct GameStruct {
        bool active;
        uint256 balanceBefore;
        uint256 withdrawTimestamp;
        uint256 balanceAfter;
        uint256 depositTimestamp;
    }

    event TiersSet(TierStruct[] _tiers);
    event VotingPeriodSet(uint256 _period);
    event ProtocolAddressSet(address _address);
    event UpdateAddressSet(address _address);
    event RedeemFeeSet(uint256 fee);
    event VoteStarted(uint8 _choices);
    event VoteEnded(address _sender, uint256[] _winners, uint256 _gameBalance);
    event VoteCasted(address _sender, uint8 _choice);
    event ShareClaimed(address _sender, uint256 _amount, uint256 _fee);
    event RewardClaimed(address _sender, uint256 _amount);
    event ForfeitShare(address _sender, uint256 _amount);
    event ForfeitSharePartial(address _sender, uint256 _amount, uint256 _toProtocol);
    event GameStarted(uint256 _balance);
    event GameEnded(uint256 _balance);

    /// @dev The new address cannot be the zero address.
    error ZeroAddress();

    /// @dev You are trying to complete an action that can be done only when no vote is in progress.
    error VoteActive();

    /// @dev as this contract relies on externally set variables we don't let the owner forfeit access
    error NoRenounce();

    /// @dev Fee exceeds the maximum of 100%.
    error FeeOverflow();

    /// @dev You are trying to complete an action that can be done only when vote is in progress.
    error VoteNotActive();

    /// @dev Action does not respect time limits dependent on currentVote.timestamp and votingPeriod
    error OutOfBounds();

    /// @dev The sum of the tokenAmount(s) of the tiers exceeds the maxSupply
    error TokenTierOverflow();

    /// @dev The sum of the revenueShare(s) of the tiers exceeds 100%
    error ShareTierOverflow();

    /// @dev The updateState input should be equal to number of tiers +1 (the downgrade array as index 0)
    /// @param tiers orrect number of arrays
    error TierArrayLength(uint256 tiers);

    /// @dev Choice should be a number between min and max
    /// @param max index of last choice, is currentVote.choices-1
    error NotAChoice(uint8 max);

    /// @dev Choice should be a number between min and max
    /// @param timestamp user lastAction timestamp
    error LastAction(uint256 timestamp);

    /// @dev User hasn't been assigned any reward tier in snapshot
    error NoTier();

    /// @dev you are trying to set an empty array of tiers;
    error NoTiers();

    /// @dev this function can be accessed only by Update address
    error OnlyUpdate();

    /// @dev user has no pending rewards
    error NoReward();

    /// @dev there aren't enough choices to start a vote
    error NoChoices();

    /// @dev No two consecutive snapshots before a vote
    error NoConsecutiveSnapshot();

    /// @dev You are trying to complete an action that can be done only when no game session is in progress.
    error GameActive();

    /// @dev You are trying to complete an action that can be done only when a game session is in progress.
    error GameNotActive();

    /// @dev Only owner or update address can call this function
    error NotOwnerOrUpdate();
}

// File: src/Vote.sol



// SPDX-License-Identifier: UNLICENSED

pragma solidity 0.8.18;

import "./interfaces/IVote.sol";
import "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";
import "lib/solady/src/auth/Ownable.sol";
import "lib/solady/src/utils/SafeTransferLib.sol";

contract Vote is IVote, Ownable {
    uint256 constant _PRECISION = 1e18;
    uint256 private constant _PERCENTAGE = 10000;
    uint256 private constant _TOTAL_SUPPLY = 1e26; // 100,000,000 w/ 18 decimals
    address private immutable _token;

    uint256 public votingPeriod;
    uint256 public lastRevenue;

    SnapshotStruct _snapshot;
    VoteStruct _currentVote;
    GameStruct _currentGame;

    uint256[] public counter;

    TierStruct[] public tiers;

    mapping(address => uint256) public balanceOf;
    mapping(address => uint256) public tierOf;

    mapping(address => uint256) public gameShareOf;

    mapping(address => uint256) public lastActionOf;

    mapping(uint256 => GameStruct) public voteTimestampToGame;

    uint256 public redeemFee;
    address payable _protocolAddress;
    address _updateAddress;

    constructor(address _tokenAddress) noZeroAddress(_tokenAddress) {
        _initializeOwner(msg.sender);
        _token = _tokenAddress;
    }

    function castVote(uint8 _choice) external inSession {
        VoteStruct storage localVote = _currentVote;
        if (_choice > localVote.choices) revert NotAChoice(localVote.choices - 1);

        uint256 amount = _getTierAmount(msg.sender);
        amount += getReward(msg.sender);
        //slither-disable-next-line incorrect-equality
        if (amount == 0) return;

        counter[_choice] += 1;

        balanceOf[msg.sender] = 0;
        lastActionOf[msg.sender] = localVote.timestamp;
        emit VoteCasted(msg.sender, _choice);
        _currentGame.balanceBefore += amount;
        gameShareOf[msg.sender] = amount;
    }

    function claimShare() external inSession {
        uint256 amount = _getTierAmount(msg.sender);
        //slither-disable-next-line incorrect-equality
        if (amount == 0) return;

        uint256 toProtocol = amount * redeemFee / _PERCENTAGE;
        amount -= toProtocol;
        amount += getReward(msg.sender);

        balanceOf[msg.sender] = 0;
        gameShareOf[msg.sender] = 0;
        emit ShareClaimed(msg.sender, amount, toProtocol);
        SafeTransferLib.safeTransferETH(msg.sender, amount);
        SafeTransferLib.safeTransferETH(_protocolAddress, toProtocol);
    }

    function claimReward() external requireVoteNotActive requireGameNotActive {
        uint256 amount = getReward(msg.sender);
        if (amount == 0 && gameShareOf[msg.sender] == 0) revert NoReward();

        gameShareOf[msg.sender] = 0;
        emit RewardClaimed(msg.sender, amount);
        SafeTransferLib.safeTransferETH(msg.sender, amount);
    }

    function _getTierAmount(address _user) internal returns (uint256) {
        uint256 currentBalance = IERC20(_token).balanceOf(_user);

        int256 currentTier = _findTier(currentBalance);
        uint256 amount = balanceOf[_user];

        if (currentTier < 0) {
            balanceOf[_user] = 0;
            emit ForfeitShare(msg.sender, amount);
            SafeTransferLib.safeTransferETH(_protocolAddress, amount);
            return 0;
        }

        uint256 snapshotTier = tierOf[_user];
        uint256 currentTierUnsigned = uint256(currentTier);
        if (snapshotTier > currentTierUnsigned) {
            uint256 currentTierShare = _getTierRevenue(currentTierUnsigned) / _snapshot.usersByTier[currentTierUnsigned];
            uint256 snapshotTierShare = _getTierRevenue(snapshotTier) / _snapshot.usersByTier[snapshotTier];
            uint256 toProtocol = snapshotTierShare - currentTierShare;
            amount -= toProtocol;
            emit ForfeitSharePartial(msg.sender, amount, toProtocol);
            SafeTransferLib.safeTransferETH(_protocolAddress, toProtocol);
        }
        return amount;
    }

    function _getTierRevenue(uint256 _tier) internal view returns (uint256) {
        return _currentVote.balance * tiers[_tier].revenueShare / _PERCENTAGE;
    }

    /// @notice Starts a vote session
    /// @dev If vote is not already undergoing the contractOwner can start a vote session,
    /// we store number of choices, timestamp of action and set vote.active to true;
    /// function is set to payable to cut on gas costs
    /// @param _choices indicates the number of choices available for this vote sessions
    /// Note Emits a {VoteStarted} event
    function startVote(uint8 _choices) external payable onlyOwnerOrUpdate requireVoteNotActive {
        if (_choices < 2) revert NoChoices();
        _currentVote = VoteStruct(true, _choices, _snapshot.balance, block.timestamp);
        _currentGame = GameStruct(false, 0, 0, 0, 0);
        counter = new uint256[](_choices);

        emit VoteStarted(_choices);
    }

    function _getWinners() internal view returns (uint256[] memory) {
        uint256[] memory localCounter = counter;
        uint256 counterLength = localCounter.length;
        uint256 maxNumber = localCounter[0];
        uint256 count = 1;

        for (uint256 i = 1; i < counterLength; ++i) {
            if (localCounter[i] > maxNumber) {
                maxNumber = localCounter[i];
                count = 1;
            } else if (localCounter[i] == maxNumber) {
                ++count;
            }
        }

        uint256[] memory winners = new uint256[](count);
        count = 0;

        for (uint256 i; i < counterLength; ++i) {
            if (localCounter[i] == maxNumber) {
                winners[count] = i;
                count += 1;
            }
        }

        return winners;
    }

    function _findTier(uint256 balance) internal view returns (int256) {
        uint256 length = tiers.length;
        for (uint256 i; i < length; ++i) {
            if (balance < tiers[i].tokenAmount) {
                return (i == 0) ? -1 : int256(i) - 1;
            }
        }
        return int256(length) - 1;
    }

    function updateState(address[][] memory addressByTier) external payable onlyUpdate requireVoteNotActive {
        SnapshotStruct storage localSnapshot = _snapshot;
        if (localSnapshot.timestamp > _currentVote.timestamp) revert NoConsecutiveSnapshot();
        TierStruct[] memory localTiers = tiers;
        uint256 tiersLength = localTiers.length;
        if (addressByTier.length != tiersLength + 1) revert TierArrayLength(tiersLength + 1);
        delete _snapshot;
        uint256 toProtocol;

        // first array is reserved for addresses that do not respect any threshold requirement
        // we zero out the pending rewards for them and send them to protocol wallet
        uint256 zeroLength = addressByTier[0].length;
        for (uint256 i; i < zeroLength; ++i) {
            toProtocol += balanceOf[addressByTier[0][i]];
            balanceOf[addressByTier[0][i]] = 0;
        }
        SafeTransferLib.safeTransferETH(_protocolAddress, toProtocol);

        uint256 inputLength = addressByTier.length;
        _snapshot = SnapshotStruct(new uint256[](tiersLength), lastRevenue, block.timestamp);

        for (uint256 l = 1; l < inputLength; ++l) {
            uint256 tier = l - 1;
            uint256 tierLength = addressByTier[l].length;
            localSnapshot.usersByTier[tier] = tierLength;
            uint256 individualShare = (lastRevenue * localTiers[tier].revenueShare / _PERCENTAGE) / tierLength;

            // Update the state for each user
            for (uint256 i; i < tierLength; ++i) {
                tierOf[addressByTier[l][i]] = tier;
                balanceOf[addressByTier[l][i]] += individualShare;
            }
        }
        lastRevenue = 0;
        // maybe emit event?
    }

    function startGame() external payable onlyOwnerOrUpdate requireGameNotActive {
        VoteStruct storage localVote = _currentVote;
        GameStruct storage localGame = _currentGame;
        if (block.timestamp < localVote.timestamp + votingPeriod) revert OutOfBounds();
        if (!localVote.active) revert VoteNotActive();

        uint256[] memory winners = _getWinners();
        localVote.active = false;
        localGame.active = true;
        localGame.withdrawTimestamp = block.timestamp;
        emit VoteEnded(owner(), winners, localGame.balanceBefore);
        SafeTransferLib.safeTransferETH(owner(), localGame.balanceBefore);
    }

    function endGame() external payable onlyOwner requireGameActive requireVoteNotActive {
        GameStruct storage localGame = _currentGame;
        localGame.active = false;
        localGame.balanceAfter = msg.value;
        localGame.depositTimestamp = block.timestamp;

        voteTimestampToGame[_currentVote.timestamp] = localGame;
        emit GameEnded(msg.value);
    }

    function getReward(address _address) public view returns (uint256) {
        uint256 share = gameShareOf[_address];
        if (share == 0) return 0;
        GameStruct storage localGame = voteTimestampToGame[lastActionOf[_address]];
        uint256 multiplier = _getMultiplier(localGame.balanceAfter, localGame.balanceBefore);
        return share * multiplier / _PRECISION;
    }

    function _getMultiplier(uint256 _newBalance, uint256 _oldBalance) internal pure returns (uint256) {
        return (_newBalance * _PRECISION) / _oldBalance;
    }

    function setTiers(TierStruct[] calldata _tiers) external payable onlyOwner tiersSafe(_tiers) {
        delete tiers;
        uint256 length = _tiers.length;
        for (uint256 i; i < length; ++i) {
            tiers.push(_tiers[i]);
        }

        emit TiersSet(_tiers);
    }

    function setPeriod(uint256 _period) external payable onlyOwner requireVoteNotActive {
        votingPeriod = _period;
        emit VotingPeriodSet(_period);
    }

    function setProtocolAddress(address _address) external payable onlyOwner noZeroAddress(_address) {
        _protocolAddress = payable(_address);
        emit ProtocolAddressSet(_address);
    }

    function setUpdateAddress(address _address) external payable onlyOwner noZeroAddress(_address) {
        _updateAddress = _address;
        emit UpdateAddressSet(_address);
    }

    /// @notice Sets fee for early redeem, values from 0.01 (1) to 100.00 (10000)
    /// @param _fee new fee amount, a percentage expressed in uint256 with 2 decimals
    function setRedeemFee(uint256 _fee) external payable onlyOwner {
        if (_fee > _PERCENTAGE) revert FeeOverflow();
        redeemFee = _fee;
        emit RedeemFeeSet(_fee);
    }

    function renounceOwnership() public payable override onlyOwner {
        revert NoRenounce();
    }

    receive() external payable {
        lastRevenue += msg.value;
    }

    // redeem emergency function;

    function currentVote() external view returns (VoteStruct memory) {
        return _currentVote;
    }

    function currentGame() external view returns (GameStruct memory) {
        return _currentGame;
    }

    function snapshot() external view returns (SnapshotStruct memory) {
        return _snapshot;
    }

    function getUsersByTier() external view returns (uint256[] memory) {
        return _snapshot.usersByTier;
    }

    modifier inSession() {
        VoteStruct storage localVote = _currentVote;
        if (block.timestamp < localVote.timestamp || block.timestamp > localVote.timestamp + votingPeriod) {
            revert OutOfBounds();
        }

        if (balanceOf[msg.sender] == 0) revert NoReward();

        _;
    }

    modifier tiersSafe(TierStruct[] memory _tiers) {
        uint256 length = _tiers.length;
        if (length == 0) revert NoTiers();
        uint256 tokenTotal;
        uint256 revenueTotal;
        uint256 supply = _TOTAL_SUPPLY;
        for (uint256 i; i < length; ++i) {
            tokenTotal += _tiers[i].tokenAmount;
            revenueTotal += _tiers[i].revenueShare;

            if (tokenTotal > supply) revert TokenTierOverflow();
            if (revenueTotal > 10_000) revert ShareTierOverflow();
        }

        _;
    }

    modifier noZeroAddress(address _address) {
        if (_address == address(0)) revert ZeroAddress();
        _;
    }

    modifier requireVoteNotActive() {
        if (_currentVote.active) revert VoteActive();
        _;
    }

    modifier requireGameActive() {
        if (!_currentGame.active) revert GameNotActive();
        _;
    }

    modifier requireGameNotActive() {
        if (_currentGame.active) revert GameActive();
        _;
    }

    modifier onlyUpdate() {
        if (msg.sender != _updateAddress) revert OnlyUpdate();
        _;
    }

    modifier onlyOwnerOrUpdate() {
        if (msg.sender != owner() && msg.sender != _updateAddress) revert NotOwnerOrUpdate();
        _;
    }
}