ETH Price: $2,254.98 (-6.86%)

Transaction Decoder

Block:
21138739 at Nov-07-2024 10:25:35 PM +UTC
Transaction Fee:
0.00248141170816742 ETH $5.60
Gas Used:
130,555 Gas / 19.006638644 Gwei

Emitted Events:

387 TITANX.Approval( owner=[Sender] 0x7843c6022abba22f353ee85881d154d34cadba81, spender=[Receiver] ElementNFT, value=100000000000000000000100000 )
388 TITANX.Transfer( from=[Sender] 0x7843c6022abba22f353ee85881d154d34cadba81, to=Element280, value=1000000000000000000000000000 )
389 TITANX.Approval( owner=[Sender] 0x7843c6022abba22f353ee85881d154d34cadba81, spender=[Receiver] ElementNFT, value=100000 )
390 TITANX.Transfer( from=[Sender] 0x7843c6022abba22f353ee85881d154d34cadba81, to=GnosisSafeProxy, value=100000000000000000000000000 )
391 ElementNFT.Transfer( from=0x00000000...000000000, to=[Sender] 0x7843c6022abba22f353ee85881d154d34cadba81, tokenId=15192 )

Account State Difference:

  Address   Before After State Difference Code
0x7843C602...34cADba81
0.012337301817491335 Eth
Nonce: 198
0.009855890109323915 Eth
Nonce: 199
0.00248141170816742
0x7F090d10...fC0Cf46c9
(beaverbuild)
14.445384552687193339 Eth14.445394861309993339 Eth0.0000103086228
0xF19308F9...BEC6665B1

Execution Trace

ElementNFT.mintWithTitanX( tieredNfts=[4] )
  • TITANX.transferFrom( from=0x7843C6022ABBA22F353eE85881D154D34cADba81, to=0xe9A53C43a0B58706e67341C4055de861e29Ee943, amount=1000000000000000000000000000 ) => ( True )
  • TITANX.transferFrom( from=0x7843C6022ABBA22F353eE85881D154D34cADba81, to=0x15E5B9B9Adf208cC7CA3aE1e6a49506eB5f397Dd, amount=100000000000000000000000000 ) => ( True )
    File 1 of 4: ElementNFT
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
    pragma solidity ^0.8.20;
    import {Context} from "../utils/Context.sol";
    /**
     * @dev Contract module which provides a basic access control mechanism, where
     * there is an account (an owner) that can be granted exclusive access to
     * specific functions.
     *
     * The initial owner is set to the address provided by the deployer. This can
     * later be changed with {transferOwnership}.
     *
     * This module is used through inheritance. It will make available the modifier
     * `onlyOwner`, which can be applied to your functions to restrict their use to
     * the owner.
     */
    abstract contract Ownable is Context {
        address private _owner;
        /**
         * @dev The caller account is not authorized to perform an operation.
         */
        error OwnableUnauthorizedAccount(address account);
        /**
         * @dev The owner is not a valid owner account. (eg. `address(0)`)
         */
        error OwnableInvalidOwner(address owner);
        event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
        /**
         * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
         */
        constructor(address initialOwner) {
            if (initialOwner == address(0)) {
                revert OwnableInvalidOwner(address(0));
            }
            _transferOwnership(initialOwner);
        }
        /**
         * @dev Throws if called by any account other than the owner.
         */
        modifier onlyOwner() {
            _checkOwner();
            _;
        }
        /**
         * @dev Returns the address of the current owner.
         */
        function owner() public view virtual returns (address) {
            return _owner;
        }
        /**
         * @dev Throws if the sender is not the owner.
         */
        function _checkOwner() internal view virtual {
            if (owner() != _msgSender()) {
                revert OwnableUnauthorizedAccount(_msgSender());
            }
        }
        /**
         * @dev Leaves the contract without owner. It will not be possible to call
         * `onlyOwner` functions. Can only be called by the current owner.
         *
         * NOTE: Renouncing ownership will leave the contract without an owner,
         * thereby disabling any functionality that is only available to the owner.
         */
        function renounceOwnership() public virtual onlyOwner {
            _transferOwnership(address(0));
        }
        /**
         * @dev Transfers ownership of the contract to a new account (`newOwner`).
         * Can only be called by the current owner.
         */
        function transferOwnership(address newOwner) public virtual onlyOwner {
            if (newOwner == address(0)) {
                revert OwnableInvalidOwner(address(0));
            }
            _transferOwnership(newOwner);
        }
        /**
         * @dev Transfers ownership of the contract to a new account (`newOwner`).
         * Internal function without access restriction.
         */
        function _transferOwnership(address newOwner) internal virtual {
            address oldOwner = _owner;
            _owner = newOwner;
            emit OwnershipTransferred(oldOwner, newOwner);
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)
    pragma solidity ^0.8.20;
    import {IERC165} from "../utils/introspection/IERC165.sol";
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
    pragma solidity ^0.8.20;
    import {IERC20} from "../token/ERC20/IERC20.sol";
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
    pragma solidity ^0.8.20;
    /**
     * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
     * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
     *
     * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
     * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
     * need to send a transaction, and thus is not required to hold Ether at all.
     *
     * ==== Security Considerations
     *
     * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
     * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
     * considered as an intention to spend the allowance in any specific way. The second is that because permits have
     * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
     * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
     * generally recommended is:
     *
     * ```solidity
     * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
     *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
     *     doThing(..., value);
     * }
     *
     * function doThing(..., uint256 value) public {
     *     token.safeTransferFrom(msg.sender, address(this), value);
     *     ...
     * }
     * ```
     *
     * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
     * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
     * {SafeERC20-safeTransferFrom}).
     *
     * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
     * contracts should have entry points that don't rely on permit.
     */
    interface IERC20Permit {
        /**
         * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
         * given ``owner``'s signed approval.
         *
         * IMPORTANT: The same issues {IERC20-approve} has related to transaction
         * ordering also apply here.
         *
         * Emits an {Approval} event.
         *
         * Requirements:
         *
         * - `spender` cannot be the zero address.
         * - `deadline` must be a timestamp in the future.
         * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
         * over the EIP712-formatted function arguments.
         * - the signature must use ``owner``'s current nonce (see {nonces}).
         *
         * For more information on the signature format, see the
         * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
         * section].
         *
         * CAUTION: See Security Considerations above.
         */
        function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
            external;
        /**
         * @dev Returns the current nonce for `owner`. This value must be
         * included whenever a signature is generated for {permit}.
         *
         * Every successful call to {permit} increases ``owner``'s nonce by one. This
         * prevents a signature from being used multiple times.
         */
        function nonces(address owner) external view returns (uint256);
        /**
         * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
         */
        // solhint-disable-next-line func-name-mixedcase
        function DOMAIN_SEPARATOR() external view returns (bytes32);
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
    pragma solidity ^0.8.20;
    /**
     * @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 value of tokens in existence.
         */
        function totalSupply() external view returns (uint256);
        /**
         * @dev Returns the value of tokens owned by `account`.
         */
        function balanceOf(address account) external view returns (uint256);
        /**
         * @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool);
        /**
         * @dev Moves a `value` amount of tokens from `from` to `to` using the
         * allowance mechanism. `value` 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 value) external returns (bool);
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
    pragma solidity ^0.8.20;
    import {IERC20} from "../IERC20.sol";
    import {IERC20Permit} from "../extensions/IERC20Permit.sol";
    import {Address} from "../../../utils/Address.sol";
    /**
     * @title SafeERC20
     * @dev Wrappers around ERC20 operations that throw on failure (when the token
     * contract returns false). Tokens that return no value (and instead revert or
     * throw on failure) are also supported, non-reverting calls are assumed to be
     * successful.
     * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
     * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
     */
    library SafeERC20 {
        using Address for address;
        /**
         * @dev An operation with an ERC20 token failed.
         */
        error SafeERC20FailedOperation(address token);
        /**
         * @dev Indicates a failed `decreaseAllowance` request.
         */
        error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
        /**
         * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
         * non-reverting calls are assumed to be successful.
         */
        function safeTransfer(IERC20 token, address to, uint256 value) internal {
            _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
        }
        /**
         * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
         * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
         */
        function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
            _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
        }
        /**
         * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
         * non-reverting calls are assumed to be successful.
         */
        function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
            uint256 oldAllowance = token.allowance(address(this), spender);
            forceApprove(token, spender, oldAllowance + value);
        }
        /**
         * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
         * value, non-reverting calls are assumed to be successful.
         */
        function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
            unchecked {
                uint256 currentAllowance = token.allowance(address(this), spender);
                if (currentAllowance < requestedDecrease) {
                    revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
                }
                forceApprove(token, spender, currentAllowance - requestedDecrease);
            }
        }
        /**
         * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
         * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
         * to be set to zero before setting it to a non-zero value, such as USDT.
         */
        function forceApprove(IERC20 token, address spender, uint256 value) internal {
            bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
            if (!_callOptionalReturnBool(token, approvalCall)) {
                _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
                _callOptionalReturn(token, approvalCall);
            }
        }
        /**
         * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
         * on the return value: the return value is optional (but if data is returned, it must not be false).
         * @param token The token targeted by the call.
         * @param data The call data (encoded using abi.encode or one of its variants).
         */
        function _callOptionalReturn(IERC20 token, bytes memory data) private {
            // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
            // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
            // the target address contains contract code and also asserts for success in the low-level call.
            bytes memory returndata = address(token).functionCall(data);
            if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
                revert SafeERC20FailedOperation(address(token));
            }
        }
        /**
         * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
         * on the return value: the return value is optional (but if data is returned, it must not be false).
         * @param token The token targeted by the call.
         * @param data The call data (encoded using abi.encode or one of its variants).
         *
         * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
         */
        function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
            // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
            // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
            // and not revert is the subcall reverts.
            (bool success, bytes memory returndata) = address(token).call(data);
            return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
    pragma solidity ^0.8.20;
    /**
     * @dev Collection of functions related to the address type
     */
    library Address {
        /**
         * @dev The ETH balance of the account is not enough to perform the operation.
         */
        error AddressInsufficientBalance(address account);
        /**
         * @dev There's no code at `target` (it is not a contract).
         */
        error AddressEmptyCode(address target);
        /**
         * @dev A call to an address target failed. The target may have reverted.
         */
        error FailedInnerCall();
        /**
         * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
         * `recipient`, forwarding all available gas and reverting on errors.
         *
         * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
         * of certain opcodes, possibly making contracts go over the 2300 gas limit
         * imposed by `transfer`, making them unable to receive funds via
         * `transfer`. {sendValue} removes this limitation.
         *
         * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
         *
         * IMPORTANT: because control is transferred to `recipient`, care must be
         * taken to not create reentrancy vulnerabilities. Consider using
         * {ReentrancyGuard} or the
         * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
         */
        function sendValue(address payable recipient, uint256 amount) internal {
            if (address(this).balance < amount) {
                revert AddressInsufficientBalance(address(this));
            }
            (bool success,) = recipient.call{value: amount}("");
            if (!success) {
                revert FailedInnerCall();
            }
        }
        /**
         * @dev Performs a Solidity function call using a low level `call`. A
         * plain `call` is an unsafe replacement for a function call: use this
         * function instead.
         *
         * If `target` reverts with a revert reason or custom error, it is bubbled
         * up by this function (like regular Solidity function calls). However, if
         * the call reverted with no returned reason, this function reverts with a
         * {FailedInnerCall} error.
         *
         * Returns the raw returned data. To convert to the expected return value,
         * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
         *
         * Requirements:
         *
         * - `target` must be a contract.
         * - calling `target` with `data` must not revert.
         */
        function functionCall(address target, bytes memory data) internal returns (bytes memory) {
            return functionCallWithValue(target, data, 0);
        }
        /**
         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
         * but also transferring `value` wei to `target`.
         *
         * Requirements:
         *
         * - the calling contract must have an ETH balance of at least `value`.
         * - the called Solidity function must be `payable`.
         */
        function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
            if (address(this).balance < value) {
                revert AddressInsufficientBalance(address(this));
            }
            (bool success, bytes memory returndata) = target.call{value: value}(data);
            return verifyCallResultFromTarget(target, success, returndata);
        }
        /**
         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
         * but performing a static call.
         */
        function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
            (bool success, bytes memory returndata) = target.staticcall(data);
            return verifyCallResultFromTarget(target, success, returndata);
        }
        /**
         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
         * but performing a delegate call.
         */
        function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
            (bool success, bytes memory returndata) = target.delegatecall(data);
            return verifyCallResultFromTarget(target, success, returndata);
        }
        /**
         * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
         * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
         * unsuccessful call.
         */
        function verifyCallResultFromTarget(address target, bool success, bytes memory returndata)
            internal
            view
            returns (bytes memory)
        {
            if (!success) {
                _revert(returndata);
            } else {
                // only check if target is a contract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                if (returndata.length == 0 && target.code.length == 0) {
                    revert AddressEmptyCode(target);
                }
                return returndata;
            }
        }
        /**
         * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
         * revert reason or with a default {FailedInnerCall} error.
         */
        function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
            if (!success) {
                _revert(returndata);
            } else {
                return returndata;
            }
        }
        /**
         * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
         */
        function _revert(bytes memory returndata) private pure {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly
                /// @solidity memory-safe-assembly
                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert FailedInnerCall();
            }
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
    pragma solidity ^0.8.20;
    /**
     * @dev Provides information about the current execution context, including the
     * sender of the transaction and its data. While these are generally available
     * via msg.sender and msg.data, they should not be accessed in such a direct
     * manner, since when dealing with meta-transactions the account sending and
     * paying for execution may not be the actual sender (as far as an application
     * is concerned).
     *
     * This contract is only required for intermediate, library-like contracts.
     */
    abstract contract Context {
        function _msgSender() internal view virtual returns (address) {
            return msg.sender;
        }
        function _msgData() internal view virtual returns (bytes calldata) {
            return msg.data;
        }
        function _contextSuffixLength() internal view virtual returns (uint256) {
            return 0;
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
    pragma solidity ^0.8.20;
    /**
     * @dev Interface of the ERC165 standard, as defined in the
     * https://eips.ethereum.org/EIPS/eip-165[EIP].
     *
     * Implementers can declare support of contract interfaces, which can then be
     * queried by others ({ERC165Checker}).
     *
     * For an implementation, see {ERC165}.
     */
    interface IERC165 {
        /**
         * @dev Returns true if this contract implements the interface defined by
         * `interfaceId`. See the corresponding
         * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
         * to learn more about how these ids are created.
         *
         * This function call must use less than 30 000 gas.
         */
        function supportsInterface(bytes4 interfaceId) external view returns (bool);
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
    pragma solidity ^0.8.20;
    /**
     * @dev Standard math utilities missing in the Solidity language.
     */
    library Math {
        /**
         * @dev Muldiv operation overflow.
         */
        error MathOverflowedMulDiv();
        enum Rounding {
            Floor, // Toward negative infinity
            Ceil, // Toward positive infinity
            Trunc, // Toward zero
            Expand // Away from zero
        }
        /**
         * @dev Returns the addition of two unsigned integers, with an overflow flag.
         */
        function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
            unchecked {
                uint256 c = a + b;
                if (c < a) return (false, 0);
                return (true, c);
            }
        }
        /**
         * @dev Returns the subtraction of two unsigned integers, with an overflow flag.
         */
        function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
            unchecked {
                if (b > a) return (false, 0);
                return (true, a - b);
            }
        }
        /**
         * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
         */
        function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
            unchecked {
                // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                // benefit is lost if 'b' is also tested.
                // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
                if (a == 0) return (true, 0);
                uint256 c = a * b;
                if (c / a != b) return (false, 0);
                return (true, c);
            }
        }
        /**
         * @dev Returns the division of two unsigned integers, with a division by zero flag.
         */
        function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
            unchecked {
                if (b == 0) return (false, 0);
                return (true, a / b);
            }
        }
        /**
         * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
         */
        function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
            unchecked {
                if (b == 0) return (false, 0);
                return (true, a % b);
            }
        }
        /**
         * @dev Returns the largest of two numbers.
         */
        function max(uint256 a, uint256 b) internal pure returns (uint256) {
            return a > b ? a : b;
        }
        /**
         * @dev Returns the smallest of two numbers.
         */
        function min(uint256 a, uint256 b) internal pure returns (uint256) {
            return a < b ? a : b;
        }
        /**
         * @dev Returns the average of two numbers. The result is rounded towards
         * zero.
         */
        function average(uint256 a, uint256 b) internal pure returns (uint256) {
            // (a + b) / 2 can overflow.
            return (a & b) + (a ^ b) / 2;
        }
        /**
         * @dev Returns the ceiling of the division of two numbers.
         *
         * This differs from standard division with `/` in that it rounds towards infinity instead
         * of rounding towards zero.
         */
        function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
            if (b == 0) {
                // Guarantee the same behavior as in a regular Solidity division.
                return a / b;
            }
            // (a + b - 1) / b can overflow on addition, so we distribute.
            return a == 0 ? 0 : (a - 1) / b + 1;
        }
        /**
         * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
         * denominator == 0.
         * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
         * Uniswap Labs also under MIT license.
         */
        function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
            unchecked {
                // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
                // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
                // variables such that product = prod1 * 2^256 + prod0.
                uint256 prod0 = x * y; // Least significant 256 bits of the product
                uint256 prod1; // Most significant 256 bits of the product
                assembly {
                    let mm := mulmod(x, y, not(0))
                    prod1 := sub(sub(mm, prod0), lt(mm, prod0))
                }
                // Handle non-overflow cases, 256 by 256 division.
                if (prod1 == 0) {
                    // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                    // The surrounding unchecked block does not change this fact.
                    // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                    return prod0 / denominator;
                }
                // Make sure the result is less than 2^256. Also prevents denominator == 0.
                if (denominator <= prod1) {
                    revert MathOverflowedMulDiv();
                }
                ///////////////////////////////////////////////
                // 512 by 256 division.
                ///////////////////////////////////////////////
                // Make division exact by subtracting the remainder from [prod1 prod0].
                uint256 remainder;
                assembly {
                    // Compute remainder using mulmod.
                    remainder := mulmod(x, y, denominator)
                    // Subtract 256 bit number from 512 bit number.
                    prod1 := sub(prod1, gt(remainder, prod0))
                    prod0 := sub(prod0, remainder)
                }
                // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
                // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
                uint256 twos = denominator & (0 - denominator);
                assembly {
                    // Divide denominator by twos.
                    denominator := div(denominator, twos)
                    // Divide [prod1 prod0] by twos.
                    prod0 := div(prod0, twos)
                    // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                    twos := add(div(sub(0, twos), twos), 1)
                }
                // Shift in bits from prod1 into prod0.
                prod0 |= prod1 * twos;
                // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
                // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
                // four bits. That is, denominator * inv = 1 mod 2^4.
                uint256 inverse = (3 * denominator) ^ 2;
                // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
                // works in modular arithmetic, doubling the correct bits in each step.
                inverse *= 2 - denominator * inverse; // inverse mod 2^8
                inverse *= 2 - denominator * inverse; // inverse mod 2^16
                inverse *= 2 - denominator * inverse; // inverse mod 2^32
                inverse *= 2 - denominator * inverse; // inverse mod 2^64
                inverse *= 2 - denominator * inverse; // inverse mod 2^128
                inverse *= 2 - denominator * inverse; // inverse mod 2^256
                // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
                // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
                // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
                // is no longer required.
                result = prod0 * inverse;
                return result;
            }
        }
        /**
         * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
         */
        function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
            uint256 result = mulDiv(x, y, denominator);
            if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
                result += 1;
            }
            return result;
        }
        /**
         * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
         * towards zero.
         *
         * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
         */
        function sqrt(uint256 a) internal pure returns (uint256) {
            if (a == 0) {
                return 0;
            }
            // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
            //
            // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
            // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
            //
            // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
            // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
            // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
            //
            // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
            uint256 result = 1 << (log2(a) >> 1);
            // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
            // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
            // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
            // into the expected uint128 result.
            unchecked {
                result = (result + a / result) >> 1;
                result = (result + a / result) >> 1;
                result = (result + a / result) >> 1;
                result = (result + a / result) >> 1;
                result = (result + a / result) >> 1;
                result = (result + a / result) >> 1;
                result = (result + a / result) >> 1;
                return min(result, a / result);
            }
        }
        /**
         * @notice Calculates sqrt(a), following the selected rounding direction.
         */
        function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
            unchecked {
                uint256 result = sqrt(a);
                return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
            }
        }
        /**
         * @dev Return the log in base 2 of a positive value rounded towards zero.
         * Returns 0 if given 0.
         */
        function log2(uint256 value) internal pure returns (uint256) {
            uint256 result = 0;
            unchecked {
                if (value >> 128 > 0) {
                    value >>= 128;
                    result += 128;
                }
                if (value >> 64 > 0) {
                    value >>= 64;
                    result += 64;
                }
                if (value >> 32 > 0) {
                    value >>= 32;
                    result += 32;
                }
                if (value >> 16 > 0) {
                    value >>= 16;
                    result += 16;
                }
                if (value >> 8 > 0) {
                    value >>= 8;
                    result += 8;
                }
                if (value >> 4 > 0) {
                    value >>= 4;
                    result += 4;
                }
                if (value >> 2 > 0) {
                    value >>= 2;
                    result += 2;
                }
                if (value >> 1 > 0) {
                    result += 1;
                }
            }
            return result;
        }
        /**
         * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
         * Returns 0 if given 0.
         */
        function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
            unchecked {
                uint256 result = log2(value);
                return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
            }
        }
        /**
         * @dev Return the log in base 10 of a positive value rounded towards zero.
         * Returns 0 if given 0.
         */
        function log10(uint256 value) internal pure returns (uint256) {
            uint256 result = 0;
            unchecked {
                if (value >= 10 ** 64) {
                    value /= 10 ** 64;
                    result += 64;
                }
                if (value >= 10 ** 32) {
                    value /= 10 ** 32;
                    result += 32;
                }
                if (value >= 10 ** 16) {
                    value /= 10 ** 16;
                    result += 16;
                }
                if (value >= 10 ** 8) {
                    value /= 10 ** 8;
                    result += 8;
                }
                if (value >= 10 ** 4) {
                    value /= 10 ** 4;
                    result += 4;
                }
                if (value >= 10 ** 2) {
                    value /= 10 ** 2;
                    result += 2;
                }
                if (value >= 10 ** 1) {
                    result += 1;
                }
            }
            return result;
        }
        /**
         * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
         * Returns 0 if given 0.
         */
        function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
            unchecked {
                uint256 result = log10(value);
                return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
            }
        }
        /**
         * @dev Return the log in base 256 of a positive value rounded towards zero.
         * Returns 0 if given 0.
         *
         * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
         */
        function log256(uint256 value) internal pure returns (uint256) {
            uint256 result = 0;
            unchecked {
                if (value >> 128 > 0) {
                    value >>= 128;
                    result += 16;
                }
                if (value >> 64 > 0) {
                    value >>= 64;
                    result += 8;
                }
                if (value >> 32 > 0) {
                    value >>= 32;
                    result += 4;
                }
                if (value >> 16 > 0) {
                    value >>= 16;
                    result += 2;
                }
                if (value >> 8 > 0) {
                    result += 1;
                }
            }
            return result;
        }
        /**
         * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
         * Returns 0 if given 0.
         */
        function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
            unchecked {
                uint256 result = log256(value);
                return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
            }
        }
        /**
         * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
         */
        function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
            return uint8(rounding) % 2 == 1;
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)
    pragma solidity ^0.8.20;
    /**
     * @dev Standard signed math utilities missing in the Solidity language.
     */
    library SignedMath {
        /**
         * @dev Returns the largest of two signed numbers.
         */
        function max(int256 a, int256 b) internal pure returns (int256) {
            return a > b ? a : b;
        }
        /**
         * @dev Returns the smallest of two signed numbers.
         */
        function min(int256 a, int256 b) internal pure returns (int256) {
            return a < b ? a : b;
        }
        /**
         * @dev Returns the average of two signed numbers without overflow.
         * The result is rounded towards zero.
         */
        function average(int256 a, int256 b) internal pure returns (int256) {
            // Formula from the book "Hacker's Delight"
            int256 x = (a & b) + ((a ^ b) >> 1);
            return x + (int256(uint256(x) >> 255) & (a ^ b));
        }
        /**
         * @dev Returns the absolute unsigned value of a signed value.
         */
        function abs(int256 n) internal pure returns (uint256) {
            unchecked {
                // must be unchecked in order to support `n = type(int256).min`
                return uint256(n >= 0 ? n : -n);
            }
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)
    pragma solidity ^0.8.20;
    import {Math} from "./math/Math.sol";
    import {SignedMath} from "./math/SignedMath.sol";
    /**
     * @dev String operations.
     */
    library Strings {
        bytes16 private constant HEX_DIGITS = "0123456789abcdef";
        uint8 private constant ADDRESS_LENGTH = 20;
        /**
         * @dev The `value` string doesn't fit in the specified `length`.
         */
        error StringsInsufficientHexLength(uint256 value, uint256 length);
        /**
         * @dev Converts a `uint256` to its ASCII `string` decimal representation.
         */
        function toString(uint256 value) internal pure returns (string memory) {
            unchecked {
                uint256 length = Math.log10(value) + 1;
                string memory buffer = new string(length);
                uint256 ptr;
                /// @solidity memory-safe-assembly
                assembly {
                    ptr := add(buffer, add(32, length))
                }
                while (true) {
                    ptr--;
                    /// @solidity memory-safe-assembly
                    assembly {
                        mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
                    }
                    value /= 10;
                    if (value == 0) break;
                }
                return buffer;
            }
        }
        /**
         * @dev Converts a `int256` to its ASCII `string` decimal representation.
         */
        function toStringSigned(int256 value) internal pure returns (string memory) {
            return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
        }
        /**
         * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
         */
        function toHexString(uint256 value) internal pure returns (string memory) {
            unchecked {
                return toHexString(value, Math.log256(value) + 1);
            }
        }
        /**
         * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
         */
        function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
            uint256 localValue = value;
            bytes memory buffer = new bytes(2 * length + 2);
            buffer[0] = "0";
            buffer[1] = "x";
            for (uint256 i = 2 * length + 1; i > 1; --i) {
                buffer[i] = HEX_DIGITS[localValue & 0xf];
                localValue >>= 4;
            }
            if (localValue != 0) {
                revert StringsInsufficientHexLength(value, length);
            }
            return string(buffer);
        }
        /**
         * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
         * representation.
         */
        function toHexString(address addr) internal pure returns (string memory) {
            return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
        }
        /**
         * @dev Returns true if the two strings are equal.
         */
        function equal(string memory a, string memory b) internal pure returns (bool) {
            return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
        }
    }
    // SPDX-License-Identifier: GPL-2.0-or-later
    pragma solidity >=0.5.0;
    /// @title Callback for IUniswapV3PoolActions#swap
    /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
    interface IUniswapV3SwapCallback {
        /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
        /// @dev In the implementation you must pay the pool tokens owed for the swap.
        /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
        /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
        /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
        /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
        /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
        /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
        /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
        function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external;
    }
    // SPDX-License-Identifier: GPL-2.0-or-later
    pragma solidity >=0.7.5;
    pragma abicoder v2;
    import "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol";
    /// @title Router token swapping functionality
    /// @notice Functions for swapping tokens via Uniswap V3
    interface ISwapRouter is IUniswapV3SwapCallback {
        struct ExactInputSingleParams {
            address tokenIn;
            address tokenOut;
            uint24 fee;
            address recipient;
            uint256 deadline;
            uint256 amountIn;
            uint256 amountOutMinimum;
            uint160 sqrtPriceLimitX96;
        }
        /// @notice Swaps `amountIn` of one token for as much as possible of another token
        /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
        /// @return amountOut The amount of the received token
        function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
        struct ExactInputParams {
            bytes path;
            address recipient;
            uint256 deadline;
            uint256 amountIn;
            uint256 amountOutMinimum;
        }
        /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
        /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
        /// @return amountOut The amount of the received token
        function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
        struct ExactOutputSingleParams {
            address tokenIn;
            address tokenOut;
            uint24 fee;
            address recipient;
            uint256 deadline;
            uint256 amountOut;
            uint256 amountInMaximum;
            uint160 sqrtPriceLimitX96;
        }
        /// @notice Swaps as little as possible of one token for `amountOut` of another token
        /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
        /// @return amountIn The amount of the input token
        function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
        struct ExactOutputParams {
            bytes path;
            address recipient;
            uint256 deadline;
            uint256 amountOut;
            uint256 amountInMaximum;
        }
        /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
        /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
        /// @return amountIn The amount of the input token
        function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
    }
    // SPDX-License-Identifier: UNLICENSED
    pragma solidity ^0.8.24;
    import "@openzeppelin/contracts/access/Ownable.sol";
    import "@openzeppelin/contracts/interfaces/IERC20.sol";
    import "@openzeppelin/contracts/interfaces/IERC165.sol";
    import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
    import "@openzeppelin/contracts/utils/Strings.sol";
    import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol";
    import "erc721a/contracts/ERC721A.sol";
    import "./interfaces/IElement280.sol";
    import "./interfaces/IWETH9.sol";
    import "./lib/constants.sol";
    /// @title Element 280 NFT Contract
    contract ElementNFT is ERC721A, Ownable, IERC165 {
        using SafeERC20 for IERC20;
        using Strings for uint256;
        // --------------------------- STATE VARIABLES --------------------------- //
        address public immutable E280;
        address public treasury;
        uint256 private constant _BITPOS_NFT_TIER = 0;
        uint256 private constant _BITMASK_NFT_TIER = (1 << 8) - 1;
        uint256 private constant _BITPOS_TIMESTAMP = 8;
        uint256 private constant _BITMASK_TIMESTAMP = (1 << 64) - 1;
        uint256 private constant _BITPOS_MULTIPLIER = 72;
        uint256 private constant _BITMASK_MULTIPLIER = (1 << 16) - 1;
        /// @notice Total multipliers of all existing tokens.
        /// @dev Used in cycle reward calculation of the Element 280 Holder Vault contract.
        uint256 public multiplierPool;
        /// @notice Timestamp in seconds of the presale end date.
        uint256 public presaleEnd;
        string public contractURI;
        mapping(uint8 tier => string) public baseURIs;
        /// @notice Static multipliers per tier.
        mapping(uint8 tier => uint16) public tierMultipliers;
        /// @notice Static Element 280 token allocations per tier.
        /// @dev Also used for price calculation.
        mapping(uint8 tier => uint256) public tierAllocations;
        mapping(uint256 => uint256) private _packedTokenData;
        // --------------------------- EVENTS & MODIFIERS --------------------------- //
        event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);
        event ContractURIUpdated();
        modifier onlyPresale() {
            require(presaleEnd > block.timestamp, "Presale not active");
            _;
        }
        // --------------------------- CONSTRUCTOR --------------------------- //
        constructor(address _owner, address _treasury, string memory _contractURI, address _E280, string[] memory _baseURIs)
            ERC721A("Element 280", "ELMNT")
            Ownable(_owner)
        {
            require(_owner != address(0), "Owner address not provided");
            require(_treasury != address(0), "Treasury address not provided");
            require(_E280 != address(0), "E280 address not provided");
            require(_baseURIs.length == 6, "Incorrect number of base URIs sent");
            contractURI = _contractURI;
            E280 = _E280;
            treasury = _treasury;
            tierMultipliers[1] = 10;
            tierMultipliers[2] = 12;
            tierMultipliers[3] = 100;
            tierMultipliers[4] = 120;
            tierMultipliers[5] = 1000;
            tierMultipliers[6] = 1200;
            tierAllocations[1] = 100_000_000 ether;
            tierAllocations[2] = 100_000_000 ether;
            tierAllocations[3] = 1_000_000_000 ether;
            tierAllocations[4] = 1_000_000_000 ether;
            tierAllocations[5] = 10_000_000_000 ether;
            tierAllocations[6] = 10_000_000_000 ether;
            for (uint8 i = 0; i < _baseURIs.length; i++) {
                baseURIs[i + 1] = _baseURIs[i];
            }
        }
        // --------------------------- PUBLIC FUNCTIONS --------------------------- //
        /// @notice Mints NFTs using TitanX tokens during the presale.
        /// @param tieredNfts List of NFTs to mint, represented by their tier number.
        function mintWithTitanX(uint8[] calldata tieredNfts) public onlyPresale {
            (uint256 titanXPool, uint256 ampPool) = _processNftTiers(tieredNfts);
            IERC20 titanX = IERC20(TITANX);
            titanX.safeTransferFrom(msg.sender, E280, titanXPool);
            if (ampPool > 0) titanX.safeTransferFrom(msg.sender, treasury, ampPool);
            _mint(msg.sender, tieredNfts.length);
        }
        /// @notice Mints NFTs using Ethereum during the presale.
        /// @notice Refunds TitanX if the amount swapped is greater than the price.
        /// @param tieredNfts List of NFTs to mint, represented by their tier number.
        function mintWithEth(uint8[] calldata tieredNfts, uint256 deadline) public payable onlyPresale {
            (uint256 titanXPool, uint256 ampPool) = _processNftTiers(tieredNfts);
            uint256 totalTitanX;
            unchecked {
                totalTitanX = titanXPool + ampPool;
            }
            uint256 swappedAmount = _swapETHForTitanX(totalTitanX, deadline);
            IERC20 titanX = IERC20(TITANX);
            titanX.safeTransfer(E280, titanXPool);
            if (ampPool > 0) titanX.safeTransfer(treasury, ampPool);
            _mint(msg.sender, tieredNfts.length);
            if (swappedAmount > totalTitanX) {
                titanX.safeTransfer(msg.sender, swappedAmount - totalTitanX);
            }
        }
        /// @notice Burns the NFT and mints Element 280 tokens to the user.
        /// @param tokenIds An array of token IDs to redeem.
        function redeemNFTs(uint256[] calldata tokenIds) external {
            uint256 totalAllocation;
            require(tokenIds.length > 0, "Empty array");
            address initialOwner = ownerOf(tokenIds[0]);
            for (uint256 i = 0; i < tokenIds.length; i++) {
                uint256 tokenId = tokenIds[i];
                uint256 data = _packedTokenData[tokenId];
                require(block.timestamp > _getTimestamp(data) + COOLDOWN_PERIOD, "Cooldown is active");
                uint8 tier = _getNftTier(data);
                unchecked {
                    totalAllocation += tierAllocations[tier];
                    multiplierPool -= _getMultiplier(data);
                    require(initialOwner == ownerOf(tokenId), "NFT not owned by same user");
                }
                _burn(tokenId, true);
            }
            IElement280(E280).handleRedeem(totalAllocation, initialOwner);
        }
        // --------------------------- ADMINISTRATIVE FUNCTIONS --------------------------- //
        /// @notice Starts the presale with a specific end date.
        /// @param _presaleEnd The timestamp when the presale will end.
        /// @dev Can only be called by the E280 contract.
        function startPresale(uint256 _presaleEnd) external {
            require(msg.sender == address(E280), "Unauthorized");
            presaleEnd = _presaleEnd;
        }
        /// @notice Sets the contract-level metadata URI.
        /// @param _uri The URI of the contract metadata.
        function setContractURI(string memory _uri) external onlyOwner {
            contractURI = _uri;
            emit ContractURIUpdated();
        }
        /// @notice Sets the base URI for a specific tier.
        /// @param tier The NFT tier to set the URI for.
        /// @param _uri The base URI for the specified tier.
        function setBaseURI(uint8 tier, string memory _uri) external onlyOwner {
            baseURIs[tier] = _uri;
            emit BatchMetadataUpdate(1, type(uint256).max);
        }
        // --------------------------- VIEW FUNCTIONS --------------------------- //
        /// @notice Calculates the total allocation of Element 280 tokens for a set of NFTs.
        /// @param tokenIds An array of token IDs to calculate allocations for.
        /// @return totalAllocation The total allocation of Element 280 tokens in WEI.
        function calculateAllocation(uint256[] calldata tokenIds) external view returns (uint256) {
            require(tokenIds.length > 0, "No tokens provided");
            uint256 totalAllocation;
            for (uint256 i = 0; i < tokenIds.length; i++) {
                for (uint256 j = i + 1; j < tokenIds.length; j++) {
                    require(tokenIds[i] != tokenIds[j], "Duplicate token ID");
                }
                unchecked {
                    require(_exists(tokenIds[i]), "Token ID does not exist");
                    totalAllocation += tierAllocations[getNftTier(tokenIds[i])];
                }
            }
            return totalAllocation;
        }
        /// @notice Returns a tier number for a specific token ID.
        /// @param tokenId Token ID of the token.
        /// @return Tier of the NFT.
        function getNftTier(uint256 tokenId) public view returns (uint8) {
            uint256 packedData = _packedTokenData[tokenId];
            return _getNftTier(packedData);
        }
        /// @notice Returns time of purchase for a specific token ID.
        /// @param tokenId Token ID of the token.
        /// @return Time of purchase in seconds.
        function getTimestamp(uint256 tokenId) public view returns (uint64) {
            uint256 packedData = _packedTokenData[tokenId];
            return _getTimestamp(packedData);
        }
        /// @notice Returns a multiplier for a specific token ID.
        /// @param tokenId Token ID of the token.
        /// @return Multiplier of the NFT.
        function getMultiplier(uint256 tokenId) public view returns (uint64) {
            uint256 packedData = _packedTokenData[tokenId];
            return _getMultiplier(packedData);
        }
        /// @notice Retrieves the timestamps and multipliers of the specified NFTs.
        /// @param tokenIds An array of token IDs to query.
        /// @param nftOwner The owner address of the NFTs.
        /// @return timestamps An array of timestamps for each token.
        /// @return multipliers An array of multipliers for each token.
        /// @dev Used by Holder Vault to calculate cycle rewards.
        function getBatchedTokensData(uint256[] calldata tokenIds, address nftOwner)
            external
            view
            returns (uint256[] memory timestamps, uint16[] memory multipliers)
        {
            timestamps = new uint256[](tokenIds.length);
            multipliers = new uint16[](tokenIds.length);
            for (uint256 i = 0; i < tokenIds.length; i++) {
                uint256 tokenId = tokenIds[i];
                require(ownerOf(tokenId) == nftOwner, "Unauthorized");
                uint256 packedData = _packedTokenData[tokenId];
                timestamps[i] = _getTimestamp(packedData);
                multipliers[i] = _getMultiplier(packedData);
            }
        }
        /// @notice Returns the total number of NFTs per tier.
        /// @return total An array where each index corresponds to the total NFTs for a specific tier.
        /// @dev Should not be called by contracts.
        function getTotalNftsPerTiers() external view returns (uint256[] memory total) {
            uint256 totalTokenIds = _nextTokenId();
            total = new uint256[](6);
            for (uint256 tokenId = 1; tokenId < totalTokenIds; tokenId++) {
                if (_exists(tokenId)) {
                    total[_getNftTier(_packedTokenData[tokenId]) - 1]++;
                }
            }
        }
        /// @notice Returns all token IDs owned by a specific account.
        /// @param account The address of the token owner.
        /// @return tokenIds An array of token IDs owned by the account.
        /// @dev Should not be called by contracts.
        function tokenIdsOf(address account) external view returns (uint256[] memory tokenIds) {
            uint256 totalTokenIds = _nextTokenId();
            uint256 userBalance = balanceOf(account);
            tokenIds = new uint256[](userBalance);
            if (userBalance == 0) return tokenIds;
            uint256 counter;
            for (uint256 tokenId = 1; tokenId < totalTokenIds; tokenId++) {
                if (_exists(tokenId) && ownerOf(tokenId) == account) {
                    tokenIds[counter] = tokenId;
                    counter++;
                    if (counter == userBalance) return tokenIds;
                }
            }
        }
        /// @notice Returns the total TitanX amount required for minting the given list of NFTs.
        /// @param tieredNfts An array of NFT to mint, represented by their respected tiers.
        /// @return titanXPool The total TitanX required for the minting transaction (in WEI).
        function getTotalPrice(uint8[] calldata tieredNfts) external view returns (uint256 titanXPool) {
            for (uint256 i = 0; i < tieredNfts.length; i++) {
                uint8 tier = tieredNfts[i];
                (bool isValid, bool isAmped) = _processTier(tier);
                require(isValid, "Not a valid tier");
                unchecked {
                    titanXPool += tierAllocations[tier];
                    if (isAmped) titanXPool += tierAllocations[tier] * 10 / 100;
                }
            }
        }
        /// @notice Returns the total number of NFTs burned.
        function totalBurned() external view returns (uint256) {
            return _totalBurned();
        }
        function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
            require(_exists(tokenId), "URI query for nonexistent token");
            return bytes(baseURIs[getNftTier(tokenId)]).length != 0 ? baseURIs[getNftTier(tokenId)] : "";
        }
        function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721A) returns (bool) {
            return interfaceId == INTERFACE_ID_ERC165 || interfaceId == INTERFACE_ID_ERC721
                || interfaceId == INTERFACE_ID_ERC721Metadata || super.supportsInterface(interfaceId);
        }
        // --------------------------- INTERNAL FUNCTIONS --------------------------- //
        function _startTokenId() internal view virtual override returns (uint256) {
            return 1;
        }
        function _processNftTiers(uint8[] calldata tieredNfts) internal returns (uint256 titanXPool, uint256 ampPool) {
            require(tieredNfts.length > 0, "Need to mint at least 1 NFT");
            uint256 currentIndex = _nextTokenId();
            for (uint256 i = 0; i < tieredNfts.length; i++) {
                uint8 tier = tieredNfts[i];
                (bool isValid, bool isAmped) = _processTier(tier);
                require(isValid, "Not a valid tier");
                uint16 multiplier = tierMultipliers[tier];
                _setNftData(currentIndex + i, tier, uint64(block.timestamp), multiplier);
                unchecked {
                    multiplierPool += multiplier;
                    titanXPool += tierAllocations[tier];
                    if (isAmped) ampPool += tierAllocations[tier] * 10 / 100;
                }
            }
        }
        function _packData(uint8 nftTier, uint64 timestamp, uint16 multiplier) internal pure returns (uint256) {
            return (uint256(nftTier) << _BITPOS_NFT_TIER) | (uint256(timestamp) << _BITPOS_TIMESTAMP)
                | (uint256(multiplier) << _BITPOS_MULTIPLIER);
        }
        function _getNftTier(uint256 packedData) internal pure returns (uint8) {
            return uint8(packedData & _BITMASK_NFT_TIER);
        }
        function _getTimestamp(uint256 packedData) internal pure returns (uint64) {
            return uint64((packedData >> _BITPOS_TIMESTAMP) & _BITMASK_TIMESTAMP);
        }
        function _getMultiplier(uint256 packedData) internal pure returns (uint16) {
            return uint16((packedData >> _BITPOS_MULTIPLIER) & _BITMASK_MULTIPLIER);
        }
        function _setNftData(uint256 tokenId, uint8 nftTier, uint64 timestamp, uint16 multiplier) internal {
            uint256 packedData = _packData(nftTier, timestamp, multiplier);
            _packedTokenData[tokenId] = packedData;
        }
        function _processTier(uint8 tier) private pure returns (bool isValid, bool isAmped) {
            return (tier > 0 && tier < 7, tier % 2 == 0);
        }
        function _swapETHForTitanX(uint256 minAmountOut, uint256 deadline) internal returns (uint256) {
            IWETH9(WETH9).deposit{value: msg.value}();
            ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams({
                tokenIn: WETH9,
                tokenOut: TITANX,
                fee: POOL_FEE_1PERCENT,
                recipient: address(this),
                deadline: deadline,
                amountIn: msg.value,
                amountOutMinimum: minAmountOut,
                sqrtPriceLimitX96: 0
            });
            IERC20(WETH9).safeIncreaseAllowance(UNISWAP_V3_ROUTER, msg.value);
            uint256 amountOut = ISwapRouter(UNISWAP_V3_ROUTER).exactInputSingle(params);
            return amountOut;
        }
    }
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.24;
    import "./IERC20Burnable.sol";
    interface IElement280 is IERC20Burnable {
        function presaleEnd() external returns (uint256);
        function handleRedeem(uint256 amount, address receiver) external;
    }
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.24;
    interface IERC20Burnable {
        function burn(uint256 value) external;
        function balanceOf(address account) external view returns (uint256);
        function transfer(address to, uint256 value) external returns (bool);
        function transferFrom(address from, address to, uint256 value) external returns (bool);
    }
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.10;
    interface ITitanOnBurn {
        function onBurn(address user, uint256 amount) external;
    }
    // SPDX-License-Identifier: GPL-2.0-or-later
    pragma solidity ^0.8.10;
    import "@openzeppelin/contracts/interfaces/IERC20.sol";
    /// @title Interface for WETH9
    interface IWETH9 is IERC20 {
        /// @notice Deposit ether to get wrapped ether
        function deposit() external payable;
        /// @notice Withdraw wrapped ether to get ether
        function withdraw(uint256) external;
    }
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.24;
    import "../interfaces/ITitanOnBurn.sol";
    import "@openzeppelin/contracts/interfaces/IERC20.sol";
    // ===================== Contract Addresses =====================================
    uint8 constant NUM_ECOSYSTEM_TOKENS = 14;
    address constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
    address constant TITANX = 0xF19308F923582A6f7c465e5CE7a9Dc1BEC6665B1;
    address constant HYPER_ADDRESS = 0xE2cfD7a01ec63875cd9Da6C7c1B7025166c2fA2F;
    address constant HELIOS_ADDRESS = 0x2614f29C39dE46468A921Fd0b41fdd99A01f2EDf;
    address constant DRAGONX_ADDRESS = 0x96a5399D07896f757Bd4c6eF56461F58DB951862;
    address constant BDX_ADDRESS = 0x9f278Dc799BbC61ecB8e5Fb8035cbfA29803623B;
    address constant BLAZE_ADDRESS = 0xfcd7cceE4071aA4ecFAC1683b7CC0aFeCAF42A36;
    address constant INFERNO_ADDRESS = 0x00F116ac0c304C570daAA68FA6c30a86A04B5C5F;
    address constant HYDRA_ADDRESS = 0xCC7ed2ab6c3396DdBc4316D2d7C1b59ff9d2091F;
    address constant AWESOMEX_ADDRESS = 0xa99AFcC6Aa4530d01DFFF8E55ec66E4C424c048c;
    address constant FLUX_ADDRESS = 0xBFDE5ac4f5Adb419A931a5bF64B0f3BB5a623d06;
    address constant DRAGONX_BURN_ADDRESS = 0x1d59429571d8Fde785F45bf593E94F2Da6072Edb;
    // ===================== Presale ================================================
    uint256 constant PRESALE_LENGTH = 28 days;
    uint256 constant COOLDOWN_PERIOD = 48 hours;
    uint256 constant LP_POOL_SIZE = 200_000_000_000 ether;
    // ===================== Fees ===================================================
    uint256 constant DEV_PERCENT = 6;
    uint256 constant TREASURY_PERCENT = 4;
    uint256 constant BURN_PERCENT = 10;
    // ===================== Sell Tax ===============================================
    uint256 constant PRESALE_TRANSFER_TAX_PERCENTAGE = 16;
    uint256 constant TRANSFER_TAX_PERCENTAGE = 4;
    uint256 constant NFT_REDEEM_TAX_PERCENTAGE = 3;
    // ===================== Holder Vault ===========================================
    uint16 constant MAX_CYCLES_PER_CLAIM = 100;
    uint32 constant CYCLE_INTERVAL = 7 days;
    // ===================== UNISWAP Interface ======================================
    address constant UNISWAP_V2_FACTORY = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
    address constant UNISWAP_V2_ROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
    address constant UNISWAP_V3_ROUTER = 0xE592427A0AEce92De3Edee1F18E0157C05861564;
    uint24 constant POOL_FEE_1PERCENT = 10000;
    // ===================== Interface IDs ==========================================
    bytes4 constant INTERFACE_ID_ERC165 = 0x01ffc9a7;
    bytes4 constant INTERFACE_ID_ERC20 = type(IERC20).interfaceId;
    bytes4 constant INTERFACE_ID_ERC721 = 0x80ac58cd;
    bytes4 constant INTERFACE_ID_ERC721Metadata = 0x5b5e139f;
    bytes4 constant INTERFACE_ID_ITITANONBURN = type(ITitanOnBurn).interfaceId;
    // SPDX-License-Identifier: MIT
    // ERC721A Contracts v4.3.0
    // Creator: Chiru Labs
    pragma solidity ^0.8.4;
    import "./IERC721A.sol";
    /**
     * @dev Interface of ERC721 token receiver.
     */
    interface ERC721A__IERC721Receiver {
        function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data)
            external
            returns (bytes4);
    }
    /**
     * @title ERC721A
     *
     * @dev Implementation of the [ERC721](https://eips.ethereum.org/EIPS/eip-721)
     * Non-Fungible Token Standard, including the Metadata extension.
     * Optimized for lower gas during batch mints.
     *
     * Token IDs are minted in sequential order (e.g. 0, 1, 2, 3, ...)
     * starting from `_startTokenId()`.
     *
     * The `_sequentialUpTo()` function can be overriden to enable spot mints
     * (i.e. non-consecutive mints) for `tokenId`s greater than `_sequentialUpTo()`.
     *
     * Assumptions:
     *
     * - An owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
     * - The maximum token ID cannot exceed 2**256 - 1 (max value of uint256).
     */
    contract ERC721A is IERC721A {
        // Bypass for a `--via-ir` bug (https://github.com/chiru-labs/ERC721A/pull/364).
        struct TokenApprovalRef {
            address value;
        }
        // =============================================================
        //                           CONSTANTS
        // =============================================================
        // Mask of an entry in packed address data.
        uint256 private constant _BITMASK_ADDRESS_DATA_ENTRY = (1 << 64) - 1;
        // The bit position of `numberMinted` in packed address data.
        uint256 private constant _BITPOS_NUMBER_MINTED = 64;
        // The bit position of `numberBurned` in packed address data.
        uint256 private constant _BITPOS_NUMBER_BURNED = 128;
        // The bit position of `aux` in packed address data.
        uint256 private constant _BITPOS_AUX = 192;
        // Mask of all 256 bits in packed address data except the 64 bits for `aux`.
        uint256 private constant _BITMASK_AUX_COMPLEMENT = (1 << 192) - 1;
        // The bit position of `startTimestamp` in packed ownership.
        uint256 private constant _BITPOS_START_TIMESTAMP = 160;
        // The bit mask of the `burned` bit in packed ownership.
        uint256 private constant _BITMASK_BURNED = 1 << 224;
        // The bit position of the `nextInitialized` bit in packed ownership.
        uint256 private constant _BITPOS_NEXT_INITIALIZED = 225;
        // The bit mask of the `nextInitialized` bit in packed ownership.
        uint256 private constant _BITMASK_NEXT_INITIALIZED = 1 << 225;
        // The bit position of `extraData` in packed ownership.
        uint256 private constant _BITPOS_EXTRA_DATA = 232;
        // Mask of all 256 bits in a packed ownership except the 24 bits for `extraData`.
        uint256 private constant _BITMASK_EXTRA_DATA_COMPLEMENT = (1 << 232) - 1;
        // The mask of the lower 160 bits for addresses.
        uint256 private constant _BITMASK_ADDRESS = (1 << 160) - 1;
        // The maximum `quantity` that can be minted with {_mintERC2309}.
        // This limit is to prevent overflows on the address data entries.
        // For a limit of 5000, a total of 3.689e15 calls to {_mintERC2309}
        // is required to cause an overflow, which is unrealistic.
        uint256 private constant _MAX_MINT_ERC2309_QUANTITY_LIMIT = 5000;
        // The `Transfer` event signature is given by:
        // `keccak256(bytes("Transfer(address,address,uint256)"))`.
        bytes32 private constant _TRANSFER_EVENT_SIGNATURE =
            0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;
        // =============================================================
        //                            STORAGE
        // =============================================================
        // The next token ID to be minted.
        uint256 private _currentIndex;
        // The number of tokens burned.
        uint256 private _burnCounter;
        // Token name
        string private _name;
        // Token symbol
        string private _symbol;
        // Mapping from token ID to ownership details
        // An empty struct value does not necessarily mean the token is unowned.
        // See {_packedOwnershipOf} implementation for details.
        //
        // Bits Layout:
        // - [0..159]   `addr`
        // - [160..223] `startTimestamp`
        // - [224]      `burned`
        // - [225]      `nextInitialized`
        // - [232..255] `extraData`
        mapping(uint256 => uint256) private _packedOwnerships;
        // Mapping owner address to address data.
        //
        // Bits Layout:
        // - [0..63]    `balance`
        // - [64..127]  `numberMinted`
        // - [128..191] `numberBurned`
        // - [192..255] `aux`
        mapping(address => uint256) private _packedAddressData;
        // Mapping from token ID to approved address.
        mapping(uint256 => TokenApprovalRef) private _tokenApprovals;
        // Mapping from owner to operator approvals
        mapping(address => mapping(address => bool)) private _operatorApprovals;
        // The amount of tokens minted above `_sequentialUpTo()`.
        // We call these spot mints (i.e. non-sequential mints).
        uint256 private _spotMinted;
        // =============================================================
        //                          CONSTRUCTOR
        // =============================================================
        constructor(string memory name_, string memory symbol_) {
            _name = name_;
            _symbol = symbol_;
            _currentIndex = _startTokenId();
            if (_sequentialUpTo() < _startTokenId()) _revert(SequentialUpToTooSmall.selector);
        }
        // =============================================================
        //                   TOKEN COUNTING OPERATIONS
        // =============================================================
        /**
         * @dev Returns the starting token ID for sequential mints.
         *
         * Override this function to change the starting token ID for sequential mints.
         *
         * Note: The value returned must never change after any tokens have been minted.
         */
        function _startTokenId() internal view virtual returns (uint256) {
            return 0;
        }
        /**
         * @dev Returns the maximum token ID (inclusive) for sequential mints.
         *
         * Override this function to return a value less than 2**256 - 1,
         * but greater than `_startTokenId()`, to enable spot (non-sequential) mints.
         *
         * Note: The value returned must never change after any tokens have been minted.
         */
        function _sequentialUpTo() internal view virtual returns (uint256) {
            return type(uint256).max;
        }
        /**
         * @dev Returns the next token ID to be minted.
         */
        function _nextTokenId() internal view virtual returns (uint256) {
            return _currentIndex;
        }
        /**
         * @dev Returns the total number of tokens in existence.
         * Burned tokens will reduce the count.
         * To get the total number of tokens minted, please see {_totalMinted}.
         */
        function totalSupply() public view virtual override returns (uint256 result) {
            // Counter underflow is impossible as `_burnCounter` cannot be incremented
            // more than `_currentIndex + _spotMinted - _startTokenId()` times.
            unchecked {
                // With spot minting, the intermediate `result` can be temporarily negative,
                // and the computation must be unchecked.
                result = _currentIndex - _burnCounter - _startTokenId();
                if (_sequentialUpTo() != type(uint256).max) result += _spotMinted;
            }
        }
        /**
         * @dev Returns the total amount of tokens minted in the contract.
         */
        function _totalMinted() internal view virtual returns (uint256 result) {
            // Counter underflow is impossible as `_currentIndex` does not decrement,
            // and it is initialized to `_startTokenId()`.
            unchecked {
                result = _currentIndex - _startTokenId();
                if (_sequentialUpTo() != type(uint256).max) result += _spotMinted;
            }
        }
        /**
         * @dev Returns the total number of tokens burned.
         */
        function _totalBurned() internal view virtual returns (uint256) {
            return _burnCounter;
        }
        /**
         * @dev Returns the total number of tokens that are spot-minted.
         */
        function _totalSpotMinted() internal view virtual returns (uint256) {
            return _spotMinted;
        }
        // =============================================================
        //                    ADDRESS DATA OPERATIONS
        // =============================================================
        /**
         * @dev Returns the number of tokens in `owner`'s account.
         */
        function balanceOf(address owner) public view virtual override returns (uint256) {
            if (owner == address(0)) _revert(BalanceQueryForZeroAddress.selector);
            return _packedAddressData[owner] & _BITMASK_ADDRESS_DATA_ENTRY;
        }
        /**
         * Returns the number of tokens minted by `owner`.
         */
        function _numberMinted(address owner) internal view returns (uint256) {
            return (_packedAddressData[owner] >> _BITPOS_NUMBER_MINTED) & _BITMASK_ADDRESS_DATA_ENTRY;
        }
        /**
         * Returns the number of tokens burned by or on behalf of `owner`.
         */
        function _numberBurned(address owner) internal view returns (uint256) {
            return (_packedAddressData[owner] >> _BITPOS_NUMBER_BURNED) & _BITMASK_ADDRESS_DATA_ENTRY;
        }
        /**
         * Returns the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).
         */
        function _getAux(address owner) internal view returns (uint64) {
            return uint64(_packedAddressData[owner] >> _BITPOS_AUX);
        }
        /**
         * Sets the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).
         * If there are multiple variables, please pack them into a uint64.
         */
        function _setAux(address owner, uint64 aux) internal virtual {
            uint256 packed = _packedAddressData[owner];
            uint256 auxCasted;
            // Cast `aux` with assembly to avoid redundant masking.
            assembly {
                auxCasted := aux
            }
            packed = (packed & _BITMASK_AUX_COMPLEMENT) | (auxCasted << _BITPOS_AUX);
            _packedAddressData[owner] = packed;
        }
        // =============================================================
        //                            IERC165
        // =============================================================
        /**
         * @dev Returns true if this contract implements the interface defined by
         * `interfaceId`. See the corresponding
         * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
         * to learn more about how these ids are created.
         *
         * This function call must use less than 30000 gas.
         */
        function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
            // The interface IDs are constants representing the first 4 bytes
            // of the XOR of all function selectors in the interface.
            // See: [ERC165](https://eips.ethereum.org/EIPS/eip-165)
            // (e.g. `bytes4(i.functionA.selector ^ i.functionB.selector ^ ...)`)
            return interfaceId == 0x01ffc9a7 // ERC165 interface ID for ERC165.
                || interfaceId == 0x80ac58cd // ERC165 interface ID for ERC721.
                || interfaceId == 0x5b5e139f; // ERC165 interface ID for ERC721Metadata.
        }
        // =============================================================
        //                        IERC721Metadata
        // =============================================================
        /**
         * @dev Returns the token collection name.
         */
        function name() public view virtual override returns (string memory) {
            return _name;
        }
        /**
         * @dev Returns the token collection symbol.
         */
        function symbol() public view virtual override returns (string memory) {
            return _symbol;
        }
        /**
         * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
         */
        function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
            if (!_exists(tokenId)) _revert(URIQueryForNonexistentToken.selector);
            string memory baseURI = _baseURI();
            return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, _toString(tokenId))) : "";
        }
        /**
         * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
         * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
         * by default, it can be overridden in child contracts.
         */
        function _baseURI() internal view virtual returns (string memory) {
            return "";
        }
        // =============================================================
        //                     OWNERSHIPS OPERATIONS
        // =============================================================
        /**
         * @dev Returns the owner of the `tokenId` token.
         *
         * Requirements:
         *
         * - `tokenId` must exist.
         */
        function ownerOf(uint256 tokenId) public view virtual override returns (address) {
            return address(uint160(_packedOwnershipOf(tokenId)));
        }
        /**
         * @dev Gas spent here starts off proportional to the maximum mint batch size.
         * It gradually moves to O(1) as tokens get transferred around over time.
         */
        function _ownershipOf(uint256 tokenId) internal view virtual returns (TokenOwnership memory) {
            return _unpackedOwnership(_packedOwnershipOf(tokenId));
        }
        /**
         * @dev Returns the unpacked `TokenOwnership` struct at `index`.
         */
        function _ownershipAt(uint256 index) internal view virtual returns (TokenOwnership memory) {
            return _unpackedOwnership(_packedOwnerships[index]);
        }
        /**
         * @dev Returns whether the ownership slot at `index` is initialized.
         * An uninitialized slot does not necessarily mean that the slot has no owner.
         */
        function _ownershipIsInitialized(uint256 index) internal view virtual returns (bool) {
            return _packedOwnerships[index] != 0;
        }
        /**
         * @dev Initializes the ownership slot minted at `index` for efficiency purposes.
         */
        function _initializeOwnershipAt(uint256 index) internal virtual {
            if (_packedOwnerships[index] == 0) {
                _packedOwnerships[index] = _packedOwnershipOf(index);
            }
        }
        /**
         * @dev Returns the packed ownership data of `tokenId`.
         */
        function _packedOwnershipOf(uint256 tokenId) private view returns (uint256 packed) {
            if (_startTokenId() <= tokenId) {
                packed = _packedOwnerships[tokenId];
                if (tokenId > _sequentialUpTo()) {
                    if (_packedOwnershipExists(packed)) return packed;
                    _revert(OwnerQueryForNonexistentToken.selector);
                }
                // If the data at the starting slot does not exist, start the scan.
                if (packed == 0) {
                    if (tokenId >= _currentIndex) _revert(OwnerQueryForNonexistentToken.selector);
                    // Invariant:
                    // There will always be an initialized ownership slot
                    // (i.e. `ownership.addr != address(0) && ownership.burned == false`)
                    // before an unintialized ownership slot
                    // (i.e. `ownership.addr == address(0) && ownership.burned == false`)
                    // Hence, `tokenId` will not underflow.
                    //
                    // We can directly compare the packed value.
                    // If the address is zero, packed will be zero.
                    for (;;) {
                        unchecked {
                            packed = _packedOwnerships[--tokenId];
                        }
                        if (packed == 0) continue;
                        if (packed & _BITMASK_BURNED == 0) return packed;
                        // Otherwise, the token is burned, and we must revert.
                        // This handles the case of batch burned tokens, where only the burned bit
                        // of the starting slot is set, and remaining slots are left uninitialized.
                        _revert(OwnerQueryForNonexistentToken.selector);
                    }
                }
                // Otherwise, the data exists and we can skip the scan.
                // This is possible because we have already achieved the target condition.
                // This saves 2143 gas on transfers of initialized tokens.
                // If the token is not burned, return `packed`. Otherwise, revert.
                if (packed & _BITMASK_BURNED == 0) return packed;
            }
            _revert(OwnerQueryForNonexistentToken.selector);
        }
        /**
         * @dev Returns the unpacked `TokenOwnership` struct from `packed`.
         */
        function _unpackedOwnership(uint256 packed) private pure returns (TokenOwnership memory ownership) {
            ownership.addr = address(uint160(packed));
            ownership.startTimestamp = uint64(packed >> _BITPOS_START_TIMESTAMP);
            ownership.burned = packed & _BITMASK_BURNED != 0;
            ownership.extraData = uint24(packed >> _BITPOS_EXTRA_DATA);
        }
        /**
         * @dev Packs ownership data into a single uint256.
         */
        function _packOwnershipData(address owner, uint256 flags) private view returns (uint256 result) {
            assembly {
                // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean.
                owner := and(owner, _BITMASK_ADDRESS)
                // `owner | (block.timestamp << _BITPOS_START_TIMESTAMP) | flags`.
                result := or(owner, or(shl(_BITPOS_START_TIMESTAMP, timestamp()), flags))
            }
        }
        /**
         * @dev Returns the `nextInitialized` flag set if `quantity` equals 1.
         */
        function _nextInitializedFlag(uint256 quantity) private pure returns (uint256 result) {
            // For branchless setting of the `nextInitialized` flag.
            assembly {
                // `(quantity == 1) << _BITPOS_NEXT_INITIALIZED`.
                result := shl(_BITPOS_NEXT_INITIALIZED, eq(quantity, 1))
            }
        }
        // =============================================================
        //                      APPROVAL OPERATIONS
        // =============================================================
        /**
         * @dev Gives permission to `to` to transfer `tokenId` token to another account. See {ERC721A-_approve}.
         *
         * Requirements:
         *
         * - The caller must own the token or be an approved operator.
         */
        function approve(address to, uint256 tokenId) public payable virtual override {
            _approve(to, tokenId, true);
        }
        /**
         * @dev Returns the account approved for `tokenId` token.
         *
         * Requirements:
         *
         * - `tokenId` must exist.
         */
        function getApproved(uint256 tokenId) public view virtual override returns (address) {
            if (!_exists(tokenId)) _revert(ApprovalQueryForNonexistentToken.selector);
            return _tokenApprovals[tokenId].value;
        }
        /**
         * @dev Approve or remove `operator` as an operator for the caller.
         * Operators can call {transferFrom} or {safeTransferFrom}
         * for any token owned by the caller.
         *
         * Requirements:
         *
         * - The `operator` cannot be the caller.
         *
         * Emits an {ApprovalForAll} event.
         */
        function setApprovalForAll(address operator, bool approved) public virtual override {
            _operatorApprovals[_msgSenderERC721A()][operator] = approved;
            emit ApprovalForAll(_msgSenderERC721A(), operator, approved);
        }
        /**
         * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
         *
         * See {setApprovalForAll}.
         */
        function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
            return _operatorApprovals[owner][operator];
        }
        /**
         * @dev Returns whether `tokenId` exists.
         *
         * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
         *
         * Tokens start existing when they are minted. See {_mint}.
         */
        function _exists(uint256 tokenId) internal view virtual returns (bool result) {
            if (_startTokenId() <= tokenId) {
                if (tokenId > _sequentialUpTo()) return _packedOwnershipExists(_packedOwnerships[tokenId]);
                if (tokenId < _currentIndex) {
                    uint256 packed;
                    while ((packed = _packedOwnerships[tokenId]) == 0) --tokenId;
                    result = packed & _BITMASK_BURNED == 0;
                }
            }
        }
        /**
         * @dev Returns whether `packed` represents a token that exists.
         */
        function _packedOwnershipExists(uint256 packed) private pure returns (bool result) {
            assembly {
                // The following is equivalent to `owner != address(0) && burned == false`.
                // Symbolically tested.
                result := gt(and(packed, _BITMASK_ADDRESS), and(packed, _BITMASK_BURNED))
            }
        }
        /**
         * @dev Returns whether `msgSender` is equal to `approvedAddress` or `owner`.
         */
        function _isSenderApprovedOrOwner(address approvedAddress, address owner, address msgSender)
            private
            pure
            returns (bool result)
        {
            assembly {
                // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean.
                owner := and(owner, _BITMASK_ADDRESS)
                // Mask `msgSender` to the lower 160 bits, in case the upper bits somehow aren't clean.
                msgSender := and(msgSender, _BITMASK_ADDRESS)
                // `msgSender == owner || msgSender == approvedAddress`.
                result := or(eq(msgSender, owner), eq(msgSender, approvedAddress))
            }
        }
        /**
         * @dev Returns the storage slot and value for the approved address of `tokenId`.
         */
        function _getApprovedSlotAndAddress(uint256 tokenId)
            private
            view
            returns (uint256 approvedAddressSlot, address approvedAddress)
        {
            TokenApprovalRef storage tokenApproval = _tokenApprovals[tokenId];
            // The following is equivalent to `approvedAddress = _tokenApprovals[tokenId].value`.
            assembly {
                approvedAddressSlot := tokenApproval.slot
                approvedAddress := sload(approvedAddressSlot)
            }
        }
        // =============================================================
        //                      TRANSFER OPERATIONS
        // =============================================================
        /**
         * @dev Transfers `tokenId` from `from` to `to`.
         *
         * Requirements:
         *
         * - `from` cannot be the zero address.
         * - `to` cannot be the zero address.
         * - `tokenId` token must be owned by `from`.
         * - If the caller is not `from`, it must be approved to move this token
         * by either {approve} or {setApprovalForAll}.
         *
         * Emits a {Transfer} event.
         */
        function transferFrom(address from, address to, uint256 tokenId) public payable virtual override {
            uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
            // Mask `from` to the lower 160 bits, in case the upper bits somehow aren't clean.
            from = address(uint160(uint256(uint160(from)) & _BITMASK_ADDRESS));
            if (address(uint160(prevOwnershipPacked)) != from) _revert(TransferFromIncorrectOwner.selector);
            (uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
            // The nested ifs save around 20+ gas over a compound boolean condition.
            if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A())) {
                if (!isApprovedForAll(from, _msgSenderERC721A())) _revert(TransferCallerNotOwnerNorApproved.selector);
            }
            _beforeTokenTransfers(from, to, tokenId, 1);
            // Clear approvals from the previous owner.
            assembly {
                if approvedAddress {
                    // This is equivalent to `delete _tokenApprovals[tokenId]`.
                    sstore(approvedAddressSlot, 0)
                }
            }
            // Underflow of the sender's balance is impossible because we check for
            // ownership above and the recipient's balance can't realistically overflow.
            // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.
            unchecked {
                // We can directly increment and decrement the balances.
                --_packedAddressData[from]; // Updates: `balance -= 1`.
                ++_packedAddressData[to]; // Updates: `balance += 1`.
                // Updates:
                // - `address` to the next owner.
                // - `startTimestamp` to the timestamp of transfering.
                // - `burned` to `false`.
                // - `nextInitialized` to `true`.
                _packedOwnerships[tokenId] =
                    _packOwnershipData(to, _BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked));
                // If the next slot may not have been initialized (i.e. `nextInitialized == false`) .
                if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
                    uint256 nextTokenId = tokenId + 1;
                    // If the next slot's address is zero and not burned (i.e. packed value is zero).
                    if (_packedOwnerships[nextTokenId] == 0) {
                        // If the next slot is within bounds.
                        if (nextTokenId != _currentIndex) {
                            // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
                            _packedOwnerships[nextTokenId] = prevOwnershipPacked;
                        }
                    }
                }
            }
            // Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean.
            uint256 toMasked = uint256(uint160(to)) & _BITMASK_ADDRESS;
            assembly {
                // Emit the `Transfer` event.
                log4(
                    0, // Start of data (0, since no data).
                    0, // End of data (0, since no data).
                    _TRANSFER_EVENT_SIGNATURE, // Signature.
                    from, // `from`.
                    toMasked, // `to`.
                    tokenId // `tokenId`.
                )
            }
            if (toMasked == 0) _revert(TransferToZeroAddress.selector);
            _afterTokenTransfers(from, to, tokenId, 1);
        }
        /**
         * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.
         */
        function safeTransferFrom(address from, address to, uint256 tokenId) public payable virtual override {
            safeTransferFrom(from, to, tokenId, "");
        }
        /**
         * @dev Safely transfers `tokenId` token from `from` to `to`.
         *
         * Requirements:
         *
         * - `from` cannot be the zero address.
         * - `to` cannot be the zero address.
         * - `tokenId` token must exist and be owned by `from`.
         * - If the caller is not `from`, it must be approved to move this token
         * by either {approve} or {setApprovalForAll}.
         * - If `to` refers to a smart contract, it must implement
         * {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
         *
         * Emits a {Transfer} event.
         */
        function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data)
            public
            payable
            virtual
            override
        {
            transferFrom(from, to, tokenId);
            if (to.code.length != 0) {
                if (!_checkContractOnERC721Received(from, to, tokenId, _data)) {
                    _revert(TransferToNonERC721ReceiverImplementer.selector);
                }
            }
        }
        /**
         * @dev Hook that is called before a set of serially-ordered token IDs
         * are about to be transferred. This includes minting.
         * And also called before burning one token.
         *
         * `startTokenId` - the first token ID to be transferred.
         * `quantity` - the amount to be transferred.
         *
         * Calling conditions:
         *
         * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
         * transferred to `to`.
         * - When `from` is zero, `tokenId` will be minted for `to`.
         * - When `to` is zero, `tokenId` will be burned by `from`.
         * - `from` and `to` are never both zero.
         */
        function _beforeTokenTransfers(address from, address to, uint256 startTokenId, uint256 quantity) internal virtual {}
        /**
         * @dev Hook that is called after a set of serially-ordered token IDs
         * have been transferred. This includes minting.
         * And also called after one token has been burned.
         *
         * `startTokenId` - the first token ID to be transferred.
         * `quantity` - the amount to be transferred.
         *
         * Calling conditions:
         *
         * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
         * transferred to `to`.
         * - When `from` is zero, `tokenId` has been minted for `to`.
         * - When `to` is zero, `tokenId` has been burned by `from`.
         * - `from` and `to` are never both zero.
         */
        function _afterTokenTransfers(address from, address to, uint256 startTokenId, uint256 quantity) internal virtual {}
        /**
         * @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target contract.
         *
         * `from` - Previous owner of the given token ID.
         * `to` - Target address that will receive the token.
         * `tokenId` - Token ID to be transferred.
         * `_data` - Optional data to send along with the call.
         *
         * Returns whether the call correctly returned the expected magic value.
         */
        function _checkContractOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
            private
            returns (bool)
        {
            try ERC721A__IERC721Receiver(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data) returns (
                bytes4 retval
            ) {
                return retval == ERC721A__IERC721Receiver(to).onERC721Received.selector;
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    _revert(TransferToNonERC721ReceiverImplementer.selector);
                }
                assembly {
                    revert(add(32, reason), mload(reason))
                }
            }
        }
        // =============================================================
        //                        MINT OPERATIONS
        // =============================================================
        /**
         * @dev Mints `quantity` tokens and transfers them to `to`.
         *
         * Requirements:
         *
         * - `to` cannot be the zero address.
         * - `quantity` must be greater than 0.
         *
         * Emits a {Transfer} event for each mint.
         */
        function _mint(address to, uint256 quantity) internal virtual {
            uint256 startTokenId = _currentIndex;
            if (quantity == 0) _revert(MintZeroQuantity.selector);
            _beforeTokenTransfers(address(0), to, startTokenId, quantity);
            // Overflows are incredibly unrealistic.
            // `balance` and `numberMinted` have a maximum limit of 2**64.
            // `tokenId` has a maximum limit of 2**256.
            unchecked {
                // Updates:
                // - `address` to the owner.
                // - `startTimestamp` to the timestamp of minting.
                // - `burned` to `false`.
                // - `nextInitialized` to `quantity == 1`.
                _packedOwnerships[startTokenId] =
                    _packOwnershipData(to, _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0));
                // Updates:
                // - `balance += quantity`.
                // - `numberMinted += quantity`.
                //
                // We can directly add to the `balance` and `numberMinted`.
                _packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1);
                // Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean.
                uint256 toMasked = uint256(uint160(to)) & _BITMASK_ADDRESS;
                if (toMasked == 0) _revert(MintToZeroAddress.selector);
                uint256 end = startTokenId + quantity;
                uint256 tokenId = startTokenId;
                if (end - 1 > _sequentialUpTo()) _revert(SequentialMintExceedsLimit.selector);
                do {
                    assembly {
                        // Emit the `Transfer` event.
                        log4(
                            0, // Start of data (0, since no data).
                            0, // End of data (0, since no data).
                            _TRANSFER_EVENT_SIGNATURE, // Signature.
                            0, // `address(0)`.
                            toMasked, // `to`.
                            tokenId // `tokenId`.
                        )
                    }
                    // The `!=` check ensures that large values of `quantity`
                    // that overflows uint256 will make the loop run out of gas.
                } while (++tokenId != end);
                _currentIndex = end;
            }
            _afterTokenTransfers(address(0), to, startTokenId, quantity);
        }
        /**
         * @dev Mints `quantity` tokens and transfers them to `to`.
         *
         * This function is intended for efficient minting only during contract creation.
         *
         * It emits only one {ConsecutiveTransfer} as defined in
         * [ERC2309](https://eips.ethereum.org/EIPS/eip-2309),
         * instead of a sequence of {Transfer} event(s).
         *
         * Calling this function outside of contract creation WILL make your contract
         * non-compliant with the ERC721 standard.
         * For full ERC721 compliance, substituting ERC721 {Transfer} event(s) with the ERC2309
         * {ConsecutiveTransfer} event is only permissible during contract creation.
         *
         * Requirements:
         *
         * - `to` cannot be the zero address.
         * - `quantity` must be greater than 0.
         *
         * Emits a {ConsecutiveTransfer} event.
         */
        function _mintERC2309(address to, uint256 quantity) internal virtual {
            uint256 startTokenId = _currentIndex;
            if (to == address(0)) _revert(MintToZeroAddress.selector);
            if (quantity == 0) _revert(MintZeroQuantity.selector);
            if (quantity > _MAX_MINT_ERC2309_QUANTITY_LIMIT) _revert(MintERC2309QuantityExceedsLimit.selector);
            _beforeTokenTransfers(address(0), to, startTokenId, quantity);
            // Overflows are unrealistic due to the above check for `quantity` to be below the limit.
            unchecked {
                // Updates:
                // - `balance += quantity`.
                // - `numberMinted += quantity`.
                //
                // We can directly add to the `balance` and `numberMinted`.
                _packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1);
                // Updates:
                // - `address` to the owner.
                // - `startTimestamp` to the timestamp of minting.
                // - `burned` to `false`.
                // - `nextInitialized` to `quantity == 1`.
                _packedOwnerships[startTokenId] =
                    _packOwnershipData(to, _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0));
                if (startTokenId + quantity - 1 > _sequentialUpTo()) _revert(SequentialMintExceedsLimit.selector);
                emit ConsecutiveTransfer(startTokenId, startTokenId + quantity - 1, address(0), to);
                _currentIndex = startTokenId + quantity;
            }
            _afterTokenTransfers(address(0), to, startTokenId, quantity);
        }
        /**
         * @dev Safely mints `quantity` tokens and transfers them to `to`.
         *
         * Requirements:
         *
         * - If `to` refers to a smart contract, it must implement
         * {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
         * - `quantity` must be greater than 0.
         *
         * See {_mint}.
         *
         * Emits a {Transfer} event for each mint.
         */
        function _safeMint(address to, uint256 quantity, bytes memory _data) internal virtual {
            _mint(to, quantity);
            unchecked {
                if (to.code.length != 0) {
                    uint256 end = _currentIndex;
                    uint256 index = end - quantity;
                    do {
                        if (!_checkContractOnERC721Received(address(0), to, index++, _data)) {
                            _revert(TransferToNonERC721ReceiverImplementer.selector);
                        }
                    } while (index < end);
                    // This prevents reentrancy to `_safeMint`.
                    // It does not prevent reentrancy to `_safeMintSpot`.
                    if (_currentIndex != end) revert();
                }
            }
        }
        /**
         * @dev Equivalent to `_safeMint(to, quantity, '')`.
         */
        function _safeMint(address to, uint256 quantity) internal virtual {
            _safeMint(to, quantity, "");
        }
        /**
         * @dev Mints a single token at `tokenId`.
         *
         * Note: A spot-minted `tokenId` that has been burned can be re-minted again.
         *
         * Requirements:
         *
         * - `to` cannot be the zero address.
         * - `tokenId` must be greater than `_sequentialUpTo()`.
         * - `tokenId` must not exist.
         *
         * Emits a {Transfer} event for each mint.
         */
        function _mintSpot(address to, uint256 tokenId) internal virtual {
            if (tokenId <= _sequentialUpTo()) _revert(SpotMintTokenIdTooSmall.selector);
            uint256 prevOwnershipPacked = _packedOwnerships[tokenId];
            if (_packedOwnershipExists(prevOwnershipPacked)) _revert(TokenAlreadyExists.selector);
            _beforeTokenTransfers(address(0), to, tokenId, 1);
            // Overflows are incredibly unrealistic.
            // The `numberMinted` for `to` is incremented by 1, and has a max limit of 2**64 - 1.
            // `_spotMinted` is incremented by 1, and has a max limit of 2**256 - 1.
            unchecked {
                // Updates:
                // - `address` to the owner.
                // - `startTimestamp` to the timestamp of minting.
                // - `burned` to `false`.
                // - `nextInitialized` to `true` (as `quantity == 1`).
                _packedOwnerships[tokenId] =
                    _packOwnershipData(to, _nextInitializedFlag(1) | _nextExtraData(address(0), to, prevOwnershipPacked));
                // Updates:
                // - `balance += 1`.
                // - `numberMinted += 1`.
                //
                // We can directly add to the `balance` and `numberMinted`.
                _packedAddressData[to] += (1 << _BITPOS_NUMBER_MINTED) | 1;
                // Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean.
                uint256 toMasked = uint256(uint160(to)) & _BITMASK_ADDRESS;
                if (toMasked == 0) _revert(MintToZeroAddress.selector);
                assembly {
                    // Emit the `Transfer` event.
                    log4(
                        0, // Start of data (0, since no data).
                        0, // End of data (0, since no data).
                        _TRANSFER_EVENT_SIGNATURE, // Signature.
                        0, // `address(0)`.
                        toMasked, // `to`.
                        tokenId // `tokenId`.
                    )
                }
                ++_spotMinted;
            }
            _afterTokenTransfers(address(0), to, tokenId, 1);
        }
        /**
         * @dev Safely mints a single token at `tokenId`.
         *
         * Note: A spot-minted `tokenId` that has been burned can be re-minted again.
         *
         * Requirements:
         *
         * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}.
         * - `tokenId` must be greater than `_sequentialUpTo()`.
         * - `tokenId` must not exist.
         *
         * See {_mintSpot}.
         *
         * Emits a {Transfer} event.
         */
        function _safeMintSpot(address to, uint256 tokenId, bytes memory _data) internal virtual {
            _mintSpot(to, tokenId);
            unchecked {
                if (to.code.length != 0) {
                    uint256 currentSpotMinted = _spotMinted;
                    if (!_checkContractOnERC721Received(address(0), to, tokenId, _data)) {
                        _revert(TransferToNonERC721ReceiverImplementer.selector);
                    }
                    // This prevents reentrancy to `_safeMintSpot`.
                    // It does not prevent reentrancy to `_safeMint`.
                    if (_spotMinted != currentSpotMinted) revert();
                }
            }
        }
        /**
         * @dev Equivalent to `_safeMintSpot(to, tokenId, '')`.
         */
        function _safeMintSpot(address to, uint256 tokenId) internal virtual {
            _safeMintSpot(to, tokenId, "");
        }
        // =============================================================
        //                       APPROVAL OPERATIONS
        // =============================================================
        /**
         * @dev Equivalent to `_approve(to, tokenId, false)`.
         */
        function _approve(address to, uint256 tokenId) internal virtual {
            _approve(to, tokenId, false);
        }
        /**
         * @dev Gives permission to `to` to transfer `tokenId` token to another account.
         * The approval is cleared when the token is transferred.
         *
         * Only a single account can be approved at a time, so approving the
         * zero address clears previous approvals.
         *
         * Requirements:
         *
         * - `tokenId` must exist.
         *
         * Emits an {Approval} event.
         */
        function _approve(address to, uint256 tokenId, bool approvalCheck) internal virtual {
            address owner = ownerOf(tokenId);
            if (approvalCheck && _msgSenderERC721A() != owner) {
                if (!isApprovedForAll(owner, _msgSenderERC721A())) {
                    _revert(ApprovalCallerNotOwnerNorApproved.selector);
                }
            }
            _tokenApprovals[tokenId].value = to;
            emit Approval(owner, to, tokenId);
        }
        // =============================================================
        //                        BURN OPERATIONS
        // =============================================================
        /**
         * @dev Equivalent to `_burn(tokenId, false)`.
         */
        function _burn(uint256 tokenId) internal virtual {
            _burn(tokenId, false);
        }
        /**
         * @dev Destroys `tokenId`.
         * The approval is cleared when the token is burned.
         *
         * Requirements:
         *
         * - `tokenId` must exist.
         *
         * Emits a {Transfer} event.
         */
        function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
            uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
            address from = address(uint160(prevOwnershipPacked));
            (uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
            if (approvalCheck) {
                // The nested ifs save around 20+ gas over a compound boolean condition.
                if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A())) {
                    if (!isApprovedForAll(from, _msgSenderERC721A())) _revert(TransferCallerNotOwnerNorApproved.selector);
                }
            }
            _beforeTokenTransfers(from, address(0), tokenId, 1);
            // Clear approvals from the previous owner.
            assembly {
                if approvedAddress {
                    // This is equivalent to `delete _tokenApprovals[tokenId]`.
                    sstore(approvedAddressSlot, 0)
                }
            }
            // Underflow of the sender's balance is impossible because we check for
            // ownership above and the recipient's balance can't realistically overflow.
            // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.
            unchecked {
                // Updates:
                // - `balance -= 1`.
                // - `numberBurned += 1`.
                //
                // We can directly decrement the balance, and increment the number burned.
                // This is equivalent to `packed -= 1; packed += 1 << _BITPOS_NUMBER_BURNED;`.
                _packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1;
                // Updates:
                // - `address` to the last owner.
                // - `startTimestamp` to the timestamp of burning.
                // - `burned` to `true`.
                // - `nextInitialized` to `true`.
                _packedOwnerships[tokenId] = _packOwnershipData(
                    from,
                    (_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
                );
                // If the next slot may not have been initialized (i.e. `nextInitialized == false`) .
                if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
                    uint256 nextTokenId = tokenId + 1;
                    // If the next slot's address is zero and not burned (i.e. packed value is zero).
                    if (_packedOwnerships[nextTokenId] == 0) {
                        // If the next slot is within bounds.
                        if (nextTokenId != _currentIndex) {
                            // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
                            _packedOwnerships[nextTokenId] = prevOwnershipPacked;
                        }
                    }
                }
            }
            emit Transfer(from, address(0), tokenId);
            _afterTokenTransfers(from, address(0), tokenId, 1);
            // Overflow not possible, as `_burnCounter` cannot be exceed `_currentIndex + _spotMinted` times.
            unchecked {
                _burnCounter++;
            }
        }
        // =============================================================
        //                     EXTRA DATA OPERATIONS
        // =============================================================
        /**
         * @dev Directly sets the extra data for the ownership data `index`.
         */
        function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual {
            uint256 packed = _packedOwnerships[index];
            if (packed == 0) _revert(OwnershipNotInitializedForExtraData.selector);
            uint256 extraDataCasted;
            // Cast `extraData` with assembly to avoid redundant masking.
            assembly {
                extraDataCasted := extraData
            }
            packed = (packed & _BITMASK_EXTRA_DATA_COMPLEMENT) | (extraDataCasted << _BITPOS_EXTRA_DATA);
            _packedOwnerships[index] = packed;
        }
        /**
         * @dev Called during each token transfer to set the 24bit `extraData` field.
         * Intended to be overridden by the cosumer contract.
         *
         * `previousExtraData` - the value of `extraData` before transfer.
         *
         * Calling conditions:
         *
         * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
         * transferred to `to`.
         * - When `from` is zero, `tokenId` will be minted for `to`.
         * - When `to` is zero, `tokenId` will be burned by `from`.
         * - `from` and `to` are never both zero.
         */
        function _extraData(address from, address to, uint24 previousExtraData) internal view virtual returns (uint24) {}
        /**
         * @dev Returns the next extra data for the packed ownership data.
         * The returned result is shifted into position.
         */
        function _nextExtraData(address from, address to, uint256 prevOwnershipPacked) private view returns (uint256) {
            uint24 extraData = uint24(prevOwnershipPacked >> _BITPOS_EXTRA_DATA);
            return uint256(_extraData(from, to, extraData)) << _BITPOS_EXTRA_DATA;
        }
        // =============================================================
        //                       OTHER OPERATIONS
        // =============================================================
        /**
         * @dev Returns the message sender (defaults to `msg.sender`).
         *
         * If you are writing GSN compatible contracts, you need to override this function.
         */
        function _msgSenderERC721A() internal view virtual returns (address) {
            return msg.sender;
        }
        /**
         * @dev Converts a uint256 to its ASCII string decimal representation.
         */
        function _toString(uint256 value) internal pure virtual returns (string memory str) {
            assembly {
                // The maximum value of a uint256 contains 78 digits (1 byte per digit), but
                // we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
                // We will need 1 word for the trailing zeros padding, 1 word for the length,
                // and 3 words for a maximum of 78 digits. Total: 5 * 0x20 = 0xa0.
                let m := add(mload(0x40), 0xa0)
                // Update the free memory pointer to allocate.
                mstore(0x40, m)
                // Assign the `str` to the end.
                str := sub(m, 0x20)
                // Zeroize the slot after the string.
                mstore(str, 0)
                // Cache the end of the memory to calculate the length later.
                let end := str
                // We write the string from rightmost digit to leftmost digit.
                // The following is essentially a do-while loop that also handles the zero case.
                // prettier-ignore
                for { let temp := value } 1 {} {
                    str := sub(str, 1)
                    // Write the character to the pointer.
                    // The ASCII index of the '0' character is 48.
                    mstore8(str, add(48, mod(temp, 10)))
                    // Keep dividing `temp` until zero.
                    temp := div(temp, 10)
                    // prettier-ignore
                    if iszero(temp) { break }
                }
                let length := sub(end, str)
                // Move the pointer 32 bytes leftwards to make room for the length.
                str := sub(str, 0x20)
                // Store the length.
                mstore(str, length)
            }
        }
        /**
         * @dev For more efficient reverts.
         */
        function _revert(bytes4 errorSelector) internal pure {
            assembly {
                mstore(0x00, errorSelector)
                revert(0x00, 0x04)
            }
        }
    }
    // SPDX-License-Identifier: MIT
    // ERC721A Contracts v4.3.0
    // Creator: Chiru Labs
    pragma solidity ^0.8.4;
    /**
     * @dev Interface of ERC721A.
     */
    interface IERC721A {
        /**
         * The caller must own the token or be an approved operator.
         */
        error ApprovalCallerNotOwnerNorApproved();
        /**
         * The token does not exist.
         */
        error ApprovalQueryForNonexistentToken();
        /**
         * Cannot query the balance for the zero address.
         */
        error BalanceQueryForZeroAddress();
        /**
         * Cannot mint to the zero address.
         */
        error MintToZeroAddress();
        /**
         * The quantity of tokens minted must be more than zero.
         */
        error MintZeroQuantity();
        /**
         * The token does not exist.
         */
        error OwnerQueryForNonexistentToken();
        /**
         * The caller must own the token or be an approved operator.
         */
        error TransferCallerNotOwnerNorApproved();
        /**
         * The token must be owned by `from`.
         */
        error TransferFromIncorrectOwner();
        /**
         * Cannot safely transfer to a contract that does not implement the
         * ERC721Receiver interface.
         */
        error TransferToNonERC721ReceiverImplementer();
        /**
         * Cannot transfer to the zero address.
         */
        error TransferToZeroAddress();
        /**
         * The token does not exist.
         */
        error URIQueryForNonexistentToken();
        /**
         * The `quantity` minted with ERC2309 exceeds the safety limit.
         */
        error MintERC2309QuantityExceedsLimit();
        /**
         * The `extraData` cannot be set on an unintialized ownership slot.
         */
        error OwnershipNotInitializedForExtraData();
        /**
         * `_sequentialUpTo()` must be greater than `_startTokenId()`.
         */
        error SequentialUpToTooSmall();
        /**
         * The `tokenId` of a sequential mint exceeds `_sequentialUpTo()`.
         */
        error SequentialMintExceedsLimit();
        /**
         * Spot minting requires a `tokenId` greater than `_sequentialUpTo()`.
         */
        error SpotMintTokenIdTooSmall();
        /**
         * Cannot mint over a token that already exists.
         */
        error TokenAlreadyExists();
        /**
         * The feature is not compatible with spot mints.
         */
        error NotCompatibleWithSpotMints();
        // =============================================================
        //                            STRUCTS
        // =============================================================
        struct TokenOwnership {
            // The address of the owner.
            address addr;
            // Stores the start time of ownership with minimal overhead for tokenomics.
            uint64 startTimestamp;
            // Whether the token has been burned.
            bool burned;
            // Arbitrary data similar to `startTimestamp` that can be set via {_extraData}.
            uint24 extraData;
        }
        // =============================================================
        //                         TOKEN COUNTERS
        // =============================================================
        /**
         * @dev Returns the total number of tokens in existence.
         * Burned tokens will reduce the count.
         * To get the total number of tokens minted, please see {_totalMinted}.
         */
        function totalSupply() external view returns (uint256);
        // =============================================================
        //                            IERC165
        // =============================================================
        /**
         * @dev Returns true if this contract implements the interface defined by
         * `interfaceId`. See the corresponding
         * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
         * to learn more about how these ids are created.
         *
         * This function call must use less than 30000 gas.
         */
        function supportsInterface(bytes4 interfaceId) external view returns (bool);
        // =============================================================
        //                            IERC721
        // =============================================================
        /**
         * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
         */
        event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
        /**
         * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
         */
        event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
        /**
         * @dev Emitted when `owner` enables or disables
         * (`approved`) `operator` to manage all of its assets.
         */
        event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
        /**
         * @dev Returns the number of tokens in `owner`'s account.
         */
        function balanceOf(address owner) external view returns (uint256 balance);
        /**
         * @dev Returns the owner of the `tokenId` token.
         *
         * Requirements:
         *
         * - `tokenId` must exist.
         */
        function ownerOf(uint256 tokenId) external view returns (address owner);
        /**
         * @dev Safely transfers `tokenId` token from `from` to `to`,
         * checking first that contract recipients are aware of the ERC721 protocol
         * to prevent tokens from being forever locked.
         *
         * Requirements:
         *
         * - `from` cannot be the zero address.
         * - `to` cannot be the zero address.
         * - `tokenId` token must exist and be owned by `from`.
         * - If the caller is not `from`, it must be have been allowed to move
         * this token by either {approve} or {setApprovalForAll}.
         * - If `to` refers to a smart contract, it must implement
         * {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
         *
         * Emits a {Transfer} event.
         */
        function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external payable;
        /**
         * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.
         */
        function safeTransferFrom(address from, address to, uint256 tokenId) external payable;
        /**
         * @dev Transfers `tokenId` from `from` to `to`.
         *
         * WARNING: Usage of this method is discouraged, use {safeTransferFrom}
         * whenever possible.
         *
         * Requirements:
         *
         * - `from` cannot be the zero address.
         * - `to` cannot be the zero address.
         * - `tokenId` token must be owned by `from`.
         * - If the caller is not `from`, it must be approved to move this token
         * by either {approve} or {setApprovalForAll}.
         *
         * Emits a {Transfer} event.
         */
        function transferFrom(address from, address to, uint256 tokenId) external payable;
        /**
         * @dev Gives permission to `to` to transfer `tokenId` token to another account.
         * The approval is cleared when the token is transferred.
         *
         * Only a single account can be approved at a time, so approving the
         * zero address clears previous approvals.
         *
         * Requirements:
         *
         * - The caller must own the token or be an approved operator.
         * - `tokenId` must exist.
         *
         * Emits an {Approval} event.
         */
        function approve(address to, uint256 tokenId) external payable;
        /**
         * @dev Approve or remove `operator` as an operator for the caller.
         * Operators can call {transferFrom} or {safeTransferFrom}
         * for any token owned by the caller.
         *
         * Requirements:
         *
         * - The `operator` cannot be the caller.
         *
         * Emits an {ApprovalForAll} event.
         */
        function setApprovalForAll(address operator, bool _approved) external;
        /**
         * @dev Returns the account approved for `tokenId` token.
         *
         * Requirements:
         *
         * - `tokenId` must exist.
         */
        function getApproved(uint256 tokenId) external view returns (address operator);
        /**
         * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
         *
         * See {setApprovalForAll}.
         */
        function isApprovedForAll(address owner, address operator) external view returns (bool);
        // =============================================================
        //                        IERC721Metadata
        // =============================================================
        /**
         * @dev Returns the token collection name.
         */
        function name() external view returns (string memory);
        /**
         * @dev Returns the token collection symbol.
         */
        function symbol() external view returns (string memory);
        /**
         * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
         */
        function tokenURI(uint256 tokenId) external view returns (string memory);
        // =============================================================
        //                           IERC2309
        // =============================================================
        /**
         * @dev Emitted when tokens in `fromTokenId` to `toTokenId`
         * (inclusive) is transferred from `from` to `to`, as defined in the
         * [ERC2309](https://eips.ethereum.org/EIPS/eip-2309) standard.
         *
         * See {_mintERC2309} for more details.
         */
        event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed from, address indexed to);
    }
    

    File 2 of 4: TITANX
    // SPDX-License-Identifier: UNLICENSED
    pragma solidity ^0.8.10;
    import "./openzeppelin/security/ReentrancyGuard.sol";
    import "./openzeppelin/token/ERC20/ERC20.sol";
    import "./openzeppelin/interfaces/IERC165.sol";
    import "../interfaces/ITitanOnBurn.sol";
    import "../interfaces/ITITANX.sol";
    import "../libs/calcFunctions.sol";
    import "./GlobalInfo.sol";
    import "./MintInfo.sol";
    import "./StakeInfo.sol";
    import "./BurnInfo.sol";
    import "./OwnerInfo.sol";
    //custom errors
    error TitanX_InvalidAmount();
    error TitanX_InsufficientBalance();
    error TitanX_NotSupportedContract();
    error TitanX_InsufficientProtocolFees();
    error TitanX_FailedToSendAmount();
    error TitanX_NotAllowed();
    error TitanX_NoCycleRewardToClaim();
    error TitanX_NoSharesExist();
    error TitanX_EmptyUndistributeFees();
    error TitanX_InvalidBurnRewardPercent();
    error TitanX_InvalidBatchCount();
    error TitanX_InvalidMintLadderInterval();
    error TitanX_InvalidMintLadderRange();
    error TitanX_MaxedWalletMints();
    error TitanX_LPTokensHasMinted();
    error TitanX_InvalidAddress();
    error TitanX_InsufficientBurnAllowance();
    /** @title Titan X */
    contract TITANX is ERC20, ReentrancyGuard, GlobalInfo, MintInfo, StakeInfo, BurnInfo, OwnerInfo {
        /** Storage Variables*/
        /** @dev stores genesis wallet address */
        address private s_genesisAddress;
        /** @dev stores buy and burn contract address */
        address private s_buyAndBurnAddress;
        /** @dev tracks collected protocol fees until it is distributed */
        uint88 private s_undistributedEth;
        /** @dev tracks burn reward from distributeETH() until payout is triggered */
        uint88 private s_cycleBurnReward;
        /** @dev tracks if initial LP tokens has minted or not */
        InitialLPMinted private s_initialLPMinted;
        /** @dev trigger to turn on burn pool reward */
        BurnPoolEnabled private s_burnPoolEnabled;
        /** @dev tracks user + project burn mints allowance */
        mapping(address => mapping(address => uint256)) private s_allowanceBurnMints;
        /** @dev tracks user + project burn stakes allowance */
        mapping(address => mapping(address => uint256)) private s_allowanceBurnStakes;
        event ProtocolFeeRecevied(address indexed user, uint256 indexed day, uint256 indexed amount);
        event ETHDistributed(address indexed caller, uint256 indexed amount);
        event CyclePayoutTriggered(
            address indexed caller,
            uint256 indexed cycleNo,
            uint256 indexed reward,
            uint256 burnReward
        );
        event RewardClaimed(address indexed user, uint256 indexed reward);
        event ApproveBurnStakes(address indexed user, address indexed project, uint256 indexed amount);
        event ApproveBurnMints(address indexed user, address indexed project, uint256 indexed amount);
        constructor(address genesisAddress, address buyAndBurnAddress) ERC20("TITAN X", "TITANX") {
            if (genesisAddress == address(0)) revert TitanX_InvalidAddress();
            if (buyAndBurnAddress == address(0)) revert TitanX_InvalidAddress();
            s_genesisAddress = genesisAddress;
            s_buyAndBurnAddress = buyAndBurnAddress;
        }
        /**** Mint Functions *****/
        /** @notice create a new mint
         * @param mintPower 1 - 100
         * @param numOfDays mint length of 1 - 280
         */
        function startMint(
            uint256 mintPower,
            uint256 numOfDays
        ) external payable nonReentrant dailyUpdate {
            if (getUserLatestMintId(_msgSender()) + 1 > MAX_MINT_PER_WALLET)
                revert TitanX_MaxedWalletMints();
            uint256 gMintPower = getGlobalMintPower() + mintPower;
            uint256 currentTRank = getGlobalTRank() + 1;
            uint256 gMinting = getTotalMinting() +
                _startMint(
                    _msgSender(),
                    mintPower,
                    numOfDays,
                    getCurrentMintableTitan(),
                    getCurrentMintPowerBonus(),
                    getCurrentEAABonus(),
                    getUserBurnAmplifierBonus(_msgSender()),
                    gMintPower,
                    currentTRank,
                    getBatchMintCost(mintPower, 1, getCurrentMintCost())
                );
            _updateMintStats(currentTRank, gMintPower, gMinting);
            _protocolFees(mintPower, 1);
        }
        /** @notice create new mints in batch of up to 100 mints
         * @param mintPower 1 - 100
         * @param numOfDays mint length of 1 - 280
         * @param count 1 - 100
         */
        function batchMint(
            uint256 mintPower,
            uint256 numOfDays,
            uint256 count
        ) external payable nonReentrant dailyUpdate {
            if (count == 0 || count > MAX_BATCH_MINT_COUNT) revert TitanX_InvalidBatchCount();
            if (getUserLatestMintId(_msgSender()) + count > MAX_MINT_PER_WALLET)
                revert TitanX_MaxedWalletMints();
            _startBatchMint(
                _msgSender(),
                mintPower,
                numOfDays,
                getCurrentMintableTitan(),
                getCurrentMintPowerBonus(),
                getCurrentEAABonus(),
                getUserBurnAmplifierBonus(_msgSender()),
                count,
                getBatchMintCost(mintPower, 1, getCurrentMintCost()) //only need 1 mint cost for all mints
            );
            _protocolFees(mintPower, count);
        }
        /** @notice create new mints in ladder up to 100 mints
         * @param mintPower 1 - 100
         * @param minDay minimum mint length
         * @param maxDay maximum mint lenght
         * @param dayInterval day increase from previous mint length
         * @param countPerInterval how many mints per mint length
         */
        function batchMintLadder(
            uint256 mintPower,
            uint256 minDay,
            uint256 maxDay,
            uint256 dayInterval,
            uint256 countPerInterval
        ) external payable nonReentrant dailyUpdate {
            if (dayInterval == 0) revert TitanX_InvalidMintLadderInterval();
            if (maxDay < minDay || minDay == 0 || maxDay > MAX_MINT_LENGTH)
                revert TitanX_InvalidMintLadderRange();
            uint256 count = getBatchMintLadderCount(minDay, maxDay, dayInterval, countPerInterval);
            if (count == 0 || count > MAX_BATCH_MINT_COUNT) revert TitanX_InvalidBatchCount();
            if (getUserLatestMintId(_msgSender()) + count > MAX_MINT_PER_WALLET)
                revert TitanX_MaxedWalletMints();
            uint256 mintCost = getBatchMintCost(mintPower, 1, getCurrentMintCost()); //only need 1 mint cost for all mints
            _startbatchMintLadder(
                _msgSender(),
                mintPower,
                minDay,
                maxDay,
                dayInterval,
                countPerInterval,
                getCurrentMintableTitan(),
                getCurrentMintPowerBonus(),
                getCurrentEAABonus(),
                getUserBurnAmplifierBonus(_msgSender()),
                mintCost
            );
            _protocolFees(mintPower, count);
        }
        /** @notice claim a matured mint
         * @param id mint id
         */
        function claimMint(uint256 id) external dailyUpdate nonReentrant {
            _mintReward(_claimMint(_msgSender(), id, MintAction.CLAIM));
        }
        /** @notice batch claim matured mint of up to 100 claims per run
         */
        function batchClaimMint() external dailyUpdate nonReentrant {
            _mintReward(_batchClaimMint(_msgSender()));
        }
        /**** Stake Functions *****/
        /** @notice start a new stake
         * @param amount titan amount
         * @param numOfDays stake length
         */
        function startStake(uint256 amount, uint256 numOfDays) external dailyUpdate nonReentrant {
            if (balanceOf(_msgSender()) < amount) revert TitanX_InsufficientBalance();
            _burn(_msgSender(), amount);
            _initFirstSharesCycleIndex(
                _msgSender(),
                _startStake(
                    _msgSender(),
                    amount,
                    numOfDays,
                    getCurrentShareRate(),
                    getCurrentContractDay(),
                    getGlobalPayoutTriggered()
                )
            );
        }
        /** @notice end a stake
         * @param id stake id
         */
        function endStake(uint256 id) external dailyUpdate nonReentrant {
            _mint(
                _msgSender(),
                _endStake(
                    _msgSender(),
                    id,
                    getCurrentContractDay(),
                    StakeAction.END,
                    StakeAction.END_OWN,
                    getGlobalPayoutTriggered()
                )
            );
        }
        /** @notice end a stake for others
         * @param user wallet address
         * @param id stake id
         */
        function endStakeForOthers(address user, uint256 id) external dailyUpdate nonReentrant {
            _mint(
                user,
                _endStake(
                    user,
                    id,
                    getCurrentContractDay(),
                    StakeAction.END,
                    StakeAction.END_OTHER,
                    getGlobalPayoutTriggered()
                )
            );
        }
        /** @notice distribute the collected protocol fees into different pools/payouts
         * automatically send the incentive fee to caller, buyAndBurnFunds to BuyAndBurn contract, and genesis wallet
         */
        function distributeETH() external dailyUpdate nonReentrant {
            (uint256 incentiveFee, uint256 buyAndBurnFunds, uint256 genesisWallet) = _distributeETH();
            _sendFunds(incentiveFee, buyAndBurnFunds, genesisWallet);
        }
        /** @notice trigger cylce payouts for day 8, 28, 90, 369, 888 including the burn reward cycle 28
         * As long as the cycle has met its maturiy day (eg. Cycle8 is day 8), payout can be triggered in any day onwards
         */
        function triggerPayouts() external dailyUpdate nonReentrant {
            uint256 globalActiveShares = getGlobalShares() - getGlobalExpiredShares();
            if (globalActiveShares < 1) revert TitanX_NoSharesExist();
            uint256 incentiveFee;
            uint256 buyAndBurnFunds;
            uint256 genesisWallet;
            if (s_undistributedEth != 0)
                (incentiveFee, buyAndBurnFunds, genesisWallet) = _distributeETH();
            uint256 currentContractDay = getCurrentContractDay();
            PayoutTriggered isTriggered = PayoutTriggered.NO;
            _triggerCyclePayout(DAY8, globalActiveShares, currentContractDay) == PayoutTriggered.YES &&
                isTriggered == PayoutTriggered.NO
                ? isTriggered = PayoutTriggered.YES
                : isTriggered;
            _triggerCyclePayout(DAY28, globalActiveShares, currentContractDay) == PayoutTriggered.YES &&
                isTriggered == PayoutTriggered.NO
                ? isTriggered = PayoutTriggered.YES
                : isTriggered;
            _triggerCyclePayout(DAY90, globalActiveShares, currentContractDay) == PayoutTriggered.YES &&
                isTriggered == PayoutTriggered.NO
                ? isTriggered = PayoutTriggered.YES
                : isTriggered;
            _triggerCyclePayout(DAY369, globalActiveShares, currentContractDay) ==
                PayoutTriggered.YES &&
                isTriggered == PayoutTriggered.NO
                ? isTriggered = PayoutTriggered.YES
                : isTriggered;
            _triggerCyclePayout(DAY888, globalActiveShares, currentContractDay) ==
                PayoutTriggered.YES &&
                isTriggered == PayoutTriggered.NO
                ? isTriggered = PayoutTriggered.YES
                : isTriggered;
            if (isTriggered == PayoutTriggered.YES) {
                if (getGlobalPayoutTriggered() == PayoutTriggered.NO) _setGlobalPayoutTriggered();
            }
            if (incentiveFee != 0) _sendFunds(incentiveFee, buyAndBurnFunds, genesisWallet);
        }
        /** @notice claim all user available ETH payouts in one call */
        function claimUserAvailableETHPayouts() external dailyUpdate nonReentrant {
            uint256 reward = _claimCyclePayout(DAY8, PayoutClaim.SHARES);
            reward += _claimCyclePayout(DAY28, PayoutClaim.SHARES);
            reward += _claimCyclePayout(DAY90, PayoutClaim.SHARES);
            reward += _claimCyclePayout(DAY369, PayoutClaim.SHARES);
            reward += _claimCyclePayout(DAY888, PayoutClaim.SHARES);
            if (reward == 0) revert TitanX_NoCycleRewardToClaim();
            _sendViaCall(payable(_msgSender()), reward);
            emit RewardClaimed(_msgSender(), reward);
        }
        /** @notice claim all user available burn rewards in one call */
        function claimUserAvailableETHBurnPool() external dailyUpdate nonReentrant {
            uint256 reward = _claimCyclePayout(DAY28, PayoutClaim.BURN);
            if (reward == 0) revert TitanX_NoCycleRewardToClaim();
            _sendViaCall(payable(_msgSender()), reward);
            emit RewardClaimed(_msgSender(), reward);
        }
        /** @notice Set BuyAndBurn Contract Address - able to change to new contract that supports UniswapV4+
         * Only owner can call this function
         * @param contractAddress BuyAndBurn contract address
         */
        function setBuyAndBurnContractAddress(address contractAddress) external onlyOwner {
            if (contractAddress == address(0)) revert TitanX_InvalidAddress();
            s_buyAndBurnAddress = contractAddress;
        }
        /** @notice enable burn pool to start accumulate reward. Only owner can call this function. */
        function enableBurnPoolReward() external onlyOwner {
            s_burnPoolEnabled = BurnPoolEnabled.TRUE;
        }
        /** @notice Set to new genesis wallet. Only genesis wallet can call this function
         * @param newAddress new genesis wallet address
         */
        function setNewGenesisAddress(address newAddress) external {
            if (_msgSender() != s_genesisAddress) revert TitanX_NotAllowed();
            if (newAddress == address(0)) revert TitanX_InvalidAddress();
            s_genesisAddress = newAddress;
        }
        /** @notice mint initial LP tokens. Only BuyAndBurn contract set by genesis wallet can call this function
         */
        function mintLPTokens() external {
            if (_msgSender() != s_buyAndBurnAddress) revert TitanX_NotAllowed();
            if (s_initialLPMinted == InitialLPMinted.YES) revert TitanX_LPTokensHasMinted();
            s_initialLPMinted = InitialLPMinted.YES;
            _mint(s_buyAndBurnAddress, INITAL_LP_TOKENS);
        }
        /** @notice burn all BuyAndBurn contract Titan */
        function burnLPTokens() external dailyUpdate {
            _burn(s_buyAndBurnAddress, balanceOf(s_buyAndBurnAddress));
        }
        //private functions
        /** @dev mint reward to user and 1% to genesis wallet
         * @param reward titan amount
         */
        function _mintReward(uint256 reward) private {
            _mint(_msgSender(), reward);
            _mint(s_genesisAddress, (reward * 800) / PERCENT_BPS);
        }
        /** @dev send ETH to respective parties
         * @param incentiveFee fees for caller to run distributeETH()
         * @param buyAndBurnFunds funds for buy and burn
         * @param genesisWalletFunds funds for genesis wallet
         */
        function _sendFunds(
            uint256 incentiveFee,
            uint256 buyAndBurnFunds,
            uint256 genesisWalletFunds
        ) private {
            _sendViaCall(payable(_msgSender()), incentiveFee);
            _sendViaCall(payable(s_genesisAddress), genesisWalletFunds);
            _sendViaCall(payable(s_buyAndBurnAddress), buyAndBurnFunds);
        }
        /** @dev calculation to distribute collected protocol fees into different pools/parties */
        function _distributeETH()
            private
            returns (uint256 incentiveFee, uint256 buyAndBurnFunds, uint256 genesisWallet)
        {
            uint256 accumulatedFees = s_undistributedEth;
            if (accumulatedFees == 0) revert TitanX_EmptyUndistributeFees();
            s_undistributedEth = 0;
            emit ETHDistributed(_msgSender(), accumulatedFees);
            incentiveFee = (accumulatedFees * INCENTIVE_FEE_PERCENT) / INCENTIVE_FEE_PERCENT_BASE; //0.01%
            accumulatedFees -= incentiveFee;
            buyAndBurnFunds = (accumulatedFees * PERCENT_TO_BUY_AND_BURN) / PERCENT_BPS;
            uint256 cylceBurnReward = (accumulatedFees * PERCENT_TO_BURN_PAYOUTS) / PERCENT_BPS;
            genesisWallet = (accumulatedFees * PERCENT_TO_GENESIS) / PERCENT_BPS;
            uint256 cycleRewardPool = accumulatedFees -
                buyAndBurnFunds -
                cylceBurnReward -
                genesisWallet;
            if (s_burnPoolEnabled == BurnPoolEnabled.TRUE) s_cycleBurnReward += uint88(cylceBurnReward);
            else buyAndBurnFunds += cylceBurnReward;
            //cycle payout
            if (cycleRewardPool != 0) {
                uint256 cycle8Reward = (cycleRewardPool * CYCLE_8_PERCENT) / PERCENT_BPS;
                uint256 cycle28Reward = (cycleRewardPool * CYCLE_28_PERCENT) / PERCENT_BPS;
                uint256 cycle90Reward = (cycleRewardPool * CYCLE_90_PERCENT) / PERCENT_BPS;
                uint256 cycle369Reward = (cycleRewardPool * CYCLE_369_PERCENT) / PERCENT_BPS;
                _setCyclePayoutPool(DAY8, cycle8Reward);
                _setCyclePayoutPool(DAY28, cycle28Reward);
                _setCyclePayoutPool(DAY90, cycle90Reward);
                _setCyclePayoutPool(DAY369, cycle369Reward);
                _setCyclePayoutPool(
                    DAY888,
                    cycleRewardPool - cycle8Reward - cycle28Reward - cycle90Reward - cycle369Reward
                );
            }
        }
        /** @dev calcualte required protocol fees, and return the balance (if any)
         * @param mintPower mint power 1-100
         * @param count how many mints
         */
        function _protocolFees(uint256 mintPower, uint256 count) private {
            uint256 protocolFee;
            protocolFee = getBatchMintCost(mintPower, count, getCurrentMintCost());
            if (msg.value < protocolFee) revert TitanX_InsufficientProtocolFees();
            uint256 feeBalance;
            s_undistributedEth += uint88(protocolFee);
            feeBalance = msg.value - protocolFee;
            if (feeBalance != 0) {
                _sendViaCall(payable(_msgSender()), feeBalance);
            }
            emit ProtocolFeeRecevied(_msgSender(), getCurrentContractDay(), protocolFee);
        }
        /** @dev calculate payouts for each cycle day tracked by cycle index
         * @param cycleNo cylce day 8, 28, 90, 369, 888
         * @param globalActiveShares global active shares
         * @param currentContractDay current contract day
         * @return triggered is payout triggered succesfully
         */
        function _triggerCyclePayout(
            uint256 cycleNo,
            uint256 globalActiveShares,
            uint256 currentContractDay
        ) private returns (PayoutTriggered triggered) {
            //check against cylce payout maturity day
            if (currentContractDay < getNextCyclePayoutDay(cycleNo)) return PayoutTriggered.NO;
            //update the next cycle payout day regardless of payout triggered succesfully or not
            _setNextCyclePayoutDay(cycleNo);
            uint256 reward = getCyclePayoutPool(cycleNo);
            if (reward == 0) return PayoutTriggered.NO;
            //calculate cycle reward per share and get new cycle Index
            uint256 cycleIndex = _calculateCycleRewardPerShare(cycleNo, reward, globalActiveShares);
            //calculate burn reward if cycle is 28
            uint256 totalCycleBurn = getCycleBurnTotal(cycleIndex);
            uint256 burnReward;
            if (cycleNo == DAY28 && totalCycleBurn != 0) {
                burnReward = s_cycleBurnReward;
                if (burnReward != 0) {
                    s_cycleBurnReward = 0;
                    _calculateCycleBurnRewardPerToken(cycleIndex, burnReward, totalCycleBurn);
                }
            }
            emit CyclePayoutTriggered(_msgSender(), cycleNo, reward, burnReward);
            return PayoutTriggered.YES;
        }
        /** @dev calculate user reward with specified cycle day and claim type (shares/burn) and update user's last claim cycle index
         * @param cycleNo cycle day 8, 28, 90, 369, 888
         * @param payoutClaim claim type - (Shares=0/Burn=1)
         */
        function _claimCyclePayout(uint256 cycleNo, PayoutClaim payoutClaim) private returns (uint256) {
            (
                uint256 reward,
                uint256 userClaimCycleIndex,
                uint256 userClaimSharesIndex,
                uint256 userClaimBurnCycleIndex
            ) = _calculateUserCycleReward(_msgSender(), cycleNo, payoutClaim);
            if (payoutClaim == PayoutClaim.SHARES)
                _updateUserClaimIndexes(
                    _msgSender(),
                    cycleNo,
                    userClaimCycleIndex,
                    userClaimSharesIndex
                );
            if (payoutClaim == PayoutClaim.BURN) {
                _updateUserBurnCycleClaimIndex(_msgSender(), cycleNo, userClaimBurnCycleIndex);
            }
            return reward;
        }
        /** @dev burn liquid Titan through other project.
         * called by other contracts for proof of burn 2.0 with up to 8% for both builder fee and user rebate
         * @param user user address
         * @param amount liquid titan amount
         * @param userRebatePercentage percentage for user rebate in liquid titan (0 - 8)
         * @param rewardPaybackPercentage percentage for builder fee in liquid titan (0 - 8)
         * @param rewardPaybackAddress builder can opt to receive fee in another address
         */
        function _burnLiquidTitan(
            address user,
            uint256 amount,
            uint256 userRebatePercentage,
            uint256 rewardPaybackPercentage,
            address rewardPaybackAddress
        ) private {
            if (amount == 0) revert TitanX_InvalidAmount();
            if (balanceOf(user) < amount) revert TitanX_InsufficientBalance();
            _spendAllowance(user, _msgSender(), amount);
            _burnbefore(userRebatePercentage, rewardPaybackPercentage);
            _burn(user, amount);
            _burnAfter(
                user,
                amount,
                userRebatePercentage,
                rewardPaybackPercentage,
                rewardPaybackAddress,
                BurnSource.LIQUID
            );
        }
        /** @dev burn stake through other project.
         * called by other contracts for proof of burn 2.0 with up to 8% for both builder fee and user rebate
         * @param user user address
         * @param id stake id
         * @param userRebatePercentage percentage for user rebate in liquid titan (0 - 8)
         * @param rewardPaybackPercentage percentage for builder fee in liquid titan (0 - 8)
         * @param rewardPaybackAddress builder can opt to receive fee in another address
         */
        function _burnStake(
            address user,
            uint256 id,
            uint256 userRebatePercentage,
            uint256 rewardPaybackPercentage,
            address rewardPaybackAddress
        ) private {
            _spendBurnStakeAllowance(user);
            _burnbefore(userRebatePercentage, rewardPaybackPercentage);
            _burnAfter(
                user,
                _endStake(
                    user,
                    id,
                    getCurrentContractDay(),
                    StakeAction.BURN,
                    StakeAction.END_OWN,
                    getGlobalPayoutTriggered()
                ),
                userRebatePercentage,
                rewardPaybackPercentage,
                rewardPaybackAddress,
                BurnSource.STAKE
            );
        }
        /** @dev burn mint through other project.
         * called by other contracts for proof of burn 2.0
         * burn mint has no builder reward and no user rebate
         * @param user user address
         * @param id mint id
         */
        function _burnMint(address user, uint256 id) private {
            _spendBurnMintAllowance(user);
            _burnbefore(0, 0);
            uint256 amount = _claimMint(user, id, MintAction.BURN);
            _mint(s_genesisAddress, (amount * 800) / PERCENT_BPS);
            _burnAfter(user, amount, 0, 0, _msgSender(), BurnSource.MINT);
        }
        /** @dev perform checks before burning starts.
         * check reward percentage and check if called by supported contract
         * @param userRebatePercentage percentage for user rebate
         * @param rewardPaybackPercentage percentage for builder fee
         */
        function _burnbefore(
            uint256 userRebatePercentage,
            uint256 rewardPaybackPercentage
        ) private view {
            if (rewardPaybackPercentage + userRebatePercentage > MAX_BURN_REWARD_PERCENT)
                revert TitanX_InvalidBurnRewardPercent();
            //Only supported contracts is allowed to call this function
            if (
                !IERC165(_msgSender()).supportsInterface(IERC165.supportsInterface.selector) ||
                !IERC165(_msgSender()).supportsInterface(type(ITitanOnBurn).interfaceId)
            ) revert TitanX_NotSupportedContract();
        }
        /** @dev update burn stats and mint reward to builder or user if applicable
         * @param user user address
         * @param amount titan amount burned
         * @param userRebatePercentage percentage for user rebate in liquid titan (0 - 8)
         * @param rewardPaybackPercentage percentage for builder fee in liquid titan (0 - 8)
         * @param rewardPaybackAddress builder can opt to receive fee in another address
         * @param source liquid/mint/stake
         */
        function _burnAfter(
            address user,
            uint256 amount,
            uint256 userRebatePercentage,
            uint256 rewardPaybackPercentage,
            address rewardPaybackAddress,
            BurnSource source
        ) private {
            uint256 index = getCurrentCycleIndex(DAY28) + 1;
            /** set to the latest cylceIndex + 1 for fresh wallet
             * same concept as _initFirstSharesCycleIndex, refer to its dev comment  */
            if (getUserBurnTotal(user) == 0) _updateUserBurnCycleClaimIndex(user, DAY28, index);
            _updateBurnAmount(user, _msgSender(), amount, index, source);
            uint256 devFee;
            uint256 userRebate;
            if (rewardPaybackPercentage != 0)
                devFee = (amount * rewardPaybackPercentage * PERCENT_BPS) / (100 * PERCENT_BPS);
            if (userRebatePercentage != 0)
                userRebate = (amount * userRebatePercentage * PERCENT_BPS) / (100 * PERCENT_BPS);
            if (devFee != 0) _mint(rewardPaybackAddress, devFee);
            if (userRebate != 0) _mint(user, userRebate);
            ITitanOnBurn(_msgSender()).onBurn(user, amount);
        }
        /** @dev Recommended method to use to send native coins.
         * @param to receiving address.
         * @param amount in wei.
         */
        function _sendViaCall(address payable to, uint256 amount) private {
            if (to == address(0)) revert TitanX_InvalidAddress();
            (bool sent, ) = to.call{value: amount}("");
            if (!sent) revert TitanX_FailedToSendAmount();
        }
        /** @dev reduce user's allowance for caller (spender/project) by 1 (burn 1 stake at a time)
         * Does not update the allowance amount in case of infinite allowance.
         * Revert if not enough allowance is available.
         * @param user user address
         */
        function _spendBurnStakeAllowance(address user) private {
            uint256 currentAllowance = allowanceBurnStakes(user, _msgSender());
            if (currentAllowance != type(uint256).max) {
                if (currentAllowance == 0) revert TitanX_InsufficientBurnAllowance();
                --s_allowanceBurnStakes[user][_msgSender()];
            }
        }
        /** @dev reduce user's allowance for caller (spender/project) by 1 (burn 1 mint at a time)
         * Does not update the allowance amount in case of infinite allowance.
         * Revert if not enough allowance is available.
         * @param user user address
         */
        function _spendBurnMintAllowance(address user) private {
            uint256 currentAllowance = allowanceBurnMints(user, _msgSender());
            if (currentAllowance != type(uint256).max) {
                if (currentAllowance == 0) revert TitanX_InsufficientBurnAllowance();
                --s_allowanceBurnMints[user][_msgSender()];
            }
        }
        //Views
        /** @dev calculate user payout reward with specified cycle day and claim type (shares/burn).
         * it loops through all the unclaimed cylce index until the latest cycle index
         * @param user user address
         * @param cycleNo cycle day 8, 28, 90, 369, 888
         * @param payoutClaim claim type (Shares=0/Burn=1)
         * @return rewards calculated reward
         * @return userClaimCycleIndex last claim cycle index
         * @return userClaimSharesIndex last claim shares index
         * @return userClaimBurnCycleIndex last claim burn cycle index
         */
        function _calculateUserCycleReward(
            address user,
            uint256 cycleNo,
            PayoutClaim payoutClaim
        )
            private
            view
            returns (
                uint256 rewards,
                uint256 userClaimCycleIndex,
                uint256 userClaimSharesIndex,
                uint256 userClaimBurnCycleIndex
            )
        {
            uint256 cycleMaxIndex = getCurrentCycleIndex(cycleNo);
            if (payoutClaim == PayoutClaim.SHARES) {
                (userClaimCycleIndex, userClaimSharesIndex) = getUserLastClaimIndex(user, cycleNo);
                uint256 sharesMaxIndex = getUserLatestShareIndex(user);
                for (uint256 i = userClaimCycleIndex; i <= cycleMaxIndex; i++) {
                    (uint256 payoutPerShare, uint256 payoutDay) = getPayoutPerShare(cycleNo, i);
                    uint256 shares;
                    //loop shares indexes to find the last updated shares before/same triggered payout day
                    for (uint256 j = userClaimSharesIndex; j <= sharesMaxIndex; j++) {
                        if (getUserActiveSharesDay(user, j) <= payoutDay)
                            shares = getUserActiveShares(user, j);
                        else break;
                        userClaimSharesIndex = j;
                    }
                    if (payoutPerShare != 0 && shares != 0) {
                        //reward has 18 decimals scaling, so here divide by 1e18
                        rewards += (shares * payoutPerShare) / SCALING_FACTOR_1e18;
                    }
                    userClaimCycleIndex = i + 1;
                }
            } else if (cycleNo == DAY28 && payoutClaim == PayoutClaim.BURN) {
                userClaimBurnCycleIndex = getUserLastBurnClaimIndex(user, cycleNo);
                for (uint256 i = userClaimBurnCycleIndex; i <= cycleMaxIndex; i++) {
                    uint256 burnPayoutPerToken = getCycleBurnPayoutPerToken(i);
                    rewards += (burnPayoutPerToken != 0)
                        ? (burnPayoutPerToken * _getUserCycleBurnTotal(user, i)) / SCALING_FACTOR_1e18
                        : 0;
                    userClaimBurnCycleIndex = i + 1;
                }
            }
        }
        /** @notice get contract ETH balance
         * @return balance eth balance
         */
        function getBalance() public view returns (uint256) {
            return address(this).balance;
        }
        /** @notice get undistributed ETH balance
         * @return amount eth amount
         */
        function getUndistributedEth() public view returns (uint256) {
            return s_undistributedEth;
        }
        /** @notice get user ETH payout for all cycles
         * @param user user address
         * @return reward total reward
         */
        function getUserETHClaimableTotal(address user) public view returns (uint256 reward) {
            uint256 _reward;
            (_reward, , , ) = _calculateUserCycleReward(user, DAY8, PayoutClaim.SHARES);
            reward += _reward;
            (_reward, , , ) = _calculateUserCycleReward(user, DAY28, PayoutClaim.SHARES);
            reward += _reward;
            (_reward, , , ) = _calculateUserCycleReward(user, DAY90, PayoutClaim.SHARES);
            reward += _reward;
            (_reward, , , ) = _calculateUserCycleReward(user, DAY369, PayoutClaim.SHARES);
            reward += _reward;
            (_reward, , , ) = _calculateUserCycleReward(user, DAY888, PayoutClaim.SHARES);
            reward += _reward;
        }
        /** @notice get user burn reward ETH payout
         * @param user user address
         * @return reward burn reward
         */
        function getUserBurnPoolETHClaimableTotal(address user) public view returns (uint256 reward) {
            (reward, , , ) = _calculateUserCycleReward(user, DAY28, PayoutClaim.BURN);
        }
        /** @notice get total penalties from mint and stake
         * @return amount total penalties
         */
        function getTotalPenalties() public view returns (uint256) {
            return getTotalMintPenalty() + getTotalStakePenalty();
        }
        /** @notice get burn pool reward
         * @return reward burn pool reward
         */
        function getCycleBurnPool() public view returns (uint256) {
            return s_cycleBurnReward;
        }
        /** @notice get user current burn cycle percentage
         * @return percentage in 18 decimals
         */
        function getCurrentUserBurnCyclePercentage() public view returns (uint256) {
            uint256 index = getCurrentCycleIndex(DAY28) + 1;
            uint256 cycleBurnTotal = getCycleBurnTotal(index);
            return
                cycleBurnTotal == 0
                    ? 0
                    : (_getUserCycleBurnTotal(_msgSender(), index) * 100 * SCALING_FACTOR_1e18) /
                        cycleBurnTotal;
        }
        /** @notice get user current cycle total titan burned
         * @param user user address
         * @return burnTotal total titan burned in curreny burn cycle
         */
        function getUserCycleBurnTotal(address user) public view returns (uint256) {
            return _getUserCycleBurnTotal(user, getCurrentCycleIndex(DAY28) + 1);
        }
        function isBurnPoolEnabled() public view returns (BurnPoolEnabled) {
            return s_burnPoolEnabled;
        }
        /** @notice returns user's burn stakes allowance of a project
         * @param user user address
         * @param spender project address
         */
        function allowanceBurnStakes(address user, address spender) public view returns (uint256) {
            return s_allowanceBurnStakes[user][spender];
        }
        /** @notice returns user's burn mints allowance of a project
         * @param user user address
         * @param spender project address
         */
        function allowanceBurnMints(address user, address spender) public view returns (uint256) {
            return s_allowanceBurnMints[user][spender];
        }
        //Public functions for devs to intergrate with Titan
        /** @notice allow anyone to sync dailyUpdate manually */
        function manualDailyUpdate() public dailyUpdate {}
        /** @notice Burn Titan tokens and creates Proof-Of-Burn record to be used by connected DeFi and fee is paid to specified address
         * @param user user address
         * @param amount titan amount
         * @param userRebatePercentage percentage for user rebate in liquid titan (0 - 8)
         * @param rewardPaybackPercentage percentage for builder fee in liquid titan (0 - 8)
         * @param rewardPaybackAddress builder can opt to receive fee in another address
         */
        function burnTokensToPayAddress(
            address user,
            uint256 amount,
            uint256 userRebatePercentage,
            uint256 rewardPaybackPercentage,
            address rewardPaybackAddress
        ) public dailyUpdate nonReentrant {
            _burnLiquidTitan(
                user,
                amount,
                userRebatePercentage,
                rewardPaybackPercentage,
                rewardPaybackAddress
            );
        }
        /** @notice Burn Titan tokens and creates Proof-Of-Burn record to be used by connected DeFi and fee is paid to specified address
         * @param user user address
         * @param amount titan amount
         * @param userRebatePercentage percentage for user rebate in liquid titan (0 - 8)
         * @param rewardPaybackPercentage percentage for builder fee in liquid titan (0 - 8)
         */
        function burnTokens(
            address user,
            uint256 amount,
            uint256 userRebatePercentage,
            uint256 rewardPaybackPercentage
        ) public dailyUpdate nonReentrant {
            _burnLiquidTitan(user, amount, userRebatePercentage, rewardPaybackPercentage, _msgSender());
        }
        /** @notice allows user to burn liquid titan directly from contract
         * @param amount titan amount
         */
        function userBurnTokens(uint256 amount) public dailyUpdate nonReentrant {
            if (amount == 0) revert TitanX_InvalidAmount();
            if (balanceOf(_msgSender()) < amount) revert TitanX_InsufficientBalance();
            _burn(_msgSender(), amount);
            _updateBurnAmount(
                _msgSender(),
                address(0),
                amount,
                getCurrentCycleIndex(DAY28) + 1,
                BurnSource.LIQUID
            );
        }
        /** @notice Burn stake and creates Proof-Of-Burn record to be used by connected DeFi and fee is paid to specified address
         * @param user user address
         * @param id stake id
         * @param userRebatePercentage percentage for user rebate in liquid titan (0 - 8)
         * @param rewardPaybackPercentage percentage for builder fee in liquid titan (0 - 8)
         * @param rewardPaybackAddress builder can opt to receive fee in another address
         */
        function burnStakeToPayAddress(
            address user,
            uint256 id,
            uint256 userRebatePercentage,
            uint256 rewardPaybackPercentage,
            address rewardPaybackAddress
        ) public dailyUpdate nonReentrant {
            _burnStake(user, id, userRebatePercentage, rewardPaybackPercentage, rewardPaybackAddress);
        }
        /** @notice Burn stake and creates Proof-Of-Burn record to be used by connected DeFi and fee is paid to project contract address
         * @param user user address
         * @param id stake id
         * @param userRebatePercentage percentage for user rebate in liquid titan (0 - 8)
         * @param rewardPaybackPercentage percentage for builder fee in liquid titan (0 - 8)
         */
        function burnStake(
            address user,
            uint256 id,
            uint256 userRebatePercentage,
            uint256 rewardPaybackPercentage
        ) public dailyUpdate nonReentrant {
            _burnStake(user, id, userRebatePercentage, rewardPaybackPercentage, _msgSender());
        }
        /** @notice allows user to burn stake directly from contract
         * @param id stake id
         */
        function userBurnStake(uint256 id) public dailyUpdate nonReentrant {
            _updateBurnAmount(
                _msgSender(),
                address(0),
                _endStake(
                    _msgSender(),
                    id,
                    getCurrentContractDay(),
                    StakeAction.BURN,
                    StakeAction.END_OWN,
                    getGlobalPayoutTriggered()
                ),
                getCurrentCycleIndex(DAY28) + 1,
                BurnSource.STAKE
            );
        }
        /** @notice Burn mint and creates Proof-Of-Burn record to be used by connected DeFi.
         * Burn mint has no project reward or user rebate
         * @param user user address
         * @param id mint id
         */
        function burnMint(address user, uint256 id) public dailyUpdate nonReentrant {
            _burnMint(user, id);
        }
        /** @notice allows user to burn mint directly from contract
         * @param id mint id
         */
        function userBurnMint(uint256 id) public dailyUpdate nonReentrant {
            _updateBurnAmount(
                _msgSender(),
                address(0),
                _claimMint(_msgSender(), id, MintAction.BURN),
                getCurrentCycleIndex(DAY28) + 1,
                BurnSource.MINT
            );
        }
        /** @notice Sets `amount` as the allowance of `spender` over the caller's (user) mints.
         * @param spender contract address
         * @param amount allowance amount
         */
        function approveBurnMints(address spender, uint256 amount) public returns (bool) {
            if (spender == address(0)) revert TitanX_InvalidAddress();
            s_allowanceBurnMints[_msgSender()][spender] = amount;
            emit ApproveBurnMints(_msgSender(), spender, amount);
            return true;
        }
        /** @notice Sets `amount` as the allowance of `spender` over the caller's (user) stakes.
         * @param spender contract address
         * @param amount allowance amount
         */
        function approveBurnStakes(address spender, uint256 amount) public returns (bool) {
            if (spender == address(0)) revert TitanX_InvalidAddress();
            s_allowanceBurnStakes[_msgSender()][spender] = amount;
            emit ApproveBurnStakes(_msgSender(), spender, amount);
            return true;
        }
    }
    // SPDX-License-Identifier: UNLICENSED
    pragma solidity ^0.8.10;
    import "./openzeppelin/utils/Context.sol";
    error TitanX_NotOnwer();
    abstract contract OwnerInfo is Context {
        address private s_owner;
        /**
         * @dev Initializes the contract setting the deployer as the initial owner.
         */
        constructor() {
            s_owner = _msgSender();
        }
        /**
         * @dev Throws if called by any account other than the owner.
         */
        modifier onlyOwner() {
            _checkOwner();
            _;
        }
        /**
         * @dev Throws if the sender is not the owner.
         */
        function _checkOwner() internal view virtual {
            if (s_owner != _msgSender()) revert TitanX_NotOnwer();
        }
        /**
         * @dev Leaves the contract without owner. It will not be possible to call
         * `onlyOwner` functions. Can only be called by the current owner.
         *
         * NOTE: Renouncing ownership will leave the contract without an owner,
         * thereby disabling any functionality that is only available to the owner.
         */
        function renounceOwnership() public onlyOwner {
            _setOwner(address(0));
        }
        /**
         * @dev Transfers ownership of the contract to a new account (`newOwner`).
         * Can only be called by the current owner.
         */
        function transferOwnership(address newOwner) public onlyOwner {
            _setOwner(newOwner);
        }
        function _setOwner(address newOwner) private {
            s_owner = newOwner;
        }
    }
    // SPDX-License-Identifier: UNLICENSED
    pragma solidity ^0.8.10;
    import "../libs/constant.sol";
    import "../libs/enum.sol";
    /**
     * @title BurnInfo
     * @dev this contract is meant to be inherited into main contract
     * @notice It has the variables and functions specifically for tracking burn amount and reward
     */
    abstract contract BurnInfo {
        //Variables
        //track the total titan burn amount
        uint256 private s_totalTitanBurned;
        //mappings
        //track wallet address -> total titan burn amount
        mapping(address => uint256) private s_userBurnAmount;
        //track contract/project address -> total titan burn amount
        mapping(address => uint256) private s_project_BurnAmount;
        //track contract/project address, wallet address -> total titan burn amount
        mapping(address => mapping(address => uint256)) private s_projectUser_BurnAmount;
        /** @dev cycleIndex is increased when triggerPayouts() was called successfully
         * so we track data in current cycleIndex + 1 which means tracking for the next cycle payout
         * cycleIndex is passed from the TITANX contract during function call
         */
        //track cycleIndex + 1 -> total burn amount
        mapping(uint256 => uint256) private s_cycle28TotalBurn;
        //track address, cycleIndex + 1 -> total burn amount
        mapping(address => mapping(uint256 => uint256)) private s_userCycle28TotalBurn;
        //track cycleIndex + 1 -> burn payout per token
        mapping(uint256 => uint256) private s_cycle28BurnPayoutPerToken;
        //events
        /** @dev log user burn titan event
         * project can be address(0) if user burns Titan directly from Titan contract
         * burnPoolCycleIndex is the cycle 28 index, which reuse the same index as Day 28 cycle index
         * titanSource 0=Liquid, 1=Mint, 2=Stake
         */
        event TitanBurned(
            address indexed user,
            address indexed project,
            uint256 indexed burnPoolCycleIndex,
            uint256 amount,
            BurnSource titanSource
        );
        //functions
        /** @dev update the burn amount in each 28-cylce for user and project (if any)
         * @param user wallet address
         * @param project contract address
         * @param amount titan amount burned
         * @param cycleIndex cycle payout triggered index
         */
        function _updateBurnAmount(
            address user,
            address project,
            uint256 amount,
            uint256 cycleIndex,
            BurnSource source
        ) internal {
            s_userBurnAmount[user] += amount;
            s_totalTitanBurned += amount;
            s_cycle28TotalBurn[cycleIndex] += amount;
            s_userCycle28TotalBurn[user][cycleIndex] += amount;
            if (project != address(0)) {
                s_project_BurnAmount[project] += amount;
                s_projectUser_BurnAmount[project][user] += amount;
            }
            emit TitanBurned(user, project, cycleIndex, amount, source);
        }
        /**
         * @dev calculate burn reward per titan burned based on total reward / total titan burned in current cycle
         * @param cycleIndex wallet address
         * @param reward contract address
         * @param cycleBurnAmount titan amount burned
         */
        function _calculateCycleBurnRewardPerToken(
            uint256 cycleIndex,
            uint256 reward,
            uint256 cycleBurnAmount
        ) internal {
            //add 18 decimals to reward for better precision in calculation
            s_cycle28BurnPayoutPerToken[cycleIndex] = (reward * SCALING_FACTOR_1e18) / cycleBurnAmount;
        }
        /** @dev returned value is in 18 decimals, need to divide it by 1e18 and 100 (percentage) when using this value for reward calculation
         * The burn amplifier percentage is applied to all future mints. Capped at MAX_BURN_AMP_PERCENT (8%)
         * @param user wallet address
         * @return percentage returns percentage value in 18 decimals
         */
        function getUserBurnAmplifierBonus(address user) public view returns (uint256) {
            uint256 userBurnTotal = getUserBurnTotal(user);
            if (userBurnTotal == 0) return 0;
            if (userBurnTotal >= MAX_BURN_AMP_BASE) return MAX_BURN_AMP_PERCENT;
            return (MAX_BURN_AMP_PERCENT * userBurnTotal) / MAX_BURN_AMP_BASE;
        }
        //views
        /** @notice return total burned titan amount from all users burn or projects burn
         * @return totalBurnAmount returns entire burned titan
         */
        function getTotalBurnTotal() public view returns (uint256) {
            return s_totalTitanBurned;
        }
        /** @notice return user address total burned titan
         * @return userBurnAmount returns user address total burned titan
         */
        function getUserBurnTotal(address user) public view returns (uint256) {
            return s_userBurnAmount[user];
        }
        /** @notice return project address total burned titan amount
         * @return projectTotalBurnAmount returns project total burned titan
         */
        function getProjectBurnTotal(address contractAddress) public view returns (uint256) {
            return s_project_BurnAmount[contractAddress];
        }
        /** @notice return user address total burned titan amount via a project address
         * @param contractAddress project address
         * @param user user address
         * @return projectUserTotalBurnAmount returns user address total burned titan via a project address
         */
        function getProjectUserBurnTotal(
            address contractAddress,
            address user
        ) public view returns (uint256) {
            return s_projectUser_BurnAmount[contractAddress][user];
        }
        /** @notice return cycle28 total burned titan amount with the specified cycleIndex
         * @param cycleIndex cycle index
         * @return cycle28TotalBurn returns cycle28 total burned titan amount with the specified cycleIndex
         */
        function getCycleBurnTotal(uint256 cycleIndex) public view returns (uint256) {
            return s_cycle28TotalBurn[cycleIndex];
        }
        /** @notice return cycle28 total burned titan amount with the specified cycleIndex
         * @param user user address
         * @param cycleIndex cycle index
         * @return cycle28TotalBurn returns cycle28 user address total burned titan amount with the specified cycleIndex
         */
        function _getUserCycleBurnTotal(
            address user,
            uint256 cycleIndex
        ) internal view returns (uint256) {
            return s_userCycle28TotalBurn[user][cycleIndex];
        }
        /** @notice return cycle28 burn payout per titan with the specified cycleIndex
         * @param cycleIndex cycle index
         * @return cycle28TotalBurn returns cycle28 burn payout per titan with the specified cycleIndex
         */
        function getCycleBurnPayoutPerToken(uint256 cycleIndex) public view returns (uint256) {
            return s_cycle28BurnPayoutPerToken[cycleIndex];
        }
    }
    // SPDX-License-Identifier: UNLICENSED
    pragma solidity ^0.8.10;
    import "../libs/calcFunctions.sol";
    //custom errors
    error TitanX_InvalidStakeLength();
    error TitanX_RequireOneMinimumShare();
    error TitanX_ExceedMaxAmountPerStake();
    error TitanX_NoStakeExists();
    error TitanX_StakeHasEnded();
    error TitanX_StakeNotMatured();
    error TitanX_StakeHasBurned();
    error TitanX_MaxedWalletStakes();
    abstract contract StakeInfo {
        //Variables
        /** @dev track global stake Id */
        uint256 private s_globalStakeId;
        /** @dev track global shares */
        uint256 private s_globalShares;
        /** @dev track global expired shares */
        uint256 private s_globalExpiredShares;
        /** @dev track global staked titan */
        uint256 private s_globalTitanStaked;
        /** @dev track global end stake penalty */
        uint256 private s_globalStakePenalty;
        /** @dev track global ended stake */
        uint256 private s_globalStakeEnd;
        /** @dev track global burned stake */
        uint256 private s_globalStakeBurn;
        //mappings
        /** @dev track address => stakeId */
        mapping(address => uint256) private s_addressSId;
        /** @dev track address, stakeId => global stake Id */
        mapping(address => mapping(uint256 => uint256)) private s_addressSIdToGlobalStakeId;
        /** @dev track global stake Id => stake info */
        mapping(uint256 => UserStakeInfo) private s_globalStakeIdToStakeInfo;
        /** @dev track address => shares Index */
        mapping(address => uint256) private s_userSharesIndex;
        /** @dev track user total active shares by user shares index
         * s_addressIdToActiveShares[user][index] = UserActiveShares (contract day, total user active shares)
         * works like a snapshot or log when user shares has changed (increase/decrease)
         */
        mapping(address => mapping(uint256 => UserActiveShares)) private s_addressIdToActiveShares;
        //structs
        struct UserStakeInfo {
            uint152 titanAmount;
            uint128 shares;
            uint16 numOfDays;
            uint48 stakeStartTs;
            uint48 maturityTs;
            StakeStatus status;
        }
        struct UserStake {
            uint256 sId;
            uint256 globalStakeId;
            UserStakeInfo stakeInfo;
        }
        struct UserActiveShares {
            uint256 day;
            uint256 activeShares;
        }
        //events
        event StakeStarted(
            address indexed user,
            uint256 indexed globalStakeId,
            uint256 numOfDays,
            UserStakeInfo indexed userStakeInfo
        );
        event StakeEnded(
            address indexed user,
            uint256 indexed globalStakeId,
            uint256 titanAmount,
            uint256 indexed penalty,
            uint256 penaltyAmount
        );
        //functions
        /** @dev create a new stake
         * @param user user address
         * @param amount titan amount
         * @param numOfDays stake lenght
         * @param shareRate current share rate
         * @param day current contract day
         * @param isPayoutTriggered has global payout triggered
         * @return isFirstShares first created shares or not
         */
        function _startStake(
            address user,
            uint256 amount,
            uint256 numOfDays,
            uint256 shareRate,
            uint256 day,
            PayoutTriggered isPayoutTriggered
        ) internal returns (uint256 isFirstShares) {
            uint256 sId = ++s_addressSId[user];
            if (sId > MAX_STAKE_PER_WALLET) revert TitanX_MaxedWalletStakes();
            if (numOfDays < MIN_STAKE_LENGTH || numOfDays > MAX_STAKE_LENGTH)
                revert TitanX_InvalidStakeLength();
            //calculate shares
            uint256 shares = calculateShares(amount, numOfDays, shareRate);
            if (shares / SCALING_FACTOR_1e18 < 1) revert TitanX_RequireOneMinimumShare();
            uint256 currentGStakeId = ++s_globalStakeId;
            uint256 maturityTs;
            maturityTs = block.timestamp + (numOfDays * SECONDS_IN_DAY);
            UserStakeInfo memory userStakeInfo = UserStakeInfo({
                titanAmount: uint152(amount),
                shares: uint128(shares),
                numOfDays: uint16(numOfDays),
                stakeStartTs: uint48(block.timestamp),
                maturityTs: uint48(maturityTs),
                status: StakeStatus.ACTIVE
            });
            /** s_addressSId[user] tracks stake Id for each address
             * s_addressSIdToGlobalStakeId[user][id] tracks stack id to global stake Id
             * s_globalStakeIdToStakeInfo[currentGStakeId] stores stake info
             */
            s_addressSIdToGlobalStakeId[user][sId] = currentGStakeId;
            s_globalStakeIdToStakeInfo[currentGStakeId] = userStakeInfo;
            //update shares changes
            isFirstShares = _updateSharesStats(
                user,
                shares,
                amount,
                day,
                isPayoutTriggered,
                StakeAction.START
            );
            emit StakeStarted(user, currentGStakeId, numOfDays, userStakeInfo);
        }
        /** @dev end stake and calculate pinciple with penalties (if any) or burn stake
         * @param user user address
         * @param id stake Id
         * @param day current contract day
         * @param action end stake or burn stake
         * @param payOther is end stake for others
         * @param isPayoutTriggered has global payout triggered
         * @return titan titan principle
         */
        function _endStake(
            address user,
            uint256 id,
            uint256 day,
            StakeAction action,
            StakeAction payOther,
            PayoutTriggered isPayoutTriggered
        ) internal returns (uint256 titan) {
            uint256 globalStakeId = s_addressSIdToGlobalStakeId[user][id];
            if (globalStakeId == 0) revert TitanX_NoStakeExists();
            UserStakeInfo memory userStakeInfo = s_globalStakeIdToStakeInfo[globalStakeId];
            if (userStakeInfo.status == StakeStatus.ENDED) revert TitanX_StakeHasEnded();
            if (userStakeInfo.status == StakeStatus.BURNED) revert TitanX_StakeHasBurned();
            //end stake for others requires matured stake to prevent EES for others
            if (payOther == StakeAction.END_OTHER && block.timestamp < userStakeInfo.maturityTs)
                revert TitanX_StakeNotMatured();
            //update shares changes
            uint256 shares = userStakeInfo.shares;
            _updateSharesStats(user, shares, userStakeInfo.titanAmount, day, isPayoutTriggered, action);
            if (action == StakeAction.END) {
                ++s_globalStakeEnd;
                s_globalStakeIdToStakeInfo[globalStakeId].status = StakeStatus.ENDED;
            } else if (action == StakeAction.BURN) {
                ++s_globalStakeBurn;
                s_globalStakeIdToStakeInfo[globalStakeId].status = StakeStatus.BURNED;
            }
            titan = _calculatePrinciple(user, globalStakeId, userStakeInfo, action);
        }
        /** @dev update shares changes to track when user shares has changed, this affect the payout calculation
         * @param user user address
         * @param shares shares
         * @param amount titan amount
         * @param day current contract day
         * @param isPayoutTriggered has global payout triggered
         * @param action start stake or end stake
         * @return isFirstShares first created shares or not
         */
        function _updateSharesStats(
            address user,
            uint256 shares,
            uint256 amount,
            uint256 day,
            PayoutTriggered isPayoutTriggered,
            StakeAction action
        ) private returns (uint256 isFirstShares) {
            //Get previous active shares to calculate new shares change
            uint256 index = s_userSharesIndex[user];
            uint256 previousShares = s_addressIdToActiveShares[user][index].activeShares;
            if (action == StakeAction.START) {
                //return 1 if this is a new wallet address
                //this is used to initialize last claim index to the latest cycle index
                if (index == 0) isFirstShares = 1;
                s_addressIdToActiveShares[user][++index].activeShares = previousShares + shares;
                s_globalShares += shares;
                s_globalTitanStaked += amount;
            } else {
                s_addressIdToActiveShares[user][++index].activeShares = previousShares - shares;
                s_globalExpiredShares += shares;
                s_globalTitanStaked -= amount;
            }
            //If global payout hasn't triggered, use current contract day to eligible for payout
            //If global payout has triggered, then start with next contract day as it's no longer eligible to claim latest payout
            s_addressIdToActiveShares[user][index].day = uint128(
                isPayoutTriggered == PayoutTriggered.NO ? day : day + 1
            );
            s_userSharesIndex[user] = index;
        }
        /** @dev calculate stake principle and apply penalty (if any)
         * @param user user address
         * @param globalStakeId global stake Id
         * @param userStakeInfo stake info
         * @param action end stake or burn stake
         * @return principle calculated principle after penalty (if any)
         */
        function _calculatePrinciple(
            address user,
            uint256 globalStakeId,
            UserStakeInfo memory userStakeInfo,
            StakeAction action
        ) internal returns (uint256 principle) {
            uint256 titanAmount = userStakeInfo.titanAmount;
            //penalty is in percentage
            uint256 penalty = calculateEndStakePenalty(
                userStakeInfo.stakeStartTs,
                userStakeInfo.maturityTs,
                block.timestamp,
                action
            );
            uint256 penaltyAmount;
            penaltyAmount = (titanAmount * penalty) / 100;
            principle = titanAmount - penaltyAmount;
            s_globalStakePenalty += penaltyAmount;
            emit StakeEnded(user, globalStakeId, principle, penalty, penaltyAmount);
        }
        //Views
        /** @notice get global shares
         * @return globalShares global shares
         */
        function getGlobalShares() public view returns (uint256) {
            return s_globalShares;
        }
        /** @notice get global expired shares
         * @return globalExpiredShares global expired shares
         */
        function getGlobalExpiredShares() public view returns (uint256) {
            return s_globalExpiredShares;
        }
        /** @notice get global active shares
         * @return globalActiveShares global active shares
         */
        function getGlobalActiveShares() public view returns (uint256) {
            return s_globalShares - s_globalExpiredShares;
        }
        /** @notice get total titan staked
         * @return totalTitanStaked total titan staked
         */
        function getTotalTitanStaked() public view returns (uint256) {
            return s_globalTitanStaked;
        }
        /** @notice get global stake id
         * @return globalStakeId global stake id
         */
        function getGlobalStakeId() public view returns (uint256) {
            return s_globalStakeId;
        }
        /** @notice get global active stakes
         * @return globalActiveStakes global active stakes
         */
        function getGlobalActiveStakes() public view returns (uint256) {
            return s_globalStakeId - getTotalStakeEnd();
        }
        /** @notice get total stake ended
         * @return totalStakeEnded total stake ended
         */
        function getTotalStakeEnd() public view returns (uint256) {
            return s_globalStakeEnd;
        }
        /** @notice get total stake burned
         * @return totalStakeBurned total stake burned
         */
        function getTotalStakeBurn() public view returns (uint256) {
            return s_globalStakeBurn;
        }
        /** @notice get total end stake penalty
         * @return totalEndStakePenalty total end stake penalty
         */
        function getTotalStakePenalty() public view returns (uint256) {
            return s_globalStakePenalty;
        }
        /** @notice get user latest shares index
         * @return latestSharesIndex latest shares index
         */
        function getUserLatestShareIndex(address user) public view returns (uint256) {
            return s_userSharesIndex[user];
        }
        /** @notice get user current active shares
         * @return currentActiveShares current active shares
         */
        function getUserCurrentActiveShares(address user) public view returns (uint256) {
            return s_addressIdToActiveShares[user][getUserLatestShareIndex(user)].activeShares;
        }
        /** @notice get user active shares at sharesIndex
         * @return activeShares active shares at sharesIndex
         */
        function getUserActiveShares(
            address user,
            uint256 sharesIndex
        ) internal view returns (uint256) {
            return s_addressIdToActiveShares[user][sharesIndex].activeShares;
        }
        /** @notice get user active shares contract day at sharesIndex
         * @return activeSharesDay active shares contract day at sharesIndex
         */
        function getUserActiveSharesDay(
            address user,
            uint256 sharesIndex
        ) internal view returns (uint256) {
            return s_addressIdToActiveShares[user][sharesIndex].day;
        }
        /** @notice get stake info with stake id
         * @return stakeInfo stake info
         */
        function getUserStakeInfo(address user, uint256 id) public view returns (UserStakeInfo memory) {
            return s_globalStakeIdToStakeInfo[s_addressSIdToGlobalStakeId[user][id]];
        }
        /** @notice get all stake info of an address
         * @return stakeInfos all stake info of an address
         */
        function getUserStakes(address user) public view returns (UserStake[] memory) {
            uint256 count = s_addressSId[user];
            UserStake[] memory stakes = new UserStake[](count);
            for (uint256 i = 1; i <= count; i++) {
                stakes[i - 1] = UserStake({
                    sId: i,
                    globalStakeId: uint128(s_addressSIdToGlobalStakeId[user][i]),
                    stakeInfo: getUserStakeInfo(user, i)
                });
            }
            return stakes;
        }
    }
    // SPDX-License-Identifier: UNLICENSED
    pragma solidity ^0.8.10;
    import "../libs/calcFunctions.sol";
    //custom errors
    error TitanX_InvalidMintLength();
    error TitanX_InvalidMintPower();
    error TitanX_NoMintExists();
    error TitanX_MintHasClaimed();
    error TitanX_MintNotMature();
    error TitanX_MintHasBurned();
    abstract contract MintInfo {
        //variables
        /** @dev track global tRank */
        uint256 private s_globalTRank;
        /** @dev track total mint claimed */
        uint256 private s_globalMintClaim;
        /** @dev track total mint burned */
        uint256 private s_globalMintBurn;
        /** @dev track total titan minting */
        uint256 private s_globalTitanMinting;
        /** @dev track total titan penalty */
        uint256 private s_globalTitanMintPenalty;
        /** @dev track global mint power */
        uint256 private s_globalMintPower;
        //mappings
        /** @dev track address => mintId */
        mapping(address => uint256) private s_addressMId;
        /** @dev track address, mintId => tRank info (gTrank, gMintPower) */
        mapping(address => mapping(uint256 => TRankInfo)) private s_addressMIdToTRankInfo;
        /** @dev track global tRank => mintInfo*/
        mapping(uint256 => UserMintInfo) private s_tRankToMintInfo;
        //structs
        struct UserMintInfo {
            uint8 mintPower;
            uint16 numOfDays;
            uint96 mintableTitan;
            uint48 mintStartTs;
            uint48 maturityTs;
            uint32 mintPowerBonus;
            uint32 EAABonus;
            uint128 mintedTitan;
            uint64 mintCost;
            MintStatus status;
        }
        struct TRankInfo {
            uint256 tRank;
            uint256 gMintPower;
        }
        struct UserMint {
            uint256 mId;
            uint256 tRank;
            uint256 gMintPower;
            UserMintInfo mintInfo;
        }
        //events
        event MintStarted(
            address indexed user,
            uint256 indexed tRank,
            uint256 indexed gMintpower,
            UserMintInfo userMintInfo
        );
        event MintClaimed(
            address indexed user,
            uint256 indexed tRank,
            uint256 rewardMinted,
            uint256 indexed penalty,
            uint256 mintPenalty
        );
        //functions
        /** @dev create a new mint
         * @param user user address
         * @param mintPower mint power
         * @param numOfDays mint lenght
         * @param mintableTitan mintable titan
         * @param mintPowerBonus mint power bonus
         * @param EAABonus EAA bonus
         * @param burnAmpBonus burn amplifier bonus
         * @param gMintPower global mint power
         * @param currentTRank current global tRank
         * @param mintCost actual mint cost paid for a mint
         */
        function _startMint(
            address user,
            uint256 mintPower,
            uint256 numOfDays,
            uint256 mintableTitan,
            uint256 mintPowerBonus,
            uint256 EAABonus,
            uint256 burnAmpBonus,
            uint256 gMintPower,
            uint256 currentTRank,
            uint256 mintCost
        ) internal returns (uint256 mintable) {
            if (numOfDays == 0 || numOfDays > MAX_MINT_LENGTH) revert TitanX_InvalidMintLength();
            if (mintPower == 0 || mintPower > MAX_MINT_POWER_CAP) revert TitanX_InvalidMintPower();
            //calculate mint reward up front with the provided params
            mintable = calculateMintReward(mintPower, numOfDays, mintableTitan, EAABonus, burnAmpBonus);
            //store variables into mint info
            UserMintInfo memory userMintInfo = UserMintInfo({
                mintPower: uint8(mintPower),
                numOfDays: uint16(numOfDays),
                mintableTitan: uint96(mintable),
                mintPowerBonus: uint32(mintPowerBonus),
                EAABonus: uint32(EAABonus),
                mintStartTs: uint48(block.timestamp),
                maturityTs: uint48(block.timestamp + (numOfDays * SECONDS_IN_DAY)),
                mintedTitan: 0,
                mintCost: uint64(mintCost),
                status: MintStatus.ACTIVE
            });
            /** s_addressMId[user] tracks mintId for each addrress
             * s_addressMIdToTRankInfo[user][id] tracks current mint tRank and gPowerMint
             *  s_tRankToMintInfo[currentTRank] stores mint info
             */
            uint256 id = ++s_addressMId[user];
            s_addressMIdToTRankInfo[user][id].tRank = currentTRank;
            s_addressMIdToTRankInfo[user][id].gMintPower = gMintPower;
            s_tRankToMintInfo[currentTRank] = userMintInfo;
            emit MintStarted(user, currentTRank, gMintPower, userMintInfo);
        }
        /** @dev create new mint in a batch of up to max 100 mints with the same mint length
         * @param user user address
         * @param mintPower mint power
         * @param numOfDays mint lenght
         * @param mintableTitan mintable titan
         * @param mintPowerBonus mint power bonus
         * @param EAABonus EAA bonus
         * @param burnAmpBonus burn amplifier bonus
         * @param mintCost actual mint cost paid for a mint
         */
        function _startBatchMint(
            address user,
            uint256 mintPower,
            uint256 numOfDays,
            uint256 mintableTitan,
            uint256 mintPowerBonus,
            uint256 EAABonus,
            uint256 burnAmpBonus,
            uint256 count,
            uint256 mintCost
        ) internal {
            uint256 gMintPower = s_globalMintPower;
            uint256 currentTRank = s_globalTRank;
            uint256 gMinting = s_globalTitanMinting;
            for (uint256 i = 0; i < count; i++) {
                gMintPower += mintPower;
                gMinting += _startMint(
                    user,
                    mintPower,
                    numOfDays,
                    mintableTitan,
                    mintPowerBonus,
                    EAABonus,
                    burnAmpBonus,
                    gMintPower,
                    ++currentTRank,
                    mintCost
                );
            }
            _updateMintStats(currentTRank, gMintPower, gMinting);
        }
        /** @dev create new mint in a batch of up to max 100 mints with different mint length
         * @param user user address
         * @param mintPower mint power
         * @param minDay minimum start day
         * @param maxDay maximum end day
         * @param dayInterval days interval between each new mint length
         * @param countPerInterval number of mint(s) to create in each mint length interval
         * @param mintableTitan mintable titan
         * @param mintPowerBonus mint power bonus
         * @param EAABonus EAA bonus
         * @param burnAmpBonus burn amplifier bonus
         * @param mintCost actual mint cost paid for a mint
         */
        function _startbatchMintLadder(
            address user,
            uint256 mintPower,
            uint256 minDay,
            uint256 maxDay,
            uint256 dayInterval,
            uint256 countPerInterval,
            uint256 mintableTitan,
            uint256 mintPowerBonus,
            uint256 EAABonus,
            uint256 burnAmpBonus,
            uint256 mintCost
        ) internal {
            uint256 gMintPower = s_globalMintPower;
            uint256 currentTRank = s_globalTRank;
            uint256 gMinting = s_globalTitanMinting;
            /**first for loop is used to determine mint length
             * minDay is the starting mint length
             * maxDay is the max mint length where it stops
             * dayInterval increases the minDay for the next mint
             */
            for (; minDay <= maxDay; minDay += dayInterval) {
                /**first for loop is used to determine mint length
                 * second for loop is to create number mints per mint length
                 */
                for (uint256 j = 0; j < countPerInterval; j++) {
                    gMintPower += mintPower;
                    gMinting += _startMint(
                        user,
                        mintPower,
                        minDay,
                        mintableTitan,
                        mintPowerBonus,
                        EAABonus,
                        burnAmpBonus,
                        gMintPower,
                        ++currentTRank,
                        mintCost
                    );
                }
            }
            _updateMintStats(currentTRank, gMintPower, gMinting);
        }
        /** @dev update variables
         * @param currentTRank current tRank
         * @param gMintPower current global mint power
         * @param gMinting current global minting
         */
        function _updateMintStats(uint256 currentTRank, uint256 gMintPower, uint256 gMinting) internal {
            s_globalTRank = currentTRank;
            s_globalMintPower = gMintPower;
            s_globalTitanMinting = gMinting;
        }
        /** @dev calculate reward for claim mint or burn mint.
         * Claim mint has maturity check while burn mint would bypass maturity check.
         * @param user user address
         * @param id mint id
         * @param action claim mint or burn mint
         * @return reward calculated final reward after all bonuses and penalty (if any)
         */
        function _claimMint(
            address user,
            uint256 id,
            MintAction action
        ) internal returns (uint256 reward) {
            uint256 tRank = s_addressMIdToTRankInfo[user][id].tRank;
            uint256 gMintPower = s_addressMIdToTRankInfo[user][id].gMintPower;
            if (tRank == 0) revert TitanX_NoMintExists();
            UserMintInfo memory mint = s_tRankToMintInfo[tRank];
            if (mint.status == MintStatus.CLAIMED) revert TitanX_MintHasClaimed();
            if (mint.status == MintStatus.BURNED) revert TitanX_MintHasBurned();
            //Only check maturity for claim mint action, burn mint bypass this check
            if (mint.maturityTs > block.timestamp && action == MintAction.CLAIM)
                revert TitanX_MintNotMature();
            s_globalTitanMinting -= mint.mintableTitan;
            reward = _calculateClaimReward(user, tRank, gMintPower, mint, action);
        }
        /** @dev calculate reward up to 100 claims for batch claim function. Only calculate active and matured mints.
         * @param user user address
         * @return reward total batch claims final calculated reward after all bonuses and penalty (if any)
         */
        function _batchClaimMint(address user) internal returns (uint256 reward) {
            uint256 maxId = s_addressMId[user];
            uint256 claimCount;
            uint256 tRank;
            uint256 gMinting;
            UserMintInfo memory mint;
            for (uint256 i = 1; i <= maxId; i++) {
                tRank = s_addressMIdToTRankInfo[user][i].tRank;
                mint = s_tRankToMintInfo[tRank];
                if (mint.status == MintStatus.ACTIVE && block.timestamp >= mint.maturityTs) {
                    reward += _calculateClaimReward(
                        user,
                        tRank,
                        s_addressMIdToTRankInfo[user][i].gMintPower,
                        mint,
                        MintAction.CLAIM
                    );
                    gMinting += mint.mintableTitan;
                    ++claimCount;
                }
                if (claimCount == 100) break;
            }
            s_globalTitanMinting -= gMinting;
        }
        /** @dev calculate final reward with bonuses and penalty (if any)
         * @param user user address
         * @param tRank mint's tRank
         * @param gMintPower mint's gMintPower
         * @param userMintInfo mint's info
         * @param action claim mint or burn mint
         * @return reward calculated final reward after all bonuses and penalty (if any)
         */
        function _calculateClaimReward(
            address user,
            uint256 tRank,
            uint256 gMintPower,
            UserMintInfo memory userMintInfo,
            MintAction action
        ) private returns (uint256 reward) {
            if (action == MintAction.CLAIM) s_tRankToMintInfo[tRank].status = MintStatus.CLAIMED;
            if (action == MintAction.BURN) s_tRankToMintInfo[tRank].status = MintStatus.BURNED;
            uint256 penaltyAmount;
            uint256 penalty;
            uint256 bonus;
            //only calculate penalty when current block timestamp > maturity timestamp
            if (block.timestamp > userMintInfo.maturityTs) {
                penalty = calculateClaimMintPenalty(block.timestamp - userMintInfo.maturityTs);
            }
            //Only Claim action has mintPower bonus
            if (action == MintAction.CLAIM) {
                bonus = calculateMintPowerBonus(
                    userMintInfo.mintPowerBonus,
                    userMintInfo.mintPower,
                    gMintPower,
                    s_globalMintPower
                );
            }
            //mintPowerBonus has scaling factor of 1e7, so divide by 1e7
            reward = uint256(userMintInfo.mintableTitan) + (bonus / SCALING_FACTOR_1e7);
            penaltyAmount = (reward * penalty) / 100;
            reward -= penaltyAmount;
            if (action == MintAction.CLAIM) ++s_globalMintClaim;
            if (action == MintAction.BURN) ++s_globalMintBurn;
            if (penaltyAmount != 0) s_globalTitanMintPenalty += penaltyAmount;
            //only stored minted amount for claim mint
            if (action == MintAction.CLAIM) s_tRankToMintInfo[tRank].mintedTitan = uint128(reward);
            emit MintClaimed(user, tRank, reward, penalty, penaltyAmount);
        }
        //views
        /** @notice Returns the latest Mint Id of an address
         * @param user address
         * @return mId latest mint id
         */
        function getUserLatestMintId(address user) public view returns (uint256) {
            return s_addressMId[user];
        }
        /** @notice Returns mint info of an address + mint id
         * @param user address
         * @param id mint id
         * @return mintInfo user mint info
         */
        function getUserMintInfo(
            address user,
            uint256 id
        ) public view returns (UserMintInfo memory mintInfo) {
            return s_tRankToMintInfo[s_addressMIdToTRankInfo[user][id].tRank];
        }
        /** @notice Return all mints info of an address
         * @param user address
         * @return mintInfos all mints info of an address including mint id, tRank and gMintPower
         */
        function getUserMints(address user) public view returns (UserMint[] memory mintInfos) {
            uint256 count = s_addressMId[user];
            mintInfos = new UserMint[](count);
            for (uint256 i = 1; i <= count; i++) {
                mintInfos[i - 1] = UserMint({
                    mId: i,
                    tRank: s_addressMIdToTRankInfo[user][i].tRank,
                    gMintPower: s_addressMIdToTRankInfo[user][i].gMintPower,
                    mintInfo: getUserMintInfo(user, i)
                });
            }
        }
        /** @notice Return total mints burned
         * @return totalMintBurned total mints burned
         */
        function getTotalMintBurn() public view returns (uint256) {
            return s_globalMintBurn;
        }
        /** @notice Return current gobal tRank
         * @return globalTRank global tRank
         */
        function getGlobalTRank() public view returns (uint256) {
            return s_globalTRank;
        }
        /** @notice Return current gobal mint power
         * @return globalMintPower global mint power
         */
        function getGlobalMintPower() public view returns (uint256) {
            return s_globalMintPower;
        }
        /** @notice Return total mints claimed
         * @return totalMintClaimed total mints claimed
         */
        function getTotalMintClaim() public view returns (uint256) {
            return s_globalMintClaim;
        }
        /** @notice Return total active mints (exluded claimed and burned mints)
         * @return totalActiveMints total active mints
         */
        function getTotalActiveMints() public view returns (uint256) {
            return s_globalTRank - s_globalMintClaim - s_globalMintBurn;
        }
        /** @notice Return total minting titan
         * @return totalMinting total minting titan
         */
        function getTotalMinting() public view returns (uint256) {
            return s_globalTitanMinting;
        }
        /** @notice Return total titan penalty
         * @return totalTitanPenalty total titan penalty
         */
        function getTotalMintPenalty() public view returns (uint256) {
            return s_globalTitanMintPenalty;
        }
    }
    // SPDX-License-Identifier: UNLICENSED
    pragma solidity ^0.8.10;
    import "../libs/enum.sol";
    import "../libs/constant.sol";
    abstract contract GlobalInfo {
        //Variables
        //deployed timestamp
        uint256 private immutable i_genesisTs;
        /** @dev track current contract day */
        uint256 private s_currentContractDay;
        /** @dev shareRate starts 800 ether and increases capped at 2800 ether, uint72 has enough size */
        uint72 private s_currentshareRate;
        /** @dev mintCost starts 0.2 ether increases and capped at 1 ether, uint64 has enough size */
        uint64 private s_currentMintCost;
        /** @dev mintableTitan starts 8m ether decreases and capped at 800 ether, uint96 has enough size */
        uint96 private s_currentMintableTitan;
        /** @dev mintPowerBonus starts 350_000_000 and decreases capped at 35_000, uint32 has enough size */
        uint32 private s_currentMintPowerBonus;
        /** @dev EAABonus starts 10_000_000 and decreases to 0, uint32 has enough size */
        uint32 private s_currentEAABonus;
        /** @dev track if any of the cycle day 8, 28, 90, 369, 888 has payout triggered succesfully
         * this is used in end stake where either the shares change should be tracked in current/next payout cycle
         */
        PayoutTriggered private s_isGlobalPayoutTriggered;
        /** @dev track payouts based on every cycle day 8, 28, 90, 369, 888 when distributeETH() is called */
        mapping(uint256 => uint256) private s_cyclePayouts;
        /** @dev track payout index for each cycle day, increased by 1 when triggerPayouts() is called succesfully
         *  eg. curent index is 2, s_cyclePayoutIndex[DAY8] = 2 */
        mapping(uint256 => uint256) private s_cyclePayoutIndex;
        /** @dev track payout info (day and payout per share) for each cycle day
         * eg. s_cyclePayoutIndex is 2,
         *  s_CyclePayoutPerShare[DAY8][2].day = 8
         * s_CyclePayoutPerShare[DAY8][2].payoutPerShare = 0.1
         */
        mapping(uint256 => mapping(uint256 => CycleRewardPerShare)) private s_cyclePayoutPerShare;
        /** @dev track user last payout reward claim index for cycleIndex, burnCycleIndex and sharesIndex
         * so calculation would start from next index instead of the first index
         * [address][DAY8].cycleIndex = 1
         * [address][DAY8].burnCycleIndex = 1
         * [address][DAY8].sharesIndex = 2
         * cycleIndex is the last stop in s_cyclePayoutPerShare
         * sharesIndex is the last stop in s_addressIdToActiveShares
         */
        mapping(address => mapping(uint256 => UserCycleClaimIndex))
            private s_addressCycleToLastClaimIndex;
        /** @dev track when is the next cycle payout day for each cycle day
         * eg. s_nextCyclePayoutDay[DAY8] = 8
         *     s_nextCyclePayoutDay[DAY28] = 28
         */
        mapping(uint256 => uint256) s_nextCyclePayoutDay;
        //structs
        struct CycleRewardPerShare {
            uint256 day;
            uint256 payoutPerShare;
        }
        struct UserCycleClaimIndex {
            uint96 cycleIndex;
            uint96 burnCycleIndex;
            uint64 sharesIndex;
        }
        //event
        event GlobalDailyUpdateStats(
            uint256 indexed day,
            uint256 indexed mintCost,
            uint256 indexed shareRate,
            uint256 mintableTitan,
            uint256 mintPowerBonus,
            uint256 EAABonus
        );
        /** @dev Update variables in terms of day, modifier is used in all external/public functions (exclude view)
         * Every interaction to the contract would run this function to update variables
         */
        modifier dailyUpdate() {
            _dailyUpdate();
            _;
        }
        constructor() {
            i_genesisTs = block.timestamp;
            s_currentContractDay = 1;
            s_currentMintCost = uint64(START_MAX_MINT_COST);
            s_currentMintableTitan = uint96(START_MAX_MINTABLE_PER_DAY);
            s_currentshareRate = uint72(START_SHARE_RATE);
            s_currentMintPowerBonus = uint32(START_MINTPOWER_INCREASE_BONUS);
            s_currentEAABonus = uint32(EAA_START);
            s_nextCyclePayoutDay[DAY8] = DAY8;
            s_nextCyclePayoutDay[DAY28] = DAY28;
            s_nextCyclePayoutDay[DAY90] = DAY90;
            s_nextCyclePayoutDay[DAY369] = DAY369;
            s_nextCyclePayoutDay[DAY888] = DAY888;
        }
        /** @dev calculate and update variables daily and reset triggers flag */
        function _dailyUpdate() private {
            uint256 currentContractDay = s_currentContractDay;
            uint256 currentBlockDay = ((block.timestamp - i_genesisTs) / 1 days) + 1;
            if (currentBlockDay > currentContractDay) {
                //get last day info ready for calculation
                uint256 newMintCost = s_currentMintCost;
                uint256 newShareRate = s_currentshareRate;
                uint256 newMintableTitan = s_currentMintableTitan;
                uint256 newMintPowerBonus = s_currentMintPowerBonus;
                uint256 newEAABonus = s_currentEAABonus;
                uint256 dayDifference = currentBlockDay - currentContractDay;
                /** Reason for a for loop to update Mint supply
                 * Ideally, user interaction happens daily, so Mint supply is synced in every day
                 *      (cylceDifference = 1)
                 * However, if there's no interaction for more than 1 day, then
                 *      Mint supply isn't updated correctly due to cylceDifference > 1 day
                 * Eg. 2 days of no interaction, then interaction happens in 3rd day.
                 *     It's incorrect to only decrease the Mint supply one time as now it's in 3rd day.
                 *   And if this happens, there will be no tracked data for the skipped days as not needed
                 */
                for (uint256 i; i < dayDifference; i++) {
                    newMintCost = (newMintCost * DAILY_MINT_COST_INCREASE_STEP) / PERCENT_BPS;
                    newShareRate = (newShareRate * DAILY_SHARE_RATE_INCREASE_STEP) / PERCENT_BPS;
                    newMintableTitan =
                        (newMintableTitan * DAILY_SUPPLY_MINTABLE_REDUCTION) /
                        PERCENT_BPS;
                    newMintPowerBonus =
                        (newMintPowerBonus * DAILY_MINTPOWER_INCREASE_BONUS_REDUCTION) /
                        PERCENT_BPS;
                    if (newMintCost > 1 ether) {
                        newMintCost = CAPPED_MAX_MINT_COST;
                    }
                    if (newShareRate > CAPPED_MAX_RATE) newShareRate = CAPPED_MAX_RATE;
                    if (newMintableTitan < CAPPED_MIN_DAILY_TITAN_MINTABLE) {
                        newMintableTitan = CAPPED_MIN_DAILY_TITAN_MINTABLE;
                    }
                    if (newMintPowerBonus < CAPPED_MIN_MINTPOWER_BONUS) {
                        newMintPowerBonus = CAPPED_MIN_MINTPOWER_BONUS;
                    }
                    if (currentBlockDay <= MAX_BONUS_DAY) {
                        newEAABonus -= EAA_BONUSE_FIXED_REDUCTION_PER_DAY;
                    } else {
                        newEAABonus = EAA_END;
                    }
                    emit GlobalDailyUpdateStats(
                        ++currentContractDay,
                        newMintCost,
                        newShareRate,
                        newMintableTitan,
                        newMintPowerBonus,
                        newEAABonus
                    );
                }
                s_currentMintCost = uint64(newMintCost);
                s_currentshareRate = uint72(newShareRate);
                s_currentMintableTitan = uint96(newMintableTitan);
                s_currentMintPowerBonus = uint32(newMintPowerBonus);
                s_currentEAABonus = uint32(newEAABonus);
                s_currentContractDay = currentBlockDay;
                s_isGlobalPayoutTriggered = PayoutTriggered.NO;
            }
        }
        /** @dev first created shares will start from the last payout index + 1 (next cycle payout)
         * as first shares will always disqualified from past payouts
         * reduce gas cost needed to loop from first index
         * @param user user address
         * @param isFirstShares flag to only initialize when address is fresh wallet
         */
        function _initFirstSharesCycleIndex(address user, uint256 isFirstShares) internal {
            if (isFirstShares == 1) {
                if (s_cyclePayoutIndex[DAY8] != 0) {
                    s_addressCycleToLastClaimIndex[user][DAY8].cycleIndex = uint96(
                        s_cyclePayoutIndex[DAY8] + 1
                    );
                    s_addressCycleToLastClaimIndex[user][DAY28].cycleIndex = uint96(
                        s_cyclePayoutIndex[DAY28] + 1
                    );
                    s_addressCycleToLastClaimIndex[user][DAY90].cycleIndex = uint96(
                        s_cyclePayoutIndex[DAY90] + 1
                    );
                    s_addressCycleToLastClaimIndex[user][DAY369].cycleIndex = uint96(
                        s_cyclePayoutIndex[DAY369] + 1
                    );
                    s_addressCycleToLastClaimIndex[user][DAY888].cycleIndex = uint96(
                        s_cyclePayoutIndex[DAY888] + 1
                    );
                }
            }
        }
        /** @dev first created shares will start from the last payout index + 1 (next cycle payout)
         * as first shares will always disqualified from past payouts
         * reduce gas cost needed to loop from first index
         * @param cycleNo cylce day 8, 28, 90, 369, 888
         * @param reward total accumulated reward in cycle day 8, 28, 90, 369, 888
         * @param globalActiveShares global active shares
         * @return index return latest current cycleIndex
         */
        function _calculateCycleRewardPerShare(
            uint256 cycleNo,
            uint256 reward,
            uint256 globalActiveShares
        ) internal returns (uint256 index) {
            s_cyclePayouts[cycleNo] = 0;
            index = ++s_cyclePayoutIndex[cycleNo];
            //add 18 decimals to reward for better precision in calculation
            s_cyclePayoutPerShare[cycleNo][index].payoutPerShare =
                (reward * SCALING_FACTOR_1e18) /
                globalActiveShares;
            s_cyclePayoutPerShare[cycleNo][index].day = getCurrentContractDay();
        }
        /** @dev update with the last index where a user has claimed the payout reward
         * @param user user address
         * @param cycleNo cylce day 8, 28, 90, 369, 888
         * @param userClaimCycleIndex last claimed cycle index
         * @param userClaimSharesIndex last claimed shares index
         */
        function _updateUserClaimIndexes(
            address user,
            uint256 cycleNo,
            uint256 userClaimCycleIndex,
            uint256 userClaimSharesIndex
        ) internal {
            if (userClaimCycleIndex != s_addressCycleToLastClaimIndex[user][cycleNo].cycleIndex)
                s_addressCycleToLastClaimIndex[user][cycleNo].cycleIndex = uint96(userClaimCycleIndex);
            if (userClaimSharesIndex != s_addressCycleToLastClaimIndex[user][cycleNo].sharesIndex)
                s_addressCycleToLastClaimIndex[user][cycleNo].sharesIndex = uint64(
                    userClaimSharesIndex
                );
        }
        /** @dev update with the last index where a user has claimed the burn payout reward
         * @param user user address
         * @param cycleNo cylce day 8, 28, 90, 369, 888
         * @param userClaimBurnCycleIndex last claimed burn cycle index
         */
        function _updateUserBurnCycleClaimIndex(
            address user,
            uint256 cycleNo,
            uint256 userClaimBurnCycleIndex
        ) internal {
            if (userClaimBurnCycleIndex != s_addressCycleToLastClaimIndex[user][cycleNo].burnCycleIndex)
                s_addressCycleToLastClaimIndex[user][cycleNo].burnCycleIndex = uint96(
                    userClaimBurnCycleIndex
                );
        }
        /** @dev set to YES when any of the cycle days payout is triggered
         * reset to NO in new contract day
         */
        function _setGlobalPayoutTriggered() internal {
            s_isGlobalPayoutTriggered = PayoutTriggered.YES;
        }
        /** @dev add reward into cycle day 8, 28, 90, 369, 888 pool
         * @param cycleNo cycle day 8, 28, 90, 369, 888
         * @param reward reward from distributeETH()
         */
        function _setCyclePayoutPool(uint256 cycleNo, uint256 reward) internal {
            s_cyclePayouts[cycleNo] += reward;
        }
        /** @dev calculate and update the next payout day for specified cycleNo
         * the formula will update the payout day based on current contract day
         * this is to make sure the value is correct when for some reason has skipped more than one cycle payout
         * @param cycleNo cycle day 8, 28, 90, 369, 888
         */
        function _setNextCyclePayoutDay(uint256 cycleNo) internal {
            uint256 maturityDay = s_nextCyclePayoutDay[cycleNo];
            uint256 currentContractDay = s_currentContractDay;
            if (currentContractDay >= maturityDay) {
                s_nextCyclePayoutDay[cycleNo] +=
                    cycleNo *
                    (((currentContractDay - maturityDay) / cycleNo) + 1);
            }
        }
        /** Views */
        /** @notice Returns current block timestamp
         * @return currentBlockTs current block timestamp
         */
        function getCurrentBlockTimeStamp() public view returns (uint256) {
            return block.timestamp;
        }
        /** @notice Returns current contract day
         * @return currentContractDay current contract day
         */
        function getCurrentContractDay() public view returns (uint256) {
            return s_currentContractDay;
        }
        /** @notice Returns current mint cost
         * @return currentMintCost current block timestamp
         */
        function getCurrentMintCost() public view returns (uint256) {
            return s_currentMintCost;
        }
        /** @notice Returns current share rate
         * @return currentShareRate current share rate
         */
        function getCurrentShareRate() public view returns (uint256) {
            return s_currentshareRate;
        }
        /** @notice Returns current mintable titan
         * @return currentMintableTitan current mintable titan
         */
        function getCurrentMintableTitan() public view returns (uint256) {
            return s_currentMintableTitan;
        }
        /** @notice Returns current mint power bonus
         * @return currentMintPowerBonus current mint power bonus
         */
        function getCurrentMintPowerBonus() public view returns (uint256) {
            return s_currentMintPowerBonus;
        }
        /** @notice Returns current contract EAA bonus
         * @return currentEAABonus current EAA bonus
         */
        function getCurrentEAABonus() public view returns (uint256) {
            return s_currentEAABonus;
        }
        /** @notice Returns current cycle index for the specified cycle day
         * @param cycleNo cycle day 8, 28, 90, 369, 888
         * @return currentCycleIndex current cycle index to track the payouts
         */
        function getCurrentCycleIndex(uint256 cycleNo) public view returns (uint256) {
            return s_cyclePayoutIndex[cycleNo];
        }
        /** @notice Returns whether payout is triggered successfully in any cylce day
         * @return isTriggered 0 or 1, 0= No, 1=Yes
         */
        function getGlobalPayoutTriggered() public view returns (PayoutTriggered) {
            return s_isGlobalPayoutTriggered;
        }
        /** @notice Returns the distributed pool reward for the specified cycle day
         * @param cycleNo cycle day 8, 28, 90, 369, 888
         * @return currentPayoutPool current accumulated payout pool
         */
        function getCyclePayoutPool(uint256 cycleNo) public view returns (uint256) {
            return s_cyclePayouts[cycleNo];
        }
        /** @notice Returns the calculated payout per share and contract day for the specified cycle day and index
         * @param cycleNo cycle day 8, 28, 90, 369, 888
         * @param index cycle index
         * @return payoutPerShare calculated payout per share
         * @return triggeredDay the day when payout was triggered to perform calculation
         */
        function getPayoutPerShare(
            uint256 cycleNo,
            uint256 index
        ) public view returns (uint256, uint256) {
            return (
                s_cyclePayoutPerShare[cycleNo][index].payoutPerShare,
                s_cyclePayoutPerShare[cycleNo][index].day
            );
        }
        /** @notice Returns user's last claimed shares payout indexes for the specified cycle day
         * @param user user address
         * @param cycleNo cycle day 8, 28, 90, 369, 888
         * @return cycleIndex cycle index
         * @return sharesIndex shares index
         
         */
        function getUserLastClaimIndex(
            address user,
            uint256 cycleNo
        ) public view returns (uint256 cycleIndex, uint256 sharesIndex) {
            return (
                s_addressCycleToLastClaimIndex[user][cycleNo].cycleIndex,
                s_addressCycleToLastClaimIndex[user][cycleNo].sharesIndex
            );
        }
        /** @notice Returns user's last claimed burn payout index for the specified cycle day
         * @param user user address
         * @param cycleNo cycle day 8, 28, 90, 369, 888
         * @return burnCycleIndex burn cycle index
         */
        function getUserLastBurnClaimIndex(
            address user,
            uint256 cycleNo
        ) public view returns (uint256 burnCycleIndex) {
            return s_addressCycleToLastClaimIndex[user][cycleNo].burnCycleIndex;
        }
        /** @notice Returns contract deployment block timestamp
         * @return genesisTs deployed timestamp
         */
        function genesisTs() public view returns (uint256) {
            return i_genesisTs;
        }
        /** @notice Returns next payout day for the specified cycle day
         * @param cycleNo cycle day 8, 28, 90, 369, 888
         * @return nextPayoutDay next payout day
         */
        function getNextCyclePayoutDay(uint256 cycleNo) public view returns (uint256) {
            return s_nextCyclePayoutDay[cycleNo];
        }
    }
    // SPDX-License-Identifier: UNLICENSED
    pragma solidity ^0.8.10;
    import "./constant.sol";
    import "./enum.sol";
    //TitanX
    /**@notice get batch mint ladder total count
     * @param minDay minimum mint length
     * @param maxDay maximum mint length, cap at 280
     * @param dayInterval day increase from previous mint length
     * @param countPerInterval number of mints per minth length
     * @return count total mints
     */
    function getBatchMintLadderCount(
        uint256 minDay,
        uint256 maxDay,
        uint256 dayInterval,
        uint256 countPerInterval
    ) pure returns (uint256 count) {
        if (maxDay > minDay) {
            count = (((maxDay - minDay) / dayInterval) + 1) * countPerInterval;
        }
    }
    /** @notice get incentive fee in 4 decimals scaling
     * @return fee fee
     */
    function getIncentiveFeePercent() pure returns (uint256) {
        return (INCENTIVE_FEE_PERCENT * 1e4) / INCENTIVE_FEE_PERCENT_BASE;
    }
    /** @notice get batch mint cost
     * @param mintPower mint power (1 - 100)
     * @param count number of mints
     * @return mintCost total mint cost
     */
    function getBatchMintCost(
        uint256 mintPower,
        uint256 count,
        uint256 mintCost
    ) pure returns (uint256) {
        return (mintCost * mintPower * count) / MAX_MINT_POWER_CAP;
    }
    //MintInfo
    /** @notice the formula to calculate mint reward at create new mint
     * @param mintPower mint power 1 - 100
     * @param numOfDays mint length 1 - 280
     * @param mintableTitan current contract day mintable titan
     * @param EAABonus current contract day EAA Bonus
     * @param burnAmpBonus user burn amplifier bonus from getUserBurnAmplifierBonus(user)
     * @return reward base titan amount
     */
    function calculateMintReward(
        uint256 mintPower,
        uint256 numOfDays,
        uint256 mintableTitan,
        uint256 EAABonus,
        uint256 burnAmpBonus
    ) pure returns (uint256 reward) {
        uint256 baseReward = (mintableTitan * mintPower * numOfDays);
        if (numOfDays != 1)
            baseReward -= (baseReward * MINT_DAILY_REDUCTION * (numOfDays - 1)) / PERCENT_BPS;
        reward = baseReward;
        if (EAABonus != 0) {
            //EAA Bonus has 1e6 scaling, so here divide by 1e6
            reward += ((baseReward * EAABonus) / 100 / SCALING_FACTOR_1e6);
        }
        if (burnAmpBonus != 0) {
            //burnAmpBonus has 1e18 scaling
            reward += (baseReward * burnAmpBonus) / 100 / SCALING_FACTOR_1e18;
        }
        reward /= MAX_MINT_POWER_CAP;
    }
    /** @notice the formula to calculate bonus reward
     * heavily influenced by the difference between current global mint power and user mint's global mint power
     * @param mintPowerBonus mint power bonus from mintinfo
     * @param mintPower mint power 1 - 100 from mintinfo
     * @param gMintPower global mint power from mintinfo
     * @param globalMintPower current global mint power
     * @return bonus bonus amount in titan
     */
    function calculateMintPowerBonus(
        uint256 mintPowerBonus,
        uint256 mintPower,
        uint256 gMintPower,
        uint256 globalMintPower
    ) pure returns (uint256 bonus) {
        if (globalMintPower <= gMintPower) return 0;
        bonus = (((mintPowerBonus * mintPower * (globalMintPower - gMintPower)) * SCALING_FACTOR_1e18) /
            MAX_MINT_POWER_CAP);
    }
    /** @notice Return max mint length
     * @return maxMintLength max mint length
     */
    function getMaxMintDays() pure returns (uint256) {
        return MAX_MINT_LENGTH;
    }
    /** @notice Return max mints per wallet
     * @return maxMintPerWallet max mints per wallet
     */
    function getMaxMintsPerWallet() pure returns (uint256) {
        return MAX_MINT_PER_WALLET;
    }
    /**
     * @dev Return penalty percentage based on number of days late after the grace period of 7 days
     * @param secsLate seconds late (block timestamp - maturity timestamp)
     * @return penalty penalty in percentage
     */
    function calculateClaimMintPenalty(uint256 secsLate) pure returns (uint256 penalty) {
        if (secsLate <= CLAIM_MINT_GRACE_PERIOD * SECONDS_IN_DAY) return 0;
        if (secsLate <= (CLAIM_MINT_GRACE_PERIOD + 1) * SECONDS_IN_DAY) return 1;
        if (secsLate <= (CLAIM_MINT_GRACE_PERIOD + 2) * SECONDS_IN_DAY) return 3;
        if (secsLate <= (CLAIM_MINT_GRACE_PERIOD + 3) * SECONDS_IN_DAY) return 8;
        if (secsLate <= (CLAIM_MINT_GRACE_PERIOD + 4) * SECONDS_IN_DAY) return 17;
        if (secsLate <= (CLAIM_MINT_GRACE_PERIOD + 5) * SECONDS_IN_DAY) return 35;
        if (secsLate <= (CLAIM_MINT_GRACE_PERIOD + 6) * SECONDS_IN_DAY) return 72;
        return 99;
    }
    //StakeInfo
    error TitanX_AtLeastHalfMaturity();
    /** @notice get max stake length
     * @return maxStakeLength max stake length
     */
    function getMaxStakeLength() pure returns (uint256) {
        return MAX_STAKE_LENGTH;
    }
    /** @notice calculate shares and shares bonus
     * @param amount titan amount
     * @param noOfDays stake length
     * @param shareRate current contract share rate
     * @return shares calculated shares in 18 decimals
     */
    function calculateShares(
        uint256 amount,
        uint256 noOfDays,
        uint256 shareRate
    ) pure returns (uint256) {
        uint256 shares = amount;
        shares += (shares * calculateShareBonus(amount, noOfDays)) / SCALING_FACTOR_1e11;
        shares /= (shareRate / SCALING_FACTOR_1e18);
        return shares;
    }
    /** @notice calculate share bonus
     * @param amount titan amount
     * @param noOfDays stake length
     * @return shareBonus calculated shares bonus in 11 decimals
     */
    function calculateShareBonus(uint256 amount, uint256 noOfDays) pure returns (uint256 shareBonus) {
        uint256 cappedExtraDays = noOfDays <= LPB_MAX_DAYS ? noOfDays : LPB_MAX_DAYS;
        uint256 cappedStakedTitan = amount <= BPB_MAX_TITAN ? amount : BPB_MAX_TITAN;
        shareBonus =
            ((cappedExtraDays * SCALING_FACTOR_1e11) / LPB_PER_PERCENT) +
            ((cappedStakedTitan * SCALING_FACTOR_1e11) / BPB_PER_PERCENT);
        return shareBonus;
    }
    /** @notice calculate end stake penalty
     * @param stakeStartTs start stake timestamp
     * @param maturityTs  maturity timestamp
     * @param currentBlockTs current block timestamp
     * @param action end stake or burn stake
     * @return penalty penalty in percentage
     */
    function calculateEndStakePenalty(
        uint256 stakeStartTs,
        uint256 maturityTs,
        uint256 currentBlockTs,
        StakeAction action
    ) view returns (uint256) {
        //Matured, then calculate and return penalty
        if (currentBlockTs > maturityTs) {
            uint256 lateSec = currentBlockTs - maturityTs;
            uint256 gracePeriodSec = END_STAKE_GRACE_PERIOD * SECONDS_IN_DAY;
            if (lateSec <= gracePeriodSec) return 0;
            return max((min((lateSec - gracePeriodSec), 1) / SECONDS_IN_DAY) + 1, 99);
        }
        //burn stake is excluded from penalty
        //if not matured and action is burn stake then return 0
        if (action == StakeAction.BURN) return 0;
        //Emergency End Stake
        //Not allow to EES below 50% maturity
        if (block.timestamp < stakeStartTs + (maturityTs - stakeStartTs) / 2)
            revert TitanX_AtLeastHalfMaturity();
        //50% penalty for EES before maturity timestamp
        return 50;
    }
    //a - input to check against b
    //b - minimum number
    function min(uint256 a, uint256 b) pure returns (uint256) {
        if (a > b) return a;
        return b;
    }
    //a - input to check against b
    //b - maximum number
    function max(uint256 a, uint256 b) pure returns (uint256) {
        if (a > b) return b;
        return a;
    }
    // SPDX-License-Identifier: UNLICENSED
    pragma solidity ^0.8.10;
    interface ITITANX {
        function balanceOf(address account) external returns (uint256);
        function getBalance() external;
        function mintLPTokens() external;
        function burnLPTokens() external;
    }
    // SPDX-License-Identifier: UNLICENSED
    pragma solidity ^0.8.10;
    interface ITitanOnBurn {
        function onBurn(address user, uint256 amount) external;
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)
    pragma solidity ^0.8.0;
    import "../utils/introspection/IERC165.sol";
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/ERC20.sol)
    pragma solidity ^0.8.0;
    import "./IERC20.sol";
    import "./extensions/IERC20Metadata.sol";
    import "../../utils/Context.sol";
    /**
     * @dev Implementation of the {IERC20} interface.
     *
     * This implementation is agnostic to the way tokens are created. This means
     * that a supply mechanism has to be added in a derived contract using {_mint}.
     * For a generic mechanism see {ERC20PresetMinterPauser}.
     *
     * TIP: For a detailed writeup see our guide
     * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
     * to implement supply mechanisms].
     *
     * We have followed general OpenZeppelin Contracts guidelines: functions revert
     * instead returning `false` on failure. This behavior is nonetheless
     * conventional and does not conflict with the expectations of ERC20
     * applications.
     *
     * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
     * This allows applications to reconstruct the allowance for all accounts just
     * by listening to said events. Other implementations of the EIP may not emit
     * these events, as it isn't required by the specification.
     *
     * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
     * functions have been added to mitigate the well-known issues around setting
     * allowances. See {IERC20-approve}.
     */
    contract ERC20 is Context, IERC20, IERC20Metadata {
        mapping(address => uint256) private _balances;
        mapping(address => mapping(address => uint256)) private _allowances;
        uint256 private _totalSupply;
        string private _name;
        string private _symbol;
        /**
         * @dev Sets the values for {name} and {symbol}.
         *
         * The default value of {decimals} is 18. To select a different value for
         * {decimals} you should overload it.
         *
         * All two of these values are immutable: they can only be set once during
         * construction.
         */
        constructor(string memory name_, string memory symbol_) {
            _name = name_;
            _symbol = symbol_;
        }
        /**
         * @dev Returns the name of the token.
         */
        function name() public view virtual override returns (string memory) {
            return _name;
        }
        /**
         * @dev Returns the symbol of the token, usually a shorter version of the
         * name.
         */
        function symbol() public view virtual override returns (string memory) {
            return _symbol;
        }
        /**
         * @dev Returns the number of decimals used to get its user representation.
         * For example, if `decimals` equals `2`, a balance of `505` tokens should
         * be displayed to a user as `5.05` (`505 / 10 ** 2`).
         *
         * Tokens usually opt for a value of 18, imitating the relationship between
         * Ether and Wei. This is the value {ERC20} uses, unless this function is
         * overridden;
         *
         * NOTE: This information is only used for _display_ purposes: it in
         * no way affects any of the arithmetic of the contract, including
         * {IERC20-balanceOf} and {IERC20-transfer}.
         */
        function decimals() public view virtual override returns (uint8) {
            return 18;
        }
        /**
         * @dev See {IERC20-totalSupply}.
         */
        function totalSupply() public view virtual override returns (uint256) {
            return _totalSupply;
        }
        /**
         * @dev See {IERC20-balanceOf}.
         */
        function balanceOf(address account) public view virtual override returns (uint256) {
            return _balances[account];
        }
        /**
         * @dev See {IERC20-transfer}.
         *
         * Requirements:
         *
         * - `to` cannot be the zero address.
         * - the caller must have a balance of at least `amount`.
         */
        function transfer(address to, uint256 amount) public virtual override returns (bool) {
            address owner = _msgSender();
            _transfer(owner, to, amount);
            return true;
        }
        /**
         * @dev See {IERC20-allowance}.
         */
        function allowance(
            address owner,
            address spender
        ) public view virtual override returns (uint256) {
            return _allowances[owner][spender];
        }
        /**
         * @dev See {IERC20-approve}.
         *
         * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
         * `transferFrom`. This is semantically equivalent to an infinite approval.
         *
         * Requirements:
         *
         * - `spender` cannot be the zero address.
         */
        function approve(address spender, uint256 amount) public virtual override returns (bool) {
            address owner = _msgSender();
            _approve(owner, spender, amount);
            return true;
        }
        /**
         * @dev See {IERC20-transferFrom}.
         *
         * Emits an {Approval} event indicating the updated allowance. This is not
         * required by the EIP. See the note at the beginning of {ERC20}.
         *
         * NOTE: Does not update the allowance if the current allowance
         * is the maximum `uint256`.
         *
         * Requirements:
         *
         * - `from` and `to` cannot be the zero address.
         * - `from` must have a balance of at least `amount`.
         * - the caller must have allowance for ``from``'s tokens of at least
         * `amount`.
         */
        function transferFrom(
            address from,
            address to,
            uint256 amount
        ) public virtual override returns (bool) {
            address spender = _msgSender();
            _spendAllowance(from, spender, amount);
            _transfer(from, to, amount);
            return true;
        }
        /**
         * @dev Moves `amount` of tokens from `from` to `to`.
         *
         * This internal function is equivalent to {transfer}, and can be used to
         * e.g. implement automatic token fees, slashing mechanisms, etc.
         *
         * Emits a {Transfer} event.
         *
         * Requirements:
         *
         * - `from` cannot be the zero address.
         * - `to` cannot be the zero address.
         * - `from` must have a balance of at least `amount`.
         */
        function _transfer(address from, address to, uint256 amount) internal virtual {
            require(from != address(0), "ERC20: transfer from the zero address");
            require(to != address(0), "ERC20: transfer to the zero address");
            _beforeTokenTransfer(from, to, amount);
            uint256 fromBalance = _balances[from];
            require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
            unchecked {
                _balances[from] = fromBalance - amount;
                // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
                // decrementing then incrementing.
                _balances[to] += amount;
            }
            emit Transfer(from, to, amount);
            _afterTokenTransfer(from, to, amount);
        }
        /** @dev Creates `amount` tokens and assigns them to `account`, increasing
         * the total supply.
         *
         * Emits a {Transfer} event with `from` set to the zero address.
         *
         * Requirements:
         *
         * - `account` cannot be the zero address.
         */
        function _mint(address account, uint256 amount) internal virtual {
            require(account != address(0), "ERC20: mint to the zero address");
            _beforeTokenTransfer(address(0), account, amount);
            _totalSupply += amount;
            unchecked {
                // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
                _balances[account] += amount;
            }
            emit Transfer(address(0), account, amount);
            _afterTokenTransfer(address(0), account, amount);
        }
        /**
         * @dev Destroys `amount` tokens from `account`, reducing the
         * total supply.
         *
         * Emits a {Transfer} event with `to` set to the zero address.
         *
         * Requirements:
         *
         * - `account` cannot be the zero address.
         * - `account` must have at least `amount` tokens.
         */
        function _burn(address account, uint256 amount) internal virtual {
            require(account != address(0), "ERC20: burn from the zero address");
            _beforeTokenTransfer(account, address(0), amount);
            uint256 accountBalance = _balances[account];
            require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
            unchecked {
                _balances[account] = accountBalance - amount;
                // Overflow not possible: amount <= accountBalance <= totalSupply.
                _totalSupply -= amount;
            }
            emit Transfer(account, address(0), amount);
            _afterTokenTransfer(account, address(0), amount);
        }
        /**
         * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
         *
         * This internal function is equivalent to `approve`, and can be used to
         * e.g. set automatic allowances for certain subsystems, etc.
         *
         * Emits an {Approval} event.
         *
         * Requirements:
         *
         * - `owner` cannot be the zero address.
         * - `spender` cannot be the zero address.
         */
        function _approve(address owner, address spender, uint256 amount) internal virtual {
            require(owner != address(0), "ERC20: approve from the zero address");
            require(spender != address(0), "ERC20: approve to the zero address");
            _allowances[owner][spender] = amount;
            emit Approval(owner, spender, amount);
        }
        /**
         * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
         *
         * Does not update the allowance amount in case of infinite allowance.
         * Revert if not enough allowance is available.
         *
         * Might emit an {Approval} event.
         */
        function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
            uint256 currentAllowance = allowance(owner, spender);
            if (currentAllowance != type(uint256).max) {
                require(currentAllowance >= amount, "ERC20: insufficient allowance");
                unchecked {
                    _approve(owner, spender, currentAllowance - amount);
                }
            }
        }
        /**
         * @dev Hook that is called before any transfer of tokens. This includes
         * minting and burning.
         *
         * Calling conditions:
         *
         * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
         * will be transferred to `to`.
         * - when `from` is zero, `amount` tokens will be minted for `to`.
         * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
         * - `from` and `to` are never both zero.
         *
         * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
         */
        function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
        /**
         * @dev Hook that is called after any transfer of tokens. This includes
         * minting and burning.
         *
         * Calling conditions:
         *
         * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
         * has been transferred to `to`.
         * - when `from` is zero, `amount` tokens have been minted for `to`.
         * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
         * - `from` and `to` are never both zero.
         *
         * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
         */
        function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)
    pragma solidity ^0.8.0;
    /**
     * @dev Contract module that helps prevent reentrant calls to a function.
     *
     * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
     * available, which can be applied to functions to make sure there are no nested
     * (reentrant) calls to them.
     *
     * Note that because there is a single `nonReentrant` guard, functions marked as
     * `nonReentrant` may not call one another. This can be worked around by making
     * those functions `private`, and then adding `external` `nonReentrant` entry
     * points to them.
     *
     * TIP: If you would like to learn more about reentrancy and alternative ways
     * to protect against it, check out our blog post
     * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
     */
    abstract contract ReentrancyGuard {
        // Booleans are more expensive than uint256 or any type that takes up a full
        // word because each write operation emits an extra SLOAD to first read the
        // slot's contents, replace the bits taken up by the boolean, and then write
        // back. This is the compiler's defense against contract upgrades and
        // pointer aliasing, and it cannot be disabled.
        // The values being non-zero value makes deployment a bit more expensive,
        // but in exchange the refund on every call to nonReentrant will be lower in
        // amount. Since refunds are capped to a percentage of the total
        // transaction's gas, it is best to keep them low in cases like this one, to
        // increase the likelihood of the full refund coming into effect.
        uint256 private constant _NOT_ENTERED = 1;
        uint256 private constant _ENTERED = 2;
        uint256 private _status;
        constructor() {
            _status = _NOT_ENTERED;
        }
        /**
         * @dev Prevents a contract from calling itself, directly or indirectly.
         * Calling a `nonReentrant` function from another `nonReentrant`
         * function is not supported. It is possible to prevent this from happening
         * by making the `nonReentrant` function external, and making it call a
         * `private` function that does the actual work.
         */
        modifier nonReentrant() {
            _nonReentrantBefore();
            _;
            _nonReentrantAfter();
        }
        function _nonReentrantBefore() private {
            // On the first call to nonReentrant, _status will be _NOT_ENTERED
            require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
            // Any calls to nonReentrant after this point will fail
            _status = _ENTERED;
        }
        function _nonReentrantAfter() private {
            // By storing the original value once again, a refund is triggered (see
            // https://eips.ethereum.org/EIPS/eip-2200)
            _status = _NOT_ENTERED;
        }
        /**
         * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
         * `nonReentrant` function in the call stack.
         */
        function _reentrancyGuardEntered() internal view returns (bool) {
            return _status == _ENTERED;
        }
    }
    // SPDX-License-Identifier: UNLICENSED
    pragma solidity ^0.8.10;
    enum MintAction {
        CLAIM,
        BURN
    }
    enum MintStatus {
        ACTIVE,
        CLAIMED,
        BURNED
    }
    enum StakeAction {
        START,
        END,
        BURN,
        END_OWN,
        END_OTHER
    }
    enum StakeStatus {
        ACTIVE,
        ENDED,
        BURNED
    }
    enum PayoutTriggered {
        NO,
        YES
    }
    enum InitialLPMinted {
        NO,
        YES
    }
    enum PayoutClaim {
        SHARES,
        BURN
    }
    enum BurnSource {
        LIQUID,
        MINT,
        STAKE
    }
    enum BurnPoolEnabled {
        FALSE,
        TRUE
    }
    // SPDX-License-Identifier: UNLICENSED
    pragma solidity ^0.8.10;
    // ===================== common ==========================================
    uint256 constant SECONDS_IN_DAY = 86400;
    uint256 constant SCALING_FACTOR_1e3 = 1e3;
    uint256 constant SCALING_FACTOR_1e6 = 1e6;
    uint256 constant SCALING_FACTOR_1e7 = 1e7;
    uint256 constant SCALING_FACTOR_1e11 = 1e11;
    uint256 constant SCALING_FACTOR_1e18 = 1e18;
    // ===================== TITANX ==========================================
    uint256 constant PERCENT_TO_BUY_AND_BURN = 62_00;
    uint256 constant PERCENT_TO_CYCLE_PAYOUTS = 28_00;
    uint256 constant PERCENT_TO_BURN_PAYOUTS = 7_00;
    uint256 constant PERCENT_TO_GENESIS = 3_00;
    uint256 constant INCENTIVE_FEE_PERCENT = 3300;
    uint256 constant INCENTIVE_FEE_PERCENT_BASE = 1_000_000;
    uint256 constant INITAL_LP_TOKENS = 100_000_000_000 ether;
    // ===================== globalInfo ==========================================
    //Titan Supply Variables
    uint256 constant START_MAX_MINTABLE_PER_DAY = 8_000_000 ether;
    uint256 constant CAPPED_MIN_DAILY_TITAN_MINTABLE = 800 ether;
    uint256 constant DAILY_SUPPLY_MINTABLE_REDUCTION = 99_65;
    //EAA Variables
    uint256 constant EAA_START = 10 * SCALING_FACTOR_1e6;
    uint256 constant EAA_BONUSE_FIXED_REDUCTION_PER_DAY = 28_571;
    uint256 constant EAA_END = 0;
    uint256 constant MAX_BONUS_DAY = 350;
    //Mint Cost Variables
    uint256 constant START_MAX_MINT_COST = 0.2 ether;
    uint256 constant CAPPED_MAX_MINT_COST = 1 ether;
    uint256 constant DAILY_MINT_COST_INCREASE_STEP = 100_08;
    //mintPower Bonus Variables
    uint256 constant START_MINTPOWER_INCREASE_BONUS = 35 * SCALING_FACTOR_1e7; //starts at 35 with 1e7 scaling factor
    uint256 constant CAPPED_MIN_MINTPOWER_BONUS = 35 * SCALING_FACTOR_1e3; //capped min of 0.0035 * 1e7 = 35 * 1e3
    uint256 constant DAILY_MINTPOWER_INCREASE_BONUS_REDUCTION = 99_65;
    //Share Rate Variables
    uint256 constant START_SHARE_RATE = 800 ether;
    uint256 constant DAILY_SHARE_RATE_INCREASE_STEP = 100_03;
    uint256 constant CAPPED_MAX_RATE = 2_800 ether;
    //Cycle Variables
    uint256 constant DAY8 = 8;
    uint256 constant DAY28 = 28;
    uint256 constant DAY90 = 90;
    uint256 constant DAY369 = 369;
    uint256 constant DAY888 = 888;
    uint256 constant CYCLE_8_PERCENT = 28_00;
    uint256 constant CYCLE_28_PERCENT = 28_00;
    uint256 constant CYCLE_90_PERCENT = 18_00;
    uint256 constant CYCLE_369_PERCENT = 18_00;
    uint256 constant CYCLE_888_PERCENT = 8_00;
    uint256 constant PERCENT_BPS = 100_00;
    // ===================== mintInfo ==========================================
    uint256 constant MAX_MINT_POWER_CAP = 100;
    uint256 constant MAX_MINT_LENGTH = 280;
    uint256 constant CLAIM_MINT_GRACE_PERIOD = 7;
    uint256 constant MAX_BATCH_MINT_COUNT = 100;
    uint256 constant MAX_MINT_PER_WALLET = 1000;
    uint256 constant MAX_BURN_AMP_BASE = 80 * 1e9 * 1 ether;
    uint256 constant MAX_BURN_AMP_PERCENT = 8 ether;
    uint256 constant MINT_DAILY_REDUCTION = 11;
    // ===================== stakeInfo ==========================================
    uint256 constant MAX_STAKE_PER_WALLET = 1000;
    uint256 constant MIN_STAKE_LENGTH = 28;
    uint256 constant MAX_STAKE_LENGTH = 3500;
    uint256 constant END_STAKE_GRACE_PERIOD = 7;
    /* Stake Longer Pays Better bonus */
    uint256 constant LPB_MAX_DAYS = 2888;
    uint256 constant LPB_PER_PERCENT = 825;
    /* Stake Bigger Pays Better bonus */
    uint256 constant BPB_MAX_TITAN = 100 * 1e9 * SCALING_FACTOR_1e18; //100 billion
    uint256 constant BPB_PER_PERCENT = 1_250_000_000_000 * SCALING_FACTOR_1e18;
    // ===================== burnInfo ==========================================
    uint256 constant MAX_BURN_REWARD_PERCENT = 8;
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
    pragma solidity ^0.8.0;
    /**
     * @dev Provides information about the current execution context, including the
     * sender of the transaction and its data. While these are generally available
     * via msg.sender and msg.data, they should not be accessed in such a direct
     * manner, since when dealing with meta-transactions the account sending and
     * paying for execution may not be the actual sender (as far as an application
     * is concerned).
     *
     * This contract is only required for intermediate, library-like contracts.
     */
    abstract contract Context {
        function _msgSender() internal view virtual returns (address) {
            return msg.sender;
        }
        function _msgData() internal view virtual returns (bytes calldata) {
            return msg.data;
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
    pragma solidity ^0.8.0;
    import "../IERC20.sol";
    /**
     * @dev Interface for the optional metadata functions from the ERC20 standard.
     *
     * _Available since v4.1._
     */
    interface IERC20Metadata is IERC20 {
        /**
         * @dev Returns the name of the token.
         */
        function name() external view returns (string memory);
        /**
         * @dev Returns the symbol of the token.
         */
        function symbol() external view returns (string memory);
        /**
         * @dev Returns the decimals places of the token.
         */
        function decimals() external view returns (uint8);
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v4.6.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);
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
    pragma solidity ^0.8.0;
    /**
     * @dev Interface of the ERC165 standard, as defined in the
     * https://eips.ethereum.org/EIPS/eip-165[EIP].
     *
     * Implementers can declare support of contract interfaces, which can then be
     * queried by others ({ERC165Checker}).
     *
     * For an implementation, see {ERC165}.
     */
    interface IERC165 {
        /**
         * @dev Returns true if this contract implements the interface defined by
         * `interfaceId`. See the corresponding
         * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
         * to learn more about how these ids are created.
         *
         * This function call must use less than 30 000 gas.
         */
        function supportsInterface(bytes4 interfaceId) external view returns (bool);
    }
    

    File 3 of 4: Element280
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
    pragma solidity ^0.8.20;
    import {Context} from "../utils/Context.sol";
    /**
     * @dev Contract module which provides a basic access control mechanism, where
     * there is an account (an owner) that can be granted exclusive access to
     * specific functions.
     *
     * The initial owner is set to the address provided by the deployer. This can
     * later be changed with {transferOwnership}.
     *
     * This module is used through inheritance. It will make available the modifier
     * `onlyOwner`, which can be applied to your functions to restrict their use to
     * the owner.
     */
    abstract contract Ownable is Context {
        address private _owner;
        /**
         * @dev The caller account is not authorized to perform an operation.
         */
        error OwnableUnauthorizedAccount(address account);
        /**
         * @dev The owner is not a valid owner account. (eg. `address(0)`)
         */
        error OwnableInvalidOwner(address owner);
        event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
        /**
         * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
         */
        constructor(address initialOwner) {
            if (initialOwner == address(0)) {
                revert OwnableInvalidOwner(address(0));
            }
            _transferOwnership(initialOwner);
        }
        /**
         * @dev Throws if called by any account other than the owner.
         */
        modifier onlyOwner() {
            _checkOwner();
            _;
        }
        /**
         * @dev Returns the address of the current owner.
         */
        function owner() public view virtual returns (address) {
            return _owner;
        }
        /**
         * @dev Throws if the sender is not the owner.
         */
        function _checkOwner() internal view virtual {
            if (owner() != _msgSender()) {
                revert OwnableUnauthorizedAccount(_msgSender());
            }
        }
        /**
         * @dev Leaves the contract without owner. It will not be possible to call
         * `onlyOwner` functions. Can only be called by the current owner.
         *
         * NOTE: Renouncing ownership will leave the contract without an owner,
         * thereby disabling any functionality that is only available to the owner.
         */
        function renounceOwnership() public virtual onlyOwner {
            _transferOwnership(address(0));
        }
        /**
         * @dev Transfers ownership of the contract to a new account (`newOwner`).
         * Can only be called by the current owner.
         */
        function transferOwnership(address newOwner) public virtual onlyOwner {
            if (newOwner == address(0)) {
                revert OwnableInvalidOwner(address(0));
            }
            _transferOwnership(newOwner);
        }
        /**
         * @dev Transfers ownership of the contract to a new account (`newOwner`).
         * Internal function without access restriction.
         */
        function _transferOwnership(address newOwner) internal virtual {
            address oldOwner = _owner;
            _owner = newOwner;
            emit OwnershipTransferred(oldOwner, newOwner);
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol)
    pragma solidity ^0.8.20;
    import {Ownable} from "./Ownable.sol";
    /**
     * @dev Contract module which provides access control mechanism, where
     * there is an account (an owner) that can be granted exclusive access to
     * specific functions.
     *
     * The initial owner is specified at deployment time in the constructor for `Ownable`. This
     * can later be changed with {transferOwnership} and {acceptOwnership}.
     *
     * This module is used through inheritance. It will make available all functions
     * from parent (Ownable).
     */
    abstract contract Ownable2Step is Ownable {
        address private _pendingOwner;
        event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
        /**
         * @dev Returns the address of the pending owner.
         */
        function pendingOwner() public view virtual returns (address) {
            return _pendingOwner;
        }
        /**
         * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
         * Can only be called by the current owner.
         */
        function transferOwnership(address newOwner) public virtual override onlyOwner {
            _pendingOwner = newOwner;
            emit OwnershipTransferStarted(owner(), newOwner);
        }
        /**
         * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
         * Internal function without access restriction.
         */
        function _transferOwnership(address newOwner) internal virtual override {
            delete _pendingOwner;
            super._transferOwnership(newOwner);
        }
        /**
         * @dev The new owner accepts the ownership transfer.
         */
        function acceptOwnership() public virtual {
            address sender = _msgSender();
            if (pendingOwner() != sender) {
                revert OwnableUnauthorizedAccount(sender);
            }
            _transferOwnership(sender);
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
    pragma solidity ^0.8.20;
    /**
     * @dev Standard ERC20 Errors
     * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
     */
    interface IERC20Errors {
        /**
         * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
         * @param sender Address whose tokens are being transferred.
         * @param balance Current balance for the interacting account.
         * @param needed Minimum amount required to perform a transfer.
         */
        error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
        /**
         * @dev Indicates a failure with the token `sender`. Used in transfers.
         * @param sender Address whose tokens are being transferred.
         */
        error ERC20InvalidSender(address sender);
        /**
         * @dev Indicates a failure with the token `receiver`. Used in transfers.
         * @param receiver Address to which tokens are being transferred.
         */
        error ERC20InvalidReceiver(address receiver);
        /**
         * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
         * @param spender Address that may be allowed to operate on tokens without being their owner.
         * @param allowance Amount of tokens a `spender` is allowed to operate with.
         * @param needed Minimum amount required to perform a transfer.
         */
        error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
        /**
         * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
         * @param approver Address initiating an approval operation.
         */
        error ERC20InvalidApprover(address approver);
        /**
         * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
         * @param spender Address that may be allowed to operate on tokens without being their owner.
         */
        error ERC20InvalidSpender(address spender);
    }
    /**
     * @dev Standard ERC721 Errors
     * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
     */
    interface IERC721Errors {
        /**
         * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
         * Used in balance queries.
         * @param owner Address of the current owner of a token.
         */
        error ERC721InvalidOwner(address owner);
        /**
         * @dev Indicates a `tokenId` whose `owner` is the zero address.
         * @param tokenId Identifier number of a token.
         */
        error ERC721NonexistentToken(uint256 tokenId);
        /**
         * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
         * @param sender Address whose tokens are being transferred.
         * @param tokenId Identifier number of a token.
         * @param owner Address of the current owner of a token.
         */
        error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
        /**
         * @dev Indicates a failure with the token `sender`. Used in transfers.
         * @param sender Address whose tokens are being transferred.
         */
        error ERC721InvalidSender(address sender);
        /**
         * @dev Indicates a failure with the token `receiver`. Used in transfers.
         * @param receiver Address to which tokens are being transferred.
         */
        error ERC721InvalidReceiver(address receiver);
        /**
         * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
         * @param operator Address that may be allowed to operate on tokens without being their owner.
         * @param tokenId Identifier number of a token.
         */
        error ERC721InsufficientApproval(address operator, uint256 tokenId);
        /**
         * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
         * @param approver Address initiating an approval operation.
         */
        error ERC721InvalidApprover(address approver);
        /**
         * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
         * @param operator Address that may be allowed to operate on tokens without being their owner.
         */
        error ERC721InvalidOperator(address operator);
    }
    /**
     * @dev Standard ERC1155 Errors
     * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
     */
    interface IERC1155Errors {
        /**
         * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
         * @param sender Address whose tokens are being transferred.
         * @param balance Current balance for the interacting account.
         * @param needed Minimum amount required to perform a transfer.
         * @param tokenId Identifier number of a token.
         */
        error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
        /**
         * @dev Indicates a failure with the token `sender`. Used in transfers.
         * @param sender Address whose tokens are being transferred.
         */
        error ERC1155InvalidSender(address sender);
        /**
         * @dev Indicates a failure with the token `receiver`. Used in transfers.
         * @param receiver Address to which tokens are being transferred.
         */
        error ERC1155InvalidReceiver(address receiver);
        /**
         * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
         * @param operator Address that may be allowed to operate on tokens without being their owner.
         * @param owner Address of the current owner of a token.
         */
        error ERC1155MissingApprovalForAll(address operator, address owner);
        /**
         * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
         * @param approver Address initiating an approval operation.
         */
        error ERC1155InvalidApprover(address approver);
        /**
         * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
         * @param operator Address that may be allowed to operate on tokens without being their owner.
         */
        error ERC1155InvalidOperator(address operator);
        /**
         * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
         * Used in batch transfers.
         * @param idsLength Length of the array of token identifiers
         * @param valuesLength Length of the array of token amounts
         */
        error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)
    pragma solidity ^0.8.20;
    import {IERC165} from "../utils/introspection/IERC165.sol";
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
    pragma solidity ^0.8.20;
    import {IERC20} from "../token/ERC20/IERC20.sol";
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)
    pragma solidity ^0.8.20;
    import {IERC20} from "./IERC20.sol";
    import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
    import {Context} from "../../utils/Context.sol";
    import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
    /**
     * @dev Implementation of the {IERC20} interface.
     *
     * This implementation is agnostic to the way tokens are created. This means
     * that a supply mechanism has to be added in a derived contract using {_mint}.
     *
     * TIP: For a detailed writeup see our guide
     * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
     * to implement supply mechanisms].
     *
     * The default value of {decimals} is 18. To change this, you should override
     * this function so it returns a different value.
     *
     * We have followed general OpenZeppelin Contracts guidelines: functions revert
     * instead returning `false` on failure. This behavior is nonetheless
     * conventional and does not conflict with the expectations of ERC20
     * applications.
     *
     * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
     * This allows applications to reconstruct the allowance for all accounts just
     * by listening to said events. Other implementations of the EIP may not emit
     * these events, as it isn't required by the specification.
     */
    abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
        mapping(address account => uint256) private _balances;
        mapping(address account => mapping(address spender => uint256)) private _allowances;
        uint256 private _totalSupply;
        string private _name;
        string private _symbol;
        /**
         * @dev Sets the values for {name} and {symbol}.
         *
         * All two of these values are immutable: they can only be set once during
         * construction.
         */
        constructor(string memory name_, string memory symbol_) {
            _name = name_;
            _symbol = symbol_;
        }
        /**
         * @dev Returns the name of the token.
         */
        function name() public view virtual returns (string memory) {
            return _name;
        }
        /**
         * @dev Returns the symbol of the token, usually a shorter version of the
         * name.
         */
        function symbol() public view virtual returns (string memory) {
            return _symbol;
        }
        /**
         * @dev Returns the number of decimals used to get its user representation.
         * For example, if `decimals` equals `2`, a balance of `505` tokens should
         * be displayed to a user as `5.05` (`505 / 10 ** 2`).
         *
         * Tokens usually opt for a value of 18, imitating the relationship between
         * Ether and Wei. This is the default value returned by this function, unless
         * it's overridden.
         *
         * NOTE: This information is only used for _display_ purposes: it in
         * no way affects any of the arithmetic of the contract, including
         * {IERC20-balanceOf} and {IERC20-transfer}.
         */
        function decimals() public view virtual returns (uint8) {
            return 18;
        }
        /**
         * @dev See {IERC20-totalSupply}.
         */
        function totalSupply() public view virtual returns (uint256) {
            return _totalSupply;
        }
        /**
         * @dev See {IERC20-balanceOf}.
         */
        function balanceOf(address account) public view virtual returns (uint256) {
            return _balances[account];
        }
        /**
         * @dev See {IERC20-transfer}.
         *
         * Requirements:
         *
         * - `to` cannot be the zero address.
         * - the caller must have a balance of at least `value`.
         */
        function transfer(address to, uint256 value) public virtual returns (bool) {
            address owner = _msgSender();
            _transfer(owner, to, value);
            return true;
        }
        /**
         * @dev See {IERC20-allowance}.
         */
        function allowance(address owner, address spender) public view virtual returns (uint256) {
            return _allowances[owner][spender];
        }
        /**
         * @dev See {IERC20-approve}.
         *
         * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
         * `transferFrom`. This is semantically equivalent to an infinite approval.
         *
         * Requirements:
         *
         * - `spender` cannot be the zero address.
         */
        function approve(address spender, uint256 value) public virtual returns (bool) {
            address owner = _msgSender();
            _approve(owner, spender, value);
            return true;
        }
        /**
         * @dev See {IERC20-transferFrom}.
         *
         * Emits an {Approval} event indicating the updated allowance. This is not
         * required by the EIP. See the note at the beginning of {ERC20}.
         *
         * NOTE: Does not update the allowance if the current allowance
         * is the maximum `uint256`.
         *
         * Requirements:
         *
         * - `from` and `to` cannot be the zero address.
         * - `from` must have a balance of at least `value`.
         * - the caller must have allowance for ``from``'s tokens of at least
         * `value`.
         */
        function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
            address spender = _msgSender();
            _spendAllowance(from, spender, value);
            _transfer(from, to, value);
            return true;
        }
        /**
         * @dev Moves a `value` amount of tokens from `from` to `to`.
         *
         * This internal function is equivalent to {transfer}, and can be used to
         * e.g. implement automatic token fees, slashing mechanisms, etc.
         *
         * Emits a {Transfer} event.
         *
         * NOTE: This function is not virtual, {_update} should be overridden instead.
         */
        function _transfer(address from, address to, uint256 value) internal {
            if (from == address(0)) {
                revert ERC20InvalidSender(address(0));
            }
            if (to == address(0)) {
                revert ERC20InvalidReceiver(address(0));
            }
            _update(from, to, value);
        }
        /**
         * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
         * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
         * this function.
         *
         * Emits a {Transfer} event.
         */
        function _update(address from, address to, uint256 value) internal virtual {
            if (from == address(0)) {
                // Overflow check required: The rest of the code assumes that totalSupply never overflows
                _totalSupply += value;
            } else {
                uint256 fromBalance = _balances[from];
                if (fromBalance < value) {
                    revert ERC20InsufficientBalance(from, fromBalance, value);
                }
                unchecked {
                    // Overflow not possible: value <= fromBalance <= totalSupply.
                    _balances[from] = fromBalance - value;
                }
            }
            if (to == address(0)) {
                unchecked {
                    // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                    _totalSupply -= value;
                }
            } else {
                unchecked {
                    // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                    _balances[to] += value;
                }
            }
            emit Transfer(from, to, value);
        }
        /**
         * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
         * Relies on the `_update` mechanism
         *
         * Emits a {Transfer} event with `from` set to the zero address.
         *
         * NOTE: This function is not virtual, {_update} should be overridden instead.
         */
        function _mint(address account, uint256 value) internal {
            if (account == address(0)) {
                revert ERC20InvalidReceiver(address(0));
            }
            _update(address(0), account, value);
        }
        /**
         * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
         * Relies on the `_update` mechanism.
         *
         * Emits a {Transfer} event with `to` set to the zero address.
         *
         * NOTE: This function is not virtual, {_update} should be overridden instead
         */
        function _burn(address account, uint256 value) internal {
            if (account == address(0)) {
                revert ERC20InvalidSender(address(0));
            }
            _update(account, address(0), value);
        }
        /**
         * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
         *
         * This internal function is equivalent to `approve`, and can be used to
         * e.g. set automatic allowances for certain subsystems, etc.
         *
         * Emits an {Approval} event.
         *
         * Requirements:
         *
         * - `owner` cannot be the zero address.
         * - `spender` cannot be the zero address.
         *
         * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
         */
        function _approve(address owner, address spender, uint256 value) internal {
            _approve(owner, spender, value, true);
        }
        /**
         * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
         *
         * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
         * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
         * `Approval` event during `transferFrom` operations.
         *
         * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
         * true using the following override:
         * ```
         * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
         *     super._approve(owner, spender, value, true);
         * }
         * ```
         *
         * Requirements are the same as {_approve}.
         */
        function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
            if (owner == address(0)) {
                revert ERC20InvalidApprover(address(0));
            }
            if (spender == address(0)) {
                revert ERC20InvalidSpender(address(0));
            }
            _allowances[owner][spender] = value;
            if (emitEvent) {
                emit Approval(owner, spender, value);
            }
        }
        /**
         * @dev Updates `owner` s allowance for `spender` based on spent `value`.
         *
         * Does not update the allowance value in case of infinite allowance.
         * Revert if not enough allowance is available.
         *
         * Does not emit an {Approval} event.
         */
        function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
            uint256 currentAllowance = allowance(owner, spender);
            if (currentAllowance != type(uint256).max) {
                if (currentAllowance < value) {
                    revert ERC20InsufficientAllowance(spender, currentAllowance, value);
                }
                unchecked {
                    _approve(owner, spender, currentAllowance - value, false);
                }
            }
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
    pragma solidity ^0.8.20;
    import {IERC20} from "../IERC20.sol";
    /**
     * @dev Interface for the optional metadata functions from the ERC20 standard.
     */
    interface IERC20Metadata is IERC20 {
        /**
         * @dev Returns the name of the token.
         */
        function name() external view returns (string memory);
        /**
         * @dev Returns the symbol of the token.
         */
        function symbol() external view returns (string memory);
        /**
         * @dev Returns the decimals places of the token.
         */
        function decimals() external view returns (uint8);
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
    pragma solidity ^0.8.20;
    /**
     * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
     * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
     *
     * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
     * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
     * need to send a transaction, and thus is not required to hold Ether at all.
     *
     * ==== Security Considerations
     *
     * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
     * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
     * considered as an intention to spend the allowance in any specific way. The second is that because permits have
     * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
     * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
     * generally recommended is:
     *
     * ```solidity
     * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
     *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
     *     doThing(..., value);
     * }
     *
     * function doThing(..., uint256 value) public {
     *     token.safeTransferFrom(msg.sender, address(this), value);
     *     ...
     * }
     * ```
     *
     * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
     * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
     * {SafeERC20-safeTransferFrom}).
     *
     * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
     * contracts should have entry points that don't rely on permit.
     */
    interface IERC20Permit {
        /**
         * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
         * given ``owner``'s signed approval.
         *
         * IMPORTANT: The same issues {IERC20-approve} has related to transaction
         * ordering also apply here.
         *
         * Emits an {Approval} event.
         *
         * Requirements:
         *
         * - `spender` cannot be the zero address.
         * - `deadline` must be a timestamp in the future.
         * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
         * over the EIP712-formatted function arguments.
         * - the signature must use ``owner``'s current nonce (see {nonces}).
         *
         * For more information on the signature format, see the
         * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
         * section].
         *
         * CAUTION: See Security Considerations above.
         */
        function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
            external;
        /**
         * @dev Returns the current nonce for `owner`. This value must be
         * included whenever a signature is generated for {permit}.
         *
         * Every successful call to {permit} increases ``owner``'s nonce by one. This
         * prevents a signature from being used multiple times.
         */
        function nonces(address owner) external view returns (uint256);
        /**
         * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
         */
        // solhint-disable-next-line func-name-mixedcase
        function DOMAIN_SEPARATOR() external view returns (bytes32);
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
    pragma solidity ^0.8.20;
    /**
     * @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 value of tokens in existence.
         */
        function totalSupply() external view returns (uint256);
        /**
         * @dev Returns the value of tokens owned by `account`.
         */
        function balanceOf(address account) external view returns (uint256);
        /**
         * @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool);
        /**
         * @dev Moves a `value` amount of tokens from `from` to `to` using the
         * allowance mechanism. `value` 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 value) external returns (bool);
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
    pragma solidity ^0.8.20;
    import {IERC20} from "../IERC20.sol";
    import {IERC20Permit} from "../extensions/IERC20Permit.sol";
    import {Address} from "../../../utils/Address.sol";
    /**
     * @title SafeERC20
     * @dev Wrappers around ERC20 operations that throw on failure (when the token
     * contract returns false). Tokens that return no value (and instead revert or
     * throw on failure) are also supported, non-reverting calls are assumed to be
     * successful.
     * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
     * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
     */
    library SafeERC20 {
        using Address for address;
        /**
         * @dev An operation with an ERC20 token failed.
         */
        error SafeERC20FailedOperation(address token);
        /**
         * @dev Indicates a failed `decreaseAllowance` request.
         */
        error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
        /**
         * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
         * non-reverting calls are assumed to be successful.
         */
        function safeTransfer(IERC20 token, address to, uint256 value) internal {
            _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
        }
        /**
         * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
         * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
         */
        function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
            _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
        }
        /**
         * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
         * non-reverting calls are assumed to be successful.
         */
        function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
            uint256 oldAllowance = token.allowance(address(this), spender);
            forceApprove(token, spender, oldAllowance + value);
        }
        /**
         * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
         * value, non-reverting calls are assumed to be successful.
         */
        function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
            unchecked {
                uint256 currentAllowance = token.allowance(address(this), spender);
                if (currentAllowance < requestedDecrease) {
                    revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
                }
                forceApprove(token, spender, currentAllowance - requestedDecrease);
            }
        }
        /**
         * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
         * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
         * to be set to zero before setting it to a non-zero value, such as USDT.
         */
        function forceApprove(IERC20 token, address spender, uint256 value) internal {
            bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
            if (!_callOptionalReturnBool(token, approvalCall)) {
                _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
                _callOptionalReturn(token, approvalCall);
            }
        }
        /**
         * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
         * on the return value: the return value is optional (but if data is returned, it must not be false).
         * @param token The token targeted by the call.
         * @param data The call data (encoded using abi.encode or one of its variants).
         */
        function _callOptionalReturn(IERC20 token, bytes memory data) private {
            // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
            // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
            // the target address contains contract code and also asserts for success in the low-level call.
            bytes memory returndata = address(token).functionCall(data);
            if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
                revert SafeERC20FailedOperation(address(token));
            }
        }
        /**
         * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
         * on the return value: the return value is optional (but if data is returned, it must not be false).
         * @param token The token targeted by the call.
         * @param data The call data (encoded using abi.encode or one of its variants).
         *
         * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
         */
        function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
            // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
            // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
            // and not revert is the subcall reverts.
            (bool success, bytes memory returndata) = address(token).call(data);
            return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
    pragma solidity ^0.8.20;
    /**
     * @dev Collection of functions related to the address type
     */
    library Address {
        /**
         * @dev The ETH balance of the account is not enough to perform the operation.
         */
        error AddressInsufficientBalance(address account);
        /**
         * @dev There's no code at `target` (it is not a contract).
         */
        error AddressEmptyCode(address target);
        /**
         * @dev A call to an address target failed. The target may have reverted.
         */
        error FailedInnerCall();
        /**
         * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
         * `recipient`, forwarding all available gas and reverting on errors.
         *
         * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
         * of certain opcodes, possibly making contracts go over the 2300 gas limit
         * imposed by `transfer`, making them unable to receive funds via
         * `transfer`. {sendValue} removes this limitation.
         *
         * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
         *
         * IMPORTANT: because control is transferred to `recipient`, care must be
         * taken to not create reentrancy vulnerabilities. Consider using
         * {ReentrancyGuard} or the
         * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
         */
        function sendValue(address payable recipient, uint256 amount) internal {
            if (address(this).balance < amount) {
                revert AddressInsufficientBalance(address(this));
            }
            (bool success,) = recipient.call{value: amount}("");
            if (!success) {
                revert FailedInnerCall();
            }
        }
        /**
         * @dev Performs a Solidity function call using a low level `call`. A
         * plain `call` is an unsafe replacement for a function call: use this
         * function instead.
         *
         * If `target` reverts with a revert reason or custom error, it is bubbled
         * up by this function (like regular Solidity function calls). However, if
         * the call reverted with no returned reason, this function reverts with a
         * {FailedInnerCall} error.
         *
         * Returns the raw returned data. To convert to the expected return value,
         * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
         *
         * Requirements:
         *
         * - `target` must be a contract.
         * - calling `target` with `data` must not revert.
         */
        function functionCall(address target, bytes memory data) internal returns (bytes memory) {
            return functionCallWithValue(target, data, 0);
        }
        /**
         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
         * but also transferring `value` wei to `target`.
         *
         * Requirements:
         *
         * - the calling contract must have an ETH balance of at least `value`.
         * - the called Solidity function must be `payable`.
         */
        function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
            if (address(this).balance < value) {
                revert AddressInsufficientBalance(address(this));
            }
            (bool success, bytes memory returndata) = target.call{value: value}(data);
            return verifyCallResultFromTarget(target, success, returndata);
        }
        /**
         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
         * but performing a static call.
         */
        function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
            (bool success, bytes memory returndata) = target.staticcall(data);
            return verifyCallResultFromTarget(target, success, returndata);
        }
        /**
         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
         * but performing a delegate call.
         */
        function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
            (bool success, bytes memory returndata) = target.delegatecall(data);
            return verifyCallResultFromTarget(target, success, returndata);
        }
        /**
         * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
         * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
         * unsuccessful call.
         */
        function verifyCallResultFromTarget(address target, bool success, bytes memory returndata)
            internal
            view
            returns (bytes memory)
        {
            if (!success) {
                _revert(returndata);
            } else {
                // only check if target is a contract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                if (returndata.length == 0 && target.code.length == 0) {
                    revert AddressEmptyCode(target);
                }
                return returndata;
            }
        }
        /**
         * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
         * revert reason or with a default {FailedInnerCall} error.
         */
        function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
            if (!success) {
                _revert(returndata);
            } else {
                return returndata;
            }
        }
        /**
         * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
         */
        function _revert(bytes memory returndata) private pure {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly
                /// @solidity memory-safe-assembly
                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert FailedInnerCall();
            }
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
    pragma solidity ^0.8.20;
    /**
     * @dev Provides information about the current execution context, including the
     * sender of the transaction and its data. While these are generally available
     * via msg.sender and msg.data, they should not be accessed in such a direct
     * manner, since when dealing with meta-transactions the account sending and
     * paying for execution may not be the actual sender (as far as an application
     * is concerned).
     *
     * This contract is only required for intermediate, library-like contracts.
     */
    abstract contract Context {
        function _msgSender() internal view virtual returns (address) {
            return msg.sender;
        }
        function _msgData() internal view virtual returns (bytes calldata) {
            return msg.data;
        }
        function _contextSuffixLength() internal view virtual returns (uint256) {
            return 0;
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
    pragma solidity ^0.8.20;
    /**
     * @dev Interface of the ERC165 standard, as defined in the
     * https://eips.ethereum.org/EIPS/eip-165[EIP].
     *
     * Implementers can declare support of contract interfaces, which can then be
     * queried by others ({ERC165Checker}).
     *
     * For an implementation, see {ERC165}.
     */
    interface IERC165 {
        /**
         * @dev Returns true if this contract implements the interface defined by
         * `interfaceId`. See the corresponding
         * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
         * to learn more about how these ids are created.
         *
         * This function call must use less than 30 000 gas.
         */
        function supportsInterface(bytes4 interfaceId) external view returns (bool);
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol)
    // This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
    pragma solidity ^0.8.20;
    /**
     * @dev Library for managing
     * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
     * types.
     *
     * Sets have the following properties:
     *
     * - Elements are added, removed, and checked for existence in constant time
     * (O(1)).
     * - Elements are enumerated in O(n). No guarantees are made on the ordering.
     *
     * ```solidity
     * contract Example {
     *     // Add the library methods
     *     using EnumerableSet for EnumerableSet.AddressSet;
     *
     *     // Declare a set state variable
     *     EnumerableSet.AddressSet private mySet;
     * }
     * ```
     *
     * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
     * and `uint256` (`UintSet`) are supported.
     *
     * [WARNING]
     * ====
     * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
     * unusable.
     * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
     *
     * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
     * array of EnumerableSet.
     * ====
     */
    library EnumerableSet {
        // To implement this library for multiple types with as little code
        // repetition as possible, we write it in terms of a generic Set type with
        // bytes32 values.
        // The Set implementation uses private functions, and user-facing
        // implementations (such as AddressSet) are just wrappers around the
        // underlying Set.
        // This means that we can only create new EnumerableSets for types that fit
        // in bytes32.
        struct Set {
            // Storage of set values
            bytes32[] _values;
            // Position is the index of the value in the `values` array plus 1.
            // Position 0 is used to mean a value is not in the set.
            mapping(bytes32 value => uint256) _positions;
        }
        /**
         * @dev Add a value to a set. O(1).
         *
         * Returns true if the value was added to the set, that is if it was not
         * already present.
         */
        function _add(Set storage set, bytes32 value) private returns (bool) {
            if (!_contains(set, value)) {
                set._values.push(value);
                // The value is stored at length-1, but we add 1 to all indexes
                // and use 0 as a sentinel value
                set._positions[value] = set._values.length;
                return true;
            } else {
                return false;
            }
        }
        /**
         * @dev Removes a value from a set. O(1).
         *
         * Returns true if the value was removed from the set, that is if it was
         * present.
         */
        function _remove(Set storage set, bytes32 value) private returns (bool) {
            // We cache the value's position to prevent multiple reads from the same storage slot
            uint256 position = set._positions[value];
            if (position != 0) {
                // Equivalent to contains(set, value)
                // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
                // the array, and then remove the last element (sometimes called as 'swap and pop').
                // This modifies the order of the array, as noted in {at}.
                uint256 valueIndex = position - 1;
                uint256 lastIndex = set._values.length - 1;
                if (valueIndex != lastIndex) {
                    bytes32 lastValue = set._values[lastIndex];
                    // Move the lastValue to the index where the value to delete is
                    set._values[valueIndex] = lastValue;
                    // Update the tracked position of the lastValue (that was just moved)
                    set._positions[lastValue] = position;
                }
                // Delete the slot where the moved value was stored
                set._values.pop();
                // Delete the tracked position for the deleted slot
                delete set._positions[value];
                return true;
            } else {
                return false;
            }
        }
        /**
         * @dev Returns true if the value is in the set. O(1).
         */
        function _contains(Set storage set, bytes32 value) private view returns (bool) {
            return set._positions[value] != 0;
        }
        /**
         * @dev Returns the number of values on the set. O(1).
         */
        function _length(Set storage set) private view returns (uint256) {
            return set._values.length;
        }
        /**
         * @dev Returns the value stored at position `index` in the set. O(1).
         *
         * Note that there are no guarantees on the ordering of values inside the
         * array, and it may change when more values are added or removed.
         *
         * Requirements:
         *
         * - `index` must be strictly less than {length}.
         */
        function _at(Set storage set, uint256 index) private view returns (bytes32) {
            return set._values[index];
        }
        /**
         * @dev Return the entire set in an array
         *
         * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
         * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
         * this function has an unbounded cost, and using it as part of a state-changing function may render the function
         * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
         */
        function _values(Set storage set) private view returns (bytes32[] memory) {
            return set._values;
        }
        // Bytes32Set
        struct Bytes32Set {
            Set _inner;
        }
        /**
         * @dev Add a value to a set. O(1).
         *
         * Returns true if the value was added to the set, that is if it was not
         * already present.
         */
        function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
            return _add(set._inner, value);
        }
        /**
         * @dev Removes a value from a set. O(1).
         *
         * Returns true if the value was removed from the set, that is if it was
         * present.
         */
        function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
            return _remove(set._inner, value);
        }
        /**
         * @dev Returns true if the value is in the set. O(1).
         */
        function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
            return _contains(set._inner, value);
        }
        /**
         * @dev Returns the number of values in the set. O(1).
         */
        function length(Bytes32Set storage set) internal view returns (uint256) {
            return _length(set._inner);
        }
        /**
         * @dev Returns the value stored at position `index` in the set. O(1).
         *
         * Note that there are no guarantees on the ordering of values inside the
         * array, and it may change when more values are added or removed.
         *
         * Requirements:
         *
         * - `index` must be strictly less than {length}.
         */
        function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
            return _at(set._inner, index);
        }
        /**
         * @dev Return the entire set in an array
         *
         * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
         * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
         * this function has an unbounded cost, and using it as part of a state-changing function may render the function
         * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
         */
        function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
            bytes32[] memory store = _values(set._inner);
            bytes32[] memory result;
            /// @solidity memory-safe-assembly
            assembly {
                result := store
            }
            return result;
        }
        // AddressSet
        struct AddressSet {
            Set _inner;
        }
        /**
         * @dev Add a value to a set. O(1).
         *
         * Returns true if the value was added to the set, that is if it was not
         * already present.
         */
        function add(AddressSet storage set, address value) internal returns (bool) {
            return _add(set._inner, bytes32(uint256(uint160(value))));
        }
        /**
         * @dev Removes a value from a set. O(1).
         *
         * Returns true if the value was removed from the set, that is if it was
         * present.
         */
        function remove(AddressSet storage set, address value) internal returns (bool) {
            return _remove(set._inner, bytes32(uint256(uint160(value))));
        }
        /**
         * @dev Returns true if the value is in the set. O(1).
         */
        function contains(AddressSet storage set, address value) internal view returns (bool) {
            return _contains(set._inner, bytes32(uint256(uint160(value))));
        }
        /**
         * @dev Returns the number of values in the set. O(1).
         */
        function length(AddressSet storage set) internal view returns (uint256) {
            return _length(set._inner);
        }
        /**
         * @dev Returns the value stored at position `index` in the set. O(1).
         *
         * Note that there are no guarantees on the ordering of values inside the
         * array, and it may change when more values are added or removed.
         *
         * Requirements:
         *
         * - `index` must be strictly less than {length}.
         */
        function at(AddressSet storage set, uint256 index) internal view returns (address) {
            return address(uint160(uint256(_at(set._inner, index))));
        }
        /**
         * @dev Return the entire set in an array
         *
         * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
         * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
         * this function has an unbounded cost, and using it as part of a state-changing function may render the function
         * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
         */
        function values(AddressSet storage set) internal view returns (address[] memory) {
            bytes32[] memory store = _values(set._inner);
            address[] memory result;
            /// @solidity memory-safe-assembly
            assembly {
                result := store
            }
            return result;
        }
        // UintSet
        struct UintSet {
            Set _inner;
        }
        /**
         * @dev Add a value to a set. O(1).
         *
         * Returns true if the value was added to the set, that is if it was not
         * already present.
         */
        function add(UintSet storage set, uint256 value) internal returns (bool) {
            return _add(set._inner, bytes32(value));
        }
        /**
         * @dev Removes a value from a set. O(1).
         *
         * Returns true if the value was removed from the set, that is if it was
         * present.
         */
        function remove(UintSet storage set, uint256 value) internal returns (bool) {
            return _remove(set._inner, bytes32(value));
        }
        /**
         * @dev Returns true if the value is in the set. O(1).
         */
        function contains(UintSet storage set, uint256 value) internal view returns (bool) {
            return _contains(set._inner, bytes32(value));
        }
        /**
         * @dev Returns the number of values in the set. O(1).
         */
        function length(UintSet storage set) internal view returns (uint256) {
            return _length(set._inner);
        }
        /**
         * @dev Returns the value stored at position `index` in the set. O(1).
         *
         * Note that there are no guarantees on the ordering of values inside the
         * array, and it may change when more values are added or removed.
         *
         * Requirements:
         *
         * - `index` must be strictly less than {length}.
         */
        function at(UintSet storage set, uint256 index) internal view returns (uint256) {
            return uint256(_at(set._inner, index));
        }
        /**
         * @dev Return the entire set in an array
         *
         * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
         * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
         * this function has an unbounded cost, and using it as part of a state-changing function may render the function
         * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
         */
        function values(UintSet storage set) internal view returns (uint256[] memory) {
            bytes32[] memory store = _values(set._inner);
            uint256[] memory result;
            /// @solidity memory-safe-assembly
            assembly {
                result := store
            }
            return result;
        }
    }
    pragma solidity >=0.5.0;
    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;
    }
    pragma solidity >=0.5.0;
    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;
    }
    pragma solidity >=0.6.2;
    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);
    }
    pragma solidity >=0.6.2;
    import "./IUniswapV2Router01.sol";
    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;
    }
    // SPDX-License-Identifier: GPL-2.0-or-later
    pragma solidity >=0.5.0;
    /// @title Callback for IUniswapV3PoolActions#swap
    /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
    interface IUniswapV3SwapCallback {
        /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
        /// @dev In the implementation you must pay the pool tokens owed for the swap.
        /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
        /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
        /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
        /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
        /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
        /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
        /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
        function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external;
    }
    // SPDX-License-Identifier: GPL-2.0-or-later
    pragma solidity >=0.7.5;
    pragma abicoder v2;
    import "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol";
    /// @title Router token swapping functionality
    /// @notice Functions for swapping tokens via Uniswap V3
    interface ISwapRouter is IUniswapV3SwapCallback {
        struct ExactInputSingleParams {
            address tokenIn;
            address tokenOut;
            uint24 fee;
            address recipient;
            uint256 deadline;
            uint256 amountIn;
            uint256 amountOutMinimum;
            uint160 sqrtPriceLimitX96;
        }
        /// @notice Swaps `amountIn` of one token for as much as possible of another token
        /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
        /// @return amountOut The amount of the received token
        function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
        struct ExactInputParams {
            bytes path;
            address recipient;
            uint256 deadline;
            uint256 amountIn;
            uint256 amountOutMinimum;
        }
        /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
        /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
        /// @return amountOut The amount of the received token
        function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
        struct ExactOutputSingleParams {
            address tokenIn;
            address tokenOut;
            uint24 fee;
            address recipient;
            uint256 deadline;
            uint256 amountOut;
            uint256 amountInMaximum;
            uint160 sqrtPriceLimitX96;
        }
        /// @notice Swaps as little as possible of one token for `amountOut` of another token
        /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
        /// @return amountIn The amount of the input token
        function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
        struct ExactOutputParams {
            bytes path;
            address recipient;
            uint256 deadline;
            uint256 amountOut;
            uint256 amountInMaximum;
        }
        /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
        /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
        /// @return amountIn The amount of the input token
        function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
    }
    // SPDX-License-Identifier: UNLICENSED
    pragma solidity ^0.8.24;
    import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
    import "@openzeppelin/contracts/interfaces/IERC20.sol";
    import "@openzeppelin/contracts/interfaces/IERC165.sol";
    import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
    import "@openzeppelin/contracts/access/Ownable2Step.sol";
    import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
    import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
    import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
    import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
    import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol";
    import "./interfaces/IElementNFT.sol";
    import "./interfaces/ITITANX.sol";
    import "./interfaces/IWETH9.sol";
    import "./lib/constants.sol";
    /// @title Element 280 Token Contract
    contract Element280 is ERC20, Ownable2Step, IERC165 {
        using SafeERC20 for IERC20;
        using EnumerableSet for EnumerableSet.UintSet;
        // --------------------------- STATE VARIABLES --------------------------- //
        struct UserPurchase {
            uint256 timestamp;
            uint256 amount;
        }
        address public treasury;
        address public devWallet;
        address public E280NFT;
        address public HOLDER_VAULT;
        address public BUY_AND_BURN;
        /// @notice Total number of liqudity pools created for Element 280 protocol tokens
        uint8 public totalLPsCreated;
        /// @notice Purchases of ecosystem tokens are in progress
        bool public lpPurchaseStarted;
        /// @notice Purchases of ecosystem tokens are done
        bool public lpPurchaseFinished;
        /// @notice Trading is disabled until all LPs are created. Enables automatically with the creation of the last LP.
        bool public tradingEnabled;
        /// @notice TitanX tokens designated for ecosystem token purchases.
        uint256 public lpPool;
        /// @notice TitanX tokens used for ecosystem token purchases.
        uint256 public totalLpPoolUsed;
        /// @notice Total ELMT tokens burned to date.
        uint256 public totalBurned;
        /// @notice Timestamp in seconds of the presale end date.
        uint256 public presaleEnd;
        uint256 private _currentPurchaseId;
        /// @notice Purchase information for a specific purchase ID.
        /// @return timestamp The time when the purchase was made (as a Unix timestamp).
        /// @return amount The amount of Element 280 toknes of the purchase.
        mapping(uint256 purchaseId => UserPurchase) public purchases;
        /// @notice Returns the total amount of ecosystem tokens purchased for LP creation for a specific token.
        /// @return The total amount of the specified token allocated to the LP pool (in WEI).
        mapping(address token => uint256) public tokenPool;
        /// @notice Percent of the lpPool to calculate the allocation per ecosystem token purchases.
        mapping(address token => uint8) public tokenLpPercent;
        /// @notice Are transcations to provided address whitelisted.
        mapping(address => bool) public whitelistTo;
        /// @notice Are transcations from provided address whitelisted.
        mapping(address => bool) public whitelistFrom;
        /// @notice Total number of purchases per each ecosystem token. 5 per token is required.
        mapping(address token => uint8) public lpPurchases;
        mapping(address user => EnumerableSet.UintSet) private _userPurchases;
        // --------------------------- EVENTS & MODIFIERS --------------------------- //
        event PresaleStarted();
        modifier onlyPresale() {
            require(isPresaleActive(), "Presale not active");
            _;
        }
        modifier onlyNftContract() {
            require(msg.sender == E280NFT, "Unauthorized");
            _;
        }
        // --------------------------- CONSTRUCTOR --------------------------- //
        constructor(
            address _owner,
            address _devWallet,
            address _treasury,
            address[] memory _ecosystemTokens,
            uint8[] memory _lpPercentages
        ) ERC20("Element 280", "ELMNT") Ownable(_owner) {
            require(_ecosystemTokens.length == NUM_ECOSYSTEM_TOKENS, "Incorrect number of tokens");
            require(_lpPercentages.length == NUM_ECOSYSTEM_TOKENS, "Incorrect number of tokens");
            require(_owner != address(0), "Owner wallet not provided");
            require(_devWallet != address(0), "Dev wallet address not provided");
            require(_treasury != address(0), "Treasury address not provided");
            devWallet = _devWallet;
            treasury = _treasury;
            whitelistFrom[address(0)] = true;
            whitelistTo[address(0)] = true;
            uint8 totalPercentage;
            for (uint256 i = 0; i < _ecosystemTokens.length; i++) {
                address token = _ecosystemTokens[i];
                uint8 allocation = _lpPercentages[i];
                require(token != address(0), "Incorrect token address");
                require(allocation > 0, "Incorrect percentage value");
                require(tokenLpPercent[token] == 0, "Duplicate token");
                tokenLpPercent[token] = allocation;
                totalPercentage += allocation;
            }
            require(totalPercentage == 100, "Percentages do not add to 100");
        }
        // --------------------------- PUBLIC FUNCTIONS --------------------------- //
        /// @notice Allows users to purchase tokens during the presale using TitanX tokens.
        /// @param amount The amount of TitanX tokens to spend.
        function purchaseWithTitanX(uint256 amount) external onlyPresale {
            require(amount > 0, "Cannot purchase 0 tokens");
            IERC20(TITANX).safeTransferFrom(msg.sender, address(this), amount);
            _writePurchaseData(amount, msg.sender);
        }
        /// @notice Allows users to purchase tokens during the presale using ETH.
        /// @param minAmount The minimum amount of Element 280 tokens to purchase.
        function purchaseWithETH(uint256 minAmount, uint256 deadline) external payable onlyPresale {
            require(minAmount > 0, "Cannot purchase 0 tokens");
            uint256 swappedAmount = _swapETHForTitanX(minAmount, deadline);
            _writePurchaseData(swappedAmount, msg.sender);
        }
        /// @notice Allows users to claim their purchased tokens after the cooldown period.
        /// @param purchaseId The ID of the purchase to claim.
        function claimPurchase(uint256 purchaseId) external {
            require(_userPurchases[msg.sender].contains(purchaseId), "Cannot claim");
            UserPurchase memory purchase = purchases[purchaseId];
            require(purchase.timestamp + COOLDOWN_PERIOD < block.timestamp, "Cooldown is active");
            _userPurchases[msg.sender].remove(purchaseId);
            _mint(msg.sender, purchase.amount);
        }
        /// @notice Transfers TitanX allocation to Element 280 Buy&Burn contract.
        /// @dev Can only be called when there is an allocation for buy and burn.
        function distributeBuyAndBurn() external {
            uint256 allocation = getBuyBurnAllocation();
            require(allocation > 0, "Nothing to distribute");
            IERC20(TITANX).safeTransfer(BUY_AND_BURN, allocation);
        }
        /// @notice Burns the specified amount of tokens from the user's balance.
        /// @param value The amount of tokens in wei.
        function burn(uint256 value) public virtual {
            totalBurned += value;
            _burn(_msgSender(), value);
        }
        // --------------------------- PRESALE MANAGEMENT FUNCTIONS --------------------------- //
        /// @notice Starts the presale for the token.
        function startPresale() external onlyOwner {
            require(E280NFT != address(0), "NFT not set");
            require(presaleEnd == 0, "Can only be done once");
            unchecked {
                presaleEnd = block.timestamp + PRESALE_LENGTH;
            }
            IElementNFT(E280NFT).startPresale(presaleEnd);
            emit PresaleStarted();
        }
        /// @notice Begins the liquidity pool creation process after the presale has either ended or accumulated more than 200B TitanX.
        function startLpPurchases() external onlyOwner {
            require(presaleEnd != 0, "Presale not started yet");
            require(!lpPurchaseStarted, "LP creation already started");
            uint256 availableBalance = IERC20(TITANX).balanceOf(address(this));
            require(availableBalance > 0, "No TitanX available");
            if (availableBalance < LP_POOL_SIZE) {
                require(block.timestamp >= presaleEnd, "Presale not finished yet");
                _registerLPPool(availableBalance);
            } else {
                _registerLPPool(LP_POOL_SIZE);
            }
            lpPurchaseStarted = true;
        }
        /// @notice Executes token purchase of the ecosystem tokens for the liquidity pool based on the allocation.
        /// @param target The target token to purchase.
        /// @param minAmountOut Minimum amout to be received after swap.
        /// @dev Can only be called by the contract owner during the LP purchase phase.
        function purchaseTokenForLP(address target, uint256 minAmountOut, uint256 deadline) external onlyOwner {
            require(lpPurchaseStarted && !lpPurchaseFinished, "LP phase not active");
            require(lpPurchases[target] < 5, "All purchases have been made for target token");
            uint8 allocation = tokenLpPercent[target];
            require(allocation > 0, "Incorrect target token");
            uint256 amount = lpPool * allocation / 500;
            totalLpPoolUsed += amount;
            uint256 swappedAmount = _swapTitanXToToken(target, amount, minAmountOut, deadline);
            unchecked {
                tokenPool[target] += swappedAmount;
                lpPurchases[target]++;
                // account for rounding error
                if (totalLpPoolUsed >= lpPool - NUM_ECOSYSTEM_TOKENS * 5) lpPurchaseFinished = true;
            }
        }
        /// @notice Deploys the liquidity pool for a specific ecosystem token.
        /// @param target The token for which the liquidity pool will be deployed.
        /// @dev Can only be called by the contract owner after the LP phase has completed.
        function deployLP(address target, uint256 minTokenAmount, uint256 minE280Amount) external onlyOwner {
            require(lpPurchaseFinished, "Not all tokens have been purchased");
            uint8 allocation = tokenLpPercent[target];
            require(allocation > 0, "Incorrect target token");
            uint256 e280Amount = lpPool * allocation / 100;
            uint256 tokenAmount = tokenPool[target];
            require(tokenAmount > 0, "Pool already deployed");
            _deployLiqudityPool(target, tokenAmount, e280Amount, minTokenAmount, minE280Amount);
            unchecked {
                totalLPsCreated++;
            }
            if (totalLPsCreated == NUM_ECOSYSTEM_TOKENS) _enableTrading();
        }
        // --------------------------- ADMINISTRATIVE FUNCTIONS --------------------------- //
        /// @notice Sets the required addresses for the Element 280 protocol.
        /// @param nftAddress The address of the Element 280 NFT contract.
        /// @param vaultAddress The address of the Element 280 Holder Vault contract.
        /// @param buyAndBurn The address of the Element 280 Buy&Burn contract.
        /// @dev Can only be set once and can only be called by the owner.
        function setProtocolAddresses(address nftAddress, address vaultAddress, address buyAndBurn) external onlyOwner {
            require(E280NFT == address(0), "Can only be done once");
            require(nftAddress != address(0), "NFT address not provided");
            require(vaultAddress != address(0), "Holder Vault address not provided");
            require(buyAndBurn != address(0), "Buy&Burn address not provided");
            E280NFT = nftAddress;
            HOLDER_VAULT = vaultAddress;
            BUY_AND_BURN = buyAndBurn;
            whitelistFrom[HOLDER_VAULT] = true;
            whitelistTo[BUY_AND_BURN] = true;
        }
        /// @notice Sets the treasury address.
        /// @param _address The address of the treasury.
        /// @dev Can only be called by the owner.
        function setTreasury(address _address) external onlyOwner {
            require(_address != address(0), "Treasury address not provided");
            treasury = _address;
        }
        /// @notice Sets the whitelist status for transfers to a specified address.
        /// @param _address The address which whitelist status will be modified.
        /// @param enabled Will the address be whitelisted.
        /// @dev Can only be called by the owner.
        function setWhitelistTo(address _address, bool enabled) external onlyOwner {
            whitelistTo[_address] = enabled;
        }
        /// @notice Sets the whitelist status for transfers from a specified address.
        /// @param _address The address which whitelist status will be modified.
        /// @param enabled Will the address be whitelisted.
        /// @dev Can only be called by the owner.
        function setWhitelistFrom(address _address, bool enabled) external onlyOwner {
            whitelistFrom[_address] = enabled;
        }
        // --------------------------- VIEW FUNCTIONS --------------------------- //
        /// @notice Checks if the presale is currently active.
        /// @return A boolean indicating whether the presale is still active.
        function isPresaleActive() public view returns (bool) {
            return presaleEnd > block.timestamp;
        }
        /// @notice Returns all purchase IDs associated with a specific user.
        /// @param account The address of the user.
        /// @return An array of purchase IDs owned by the user.
        function getUserPurchaseIds(address account) external view returns (uint256[] memory) {
            return _userPurchases[account].values();
        }
        /// @notice Returns the available TitanX tokens for Element 280 Buy&Burn contract.
        /// @return The amount of TitanX tokens allocated (in WEI).
        /// @dev Requires that trading has been enabled.
        function getBuyBurnAllocation() public view returns (uint256) {
            require(tradingEnabled, "Trading is not enabled yet");
            return IERC20(TITANX).balanceOf(address(this));
        }
        function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165) returns (bool) {
            return interfaceId == INTERFACE_ID_ERC165 || interfaceId == INTERFACE_ID_ERC20;
        }
        // --------------------------- INTERNAL FUNCTIONS --------------------------- //
        /// @notice Handles the redemption process, applying tax and distributing the remaining amount.
        /// @param amount The amount to redeem.
        /// @param receiver The address to receive the redeemed amount after tax.
        /// @dev This function is only callable by the NFT contract.
        function handleRedeem(uint256 amount, address receiver) external onlyNftContract {
            (uint256 taxAmount, uint256 amountAfterTax) = _processTax(amount, NFT_REDEEM_TAX_PERCENTAGE);
            _mint(HOLDER_VAULT, taxAmount);
            _mint(receiver, amountAfterTax);
        }
        function _enableTrading() internal {
            tradingEnabled = true;
        }
        function _update(address from, address to, uint256 amount) internal override {
            if (!tradingEnabled) {
                if (from == address(this) || from == address(0)) {
                    super._update(from, to, amount);
                } else {
                    revert("Trading is disabled");
                }
            } else {
                if (whitelistTo[to] || whitelistFrom[from]) {
                    super._update(from, to, amount);
                } else {
                    uint256 taxPercentage = isPresaleActive() ? PRESALE_TRANSFER_TAX_PERCENTAGE : TRANSFER_TAX_PERCENTAGE;
                    (uint256 taxAmount, uint256 amountAfterTax) = _processTax(amount, taxPercentage);
                    super._update(from, HOLDER_VAULT, taxAmount);
                    super._update(from, to, amountAfterTax);
                }
            }
        }
        function _writePurchaseData(uint256 amount, address to) internal {
            purchases[_currentPurchaseId] = UserPurchase(block.timestamp, amount);
            _userPurchases[to].add(_currentPurchaseId);
            unchecked {
                _currentPurchaseId++;
            }
        }
        function _processTax(uint256 amount, uint256 percentage)
            internal
            pure
            returns (uint256 taxAmount, uint256 amountAfterTax)
        {
            unchecked {
                taxAmount = (amount * percentage) / 100;
                amountAfterTax = amount - taxAmount;
            }
        }
        function _registerLPPool(uint256 amount) internal {
            uint256 devAmount = amount * DEV_PERCENT / 100;
            uint256 treasuryAmount = amount * TREASURY_PERCENT / 100;
            IERC20(TITANX).safeTransfer(devWallet, devAmount);
            IERC20(TITANX).safeTransfer(treasury, treasuryAmount);
            lpPool = amount - devAmount - treasuryAmount;
            lpPurchases[TITANX] = 5;
            uint256 titanXPool = lpPool * tokenLpPercent[TITANX] / 100;
            tokenPool[TITANX] = titanXPool;
            totalLpPoolUsed += titanXPool;
        }
        function _deployLiqudityPool(address tokenAddress, uint256 tokenAmount, uint256 e280Amount, uint256 minTokenAmount, uint256 minE280Amount) internal {
            (uint256 pairBalance, address pairAddress) = _checkPoolValidity(tokenAddress);
            if (pairBalance > 0) _fixPool(pairAddress, tokenAmount, e280Amount, pairBalance);
            _mint(address(this), e280Amount);
            IERC20(address(this)).safeIncreaseAllowance(UNISWAP_V2_ROUTER, e280Amount);
            IERC20(tokenAddress).safeIncreaseAllowance(UNISWAP_V2_ROUTER, tokenAmount);
            IUniswapV2Router02(UNISWAP_V2_ROUTER).addLiquidity(
                address(this),
                tokenAddress,
                e280Amount,
                tokenAmount,
                minE280Amount,
                minTokenAmount,
                address(0), //send governance tokens directly to zero address
                block.timestamp
            );
            tokenPool[tokenAddress] = 0;
        }
        function _checkPoolValidity(address target) internal view returns (uint256, address) {
            address pairAddress = IUniswapV2Factory(UNISWAP_V2_FACTORY).getPair(address(this), target);
            if (pairAddress == address(0)) return (0, pairAddress);
            IUniswapV2Pair pair = IUniswapV2Pair(pairAddress);
            (uint112 reserve0, uint112 reserve1, ) = pair.getReserves();
            if (reserve0 != 0) return (reserve0, pairAddress);
            if (reserve1 != 0) return (reserve1, pairAddress);
            return (0, pairAddress);
        }
        function _fixPool(address pairAddress, uint256 tokenAmount, uint256 e280Amount, uint256 currentBalance) internal {
            uint256 requiredE280 = currentBalance * e280Amount / tokenAmount;
            _mint(pairAddress, requiredE280);
            IUniswapV2Pair(pairAddress).sync();
        }
        function _swapETHForTitanX(uint256 minAmountOut, uint256 deadline) internal returns (uint256) {
            IWETH9(WETH9).deposit{value: msg.value}();
            ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams({
                tokenIn: WETH9,
                tokenOut: TITANX,
                fee: POOL_FEE_1PERCENT,
                recipient: address(this),
                deadline: deadline,
                amountIn: msg.value,
                amountOutMinimum: minAmountOut,
                sqrtPriceLimitX96: 0
            });
            IERC20(WETH9).safeIncreaseAllowance(UNISWAP_V3_ROUTER, msg.value);
            uint256 amountOut = ISwapRouter(UNISWAP_V3_ROUTER).exactInputSingle(params);
            return amountOut;
        }
        function _swapTitanXToToken(address outputToken, uint256 amount, uint256 minAmountOut, uint256 deadline)
            internal
            returns (uint256)
        {
            if (outputToken == BLAZE_ADDRESS) return _swapUniswapV2Pool(outputToken, amount, minAmountOut, deadline);
            if (outputToken == BDX_ADDRESS || outputToken == HYDRA_ADDRESS || outputToken == AWESOMEX_ADDRESS) {
                return _swapMultihop(outputToken, DRAGONX_ADDRESS, amount, minAmountOut, deadline);
            }
            if (outputToken == FLUX_ADDRESS) {
                return _swapMultihop(outputToken, INFERNO_ADDRESS, amount, minAmountOut, deadline);
            }
            return _swapUniswapV3Pool(outputToken, amount, minAmountOut, deadline);
        }
        function _swapUniswapV3Pool(address outputToken, uint256 amountIn, uint256 minAmountOut, uint256 deadline)
            internal
            returns (uint256)
        {
            ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams({
                tokenIn: TITANX,
                tokenOut: outputToken,
                fee: POOL_FEE_1PERCENT,
                recipient: address(this),
                deadline: deadline,
                amountIn: amountIn,
                amountOutMinimum: minAmountOut,
                sqrtPriceLimitX96: 0
            });
            IERC20(TITANX).safeIncreaseAllowance(UNISWAP_V3_ROUTER, amountIn);
            uint256 amountOut = ISwapRouter(UNISWAP_V3_ROUTER).exactInputSingle(params);
            return amountOut;
        }
        function _swapUniswapV2Pool(address outputToken, uint256 amountIn, uint256 minAmountOut, uint256 deadline)
            internal
            returns (uint256)
        {
            require(minAmountOut > 0, "minAmountOut not provided");
            IERC20(TITANX).safeIncreaseAllowance(UNISWAP_V2_ROUTER, amountIn);
            address[] memory path = new address[](2);
            path[0] = TITANX;
            path[1] = outputToken;
            uint256[] memory amounts = IUniswapV2Router02(UNISWAP_V2_ROUTER).swapExactTokensForTokens(
                amountIn, minAmountOut, path, address(this), deadline
            );
            return amounts[1];
        }
        function _swapMultihop(
            address outputToken,
            address midToken,
            uint256 amountIn,
            uint256 minAmountOut,
            uint256 deadline
        ) internal returns (uint256) {
            bytes memory path = abi.encodePacked(TITANX, POOL_FEE_1PERCENT, midToken, POOL_FEE_1PERCENT, outputToken);
            ISwapRouter.ExactInputParams memory params = ISwapRouter.ExactInputParams({
                path: path,
                recipient: address(this),
                deadline: deadline,
                amountIn: amountIn,
                amountOutMinimum: minAmountOut
            });
            IERC20(TITANX).safeIncreaseAllowance(UNISWAP_V3_ROUTER, amountIn);
            uint256 amoutOut = ISwapRouter(UNISWAP_V3_ROUTER).exactInput(params);
            return amoutOut;
        }
    }
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.24;
    interface IElementNFT {
        function startPresale(uint256 _presaleEnd) external;
        function multiplierPool() external returns (uint256);
        function getBatchedTokensData(uint256[] calldata tokenIds, address owner)
            external
            view
            returns (uint256[] memory timestamps, uint16[] memory multipliers);
    }
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.10;
    interface ITitanOnBurn {
        function onBurn(address user, uint256 amount) external;
    }
    // SPDX-License-Identifier: UNLICENSED
    pragma solidity ^0.8.10;
    interface ITITANX {
        error TitanX_InvalidAmount();
        error TitanX_InsufficientBalance();
        error TitanX_NotSupportedContract();
        error TitanX_InsufficientProtocolFees();
        error TitanX_FailedToSendAmount();
        error TitanX_NotAllowed();
        error TitanX_NoCycleRewardToClaim();
        error TitanX_NoSharesExist();
        error TitanX_EmptyUndistributeFees();
        error TitanX_InvalidBurnRewardPercent();
        error TitanX_InvalidBatchCount();
        error TitanX_InvalidMintLadderInterval();
        error TitanX_InvalidMintLadderRange();
        error TitanX_MaxedWalletMints();
        error TitanX_LPTokensHasMinted();
        error TitanX_InvalidAddress();
        error TitanX_InsufficientBurnAllowance();
        function getBalance() external;
        /**
         * @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 value of tokens in existence.
         */
        function totalSupply() external view returns (uint256);
        /**
         * @dev Returns the value of tokens owned by `account`.
         */
        function balanceOf(address account) external view returns (uint256);
        /**
         * @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool);
        /**
         * @dev Moves a `value` amount of tokens from `from` to `to` using the
         * allowance mechanism. `value` 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 value) external returns (bool);
        function burnTokensToPayAddress(
            address user,
            uint256 amount,
            uint256 userRebatePercentage,
            uint256 rewardPaybackPercentage,
            address rewardPaybackAddress
        ) external;
        function burnTokens(address user, uint256 amount, uint256 userRebatePercentage, uint256 rewardPaybackPercentage)
            external;
        function userBurnTokens(uint256 amount) external;
    }
    // SPDX-License-Identifier: GPL-2.0-or-later
    pragma solidity ^0.8.10;
    import "@openzeppelin/contracts/interfaces/IERC20.sol";
    /// @title Interface for WETH9
    interface IWETH9 is IERC20 {
        /// @notice Deposit ether to get wrapped ether
        function deposit() external payable;
        /// @notice Withdraw wrapped ether to get ether
        function withdraw(uint256) external;
    }
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.24;
    import "../interfaces/ITitanOnBurn.sol";
    import "@openzeppelin/contracts/interfaces/IERC20.sol";
    // ===================== Contract Addresses =====================================
    uint8 constant NUM_ECOSYSTEM_TOKENS = 14;
    address constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
    address constant TITANX = 0xF19308F923582A6f7c465e5CE7a9Dc1BEC6665B1;
    address constant HYPER_ADDRESS = 0xE2cfD7a01ec63875cd9Da6C7c1B7025166c2fA2F;
    address constant HELIOS_ADDRESS = 0x2614f29C39dE46468A921Fd0b41fdd99A01f2EDf;
    address constant DRAGONX_ADDRESS = 0x96a5399D07896f757Bd4c6eF56461F58DB951862;
    address constant BDX_ADDRESS = 0x9f278Dc799BbC61ecB8e5Fb8035cbfA29803623B;
    address constant BLAZE_ADDRESS = 0xfcd7cceE4071aA4ecFAC1683b7CC0aFeCAF42A36;
    address constant INFERNO_ADDRESS = 0x00F116ac0c304C570daAA68FA6c30a86A04B5C5F;
    address constant HYDRA_ADDRESS = 0xCC7ed2ab6c3396DdBc4316D2d7C1b59ff9d2091F;
    address constant AWESOMEX_ADDRESS = 0xa99AFcC6Aa4530d01DFFF8E55ec66E4C424c048c;
    address constant FLUX_ADDRESS = 0xBFDE5ac4f5Adb419A931a5bF64B0f3BB5a623d06;
    address constant DRAGONX_BURN_ADDRESS = 0x1d59429571d8Fde785F45bf593E94F2Da6072Edb;
    // ===================== Presale ================================================
    uint256 constant PRESALE_LENGTH = 28 days;
    uint256 constant COOLDOWN_PERIOD = 48 hours;
    uint256 constant LP_POOL_SIZE = 200_000_000_000 ether;
    // ===================== Fees ===================================================
    uint256 constant DEV_PERCENT = 6;
    uint256 constant TREASURY_PERCENT = 4;
    uint256 constant BURN_PERCENT = 10;
    // ===================== Sell Tax ===============================================
    uint256 constant PRESALE_TRANSFER_TAX_PERCENTAGE = 16;
    uint256 constant TRANSFER_TAX_PERCENTAGE = 4;
    uint256 constant NFT_REDEEM_TAX_PERCENTAGE = 3;
    // ===================== Holder Vault ===========================================
    uint16 constant MAX_CYCLES_PER_CLAIM = 100;
    uint32 constant CYCLE_INTERVAL = 7 days;
    // ===================== UNISWAP Interface ======================================
    address constant UNISWAP_V2_FACTORY = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
    address constant UNISWAP_V2_ROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
    address constant UNISWAP_V3_ROUTER = 0xE592427A0AEce92De3Edee1F18E0157C05861564;
    uint24 constant POOL_FEE_1PERCENT = 10000;
    // ===================== Interface IDs ==========================================
    bytes4 constant INTERFACE_ID_ERC165 = 0x01ffc9a7;
    bytes4 constant INTERFACE_ID_ERC20 = type(IERC20).interfaceId;
    bytes4 constant INTERFACE_ID_ERC721 = 0x80ac58cd;
    bytes4 constant INTERFACE_ID_ERC721Metadata = 0x5b5e139f;
    bytes4 constant INTERFACE_ID_ITITANONBURN = type(ITitanOnBurn).interfaceId;
    

    File 4 of 4: GnosisSafeProxy
    // SPDX-License-Identifier: LGPL-3.0-only
    pragma solidity >=0.7.0 <0.9.0;
    
    /// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain
    /// @author Richard Meissner - <[email protected]>
    interface IProxy {
        function masterCopy() external view returns (address);
    }
    
    /// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
    /// @author Stefan George - <[email protected]>
    /// @author Richard Meissner - <[email protected]>
    contract GnosisSafeProxy {
        // singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
        // To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
        address internal singleton;
    
        /// @dev Constructor function sets address of singleton contract.
        /// @param _singleton Singleton address.
        constructor(address _singleton) {
            require(_singleton != address(0), "Invalid singleton address provided");
            singleton = _singleton;
        }
    
        /// @dev Fallback function forwards all transactions and returns all received return data.
        fallback() external payable {
            // solhint-disable-next-line no-inline-assembly
            assembly {
                let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
                // 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
                if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
                    mstore(0, _singleton)
                    return(0, 0x20)
                }
                calldatacopy(0, 0, calldatasize())
                let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
                returndatacopy(0, 0, returndatasize())
                if eq(success, 0) {
                    revert(0, returndatasize())
                }
                return(0, returndatasize())
            }
        }
    }
    
    /// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
    /// @author Stefan George - <[email protected]>
    contract GnosisSafeProxyFactory {
        event ProxyCreation(GnosisSafeProxy proxy, address singleton);
    
        /// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
        /// @param singleton Address of singleton contract.
        /// @param data Payload for message call sent to new proxy contract.
        function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) {
            proxy = new GnosisSafeProxy(singleton);
            if (data.length > 0)
                // solhint-disable-next-line no-inline-assembly
                assembly {
                    if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) {
                        revert(0, 0)
                    }
                }
            emit ProxyCreation(proxy, singleton);
        }
    
        /// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed.
        function proxyRuntimeCode() public pure returns (bytes memory) {
            return type(GnosisSafeProxy).runtimeCode;
        }
    
        /// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address.
        function proxyCreationCode() public pure returns (bytes memory) {
            return type(GnosisSafeProxy).creationCode;
        }
    
        /// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer.
        ///      This method is only meant as an utility to be called from other methods
        /// @param _singleton Address of singleton contract.
        /// @param initializer Payload for message call sent to new proxy contract.
        /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
        function deployProxyWithNonce(
            address _singleton,
            bytes memory initializer,
            uint256 saltNonce
        ) internal returns (GnosisSafeProxy proxy) {
            // If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it
            bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));
            bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton)));
            // solhint-disable-next-line no-inline-assembly
            assembly {
                proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)
            }
            require(address(proxy) != address(0), "Create2 call failed");
        }
    
        /// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
        /// @param _singleton Address of singleton contract.
        /// @param initializer Payload for message call sent to new proxy contract.
        /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
        function createProxyWithNonce(
            address _singleton,
            bytes memory initializer,
            uint256 saltNonce
        ) public returns (GnosisSafeProxy proxy) {
            proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
            if (initializer.length > 0)
                // solhint-disable-next-line no-inline-assembly
                assembly {
                    if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) {
                        revert(0, 0)
                    }
                }
            emit ProxyCreation(proxy, _singleton);
        }
    
        /// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction
        /// @param _singleton Address of singleton contract.
        /// @param initializer Payload for message call sent to new proxy contract.
        /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
        /// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized.
        function createProxyWithCallback(
            address _singleton,
            bytes memory initializer,
            uint256 saltNonce,
            IProxyCreationCallback callback
        ) public returns (GnosisSafeProxy proxy) {
            uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback)));
            proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback);
            if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce);
        }
    
        /// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce`
        ///      This method is only meant for address calculation purpose when you use an initializer that would revert,
        ///      therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory.
        /// @param _singleton Address of singleton contract.
        /// @param initializer Payload for message call sent to new proxy contract.
        /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
        function calculateCreateProxyWithNonceAddress(
            address _singleton,
            bytes calldata initializer,
            uint256 saltNonce
        ) external returns (GnosisSafeProxy proxy) {
            proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
            revert(string(abi.encodePacked(proxy)));
        }
    }
    
    interface IProxyCreationCallback {
        function proxyCreated(
            GnosisSafeProxy proxy,
            address _singleton,
            bytes calldata initializer,
            uint256 saltNonce
        ) external;
    }