// File: contracts/Infiltration.sol



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

import {IInfiltration} from "./interfaces/IInfiltration.sol";

import {OwnableTwoSteps} from "@looksrare/contracts-libs/contracts/OwnableTwoSteps.sol";
import {IERC20} from "@looksrare/contracts-libs/contracts/interfaces/generic/IERC20.sol";

import {ProtocolFee} from "@looksrare/contracts-libs/contracts/ProtocolFee.sol";
import {PackableReentrancyGuard} from "@looksrare/contracts-libs/contracts/PackableReentrancyGuard.sol";
import {LowLevelERC20Transfer} from "@looksrare/contracts-libs/contracts/lowLevelCallers/LowLevelERC20Transfer.sol";
import {LowLevelWETH} from "@looksrare/contracts-libs/contracts/lowLevelCallers/LowLevelWETH.sol";
import {ITransferManager} from "@looksrare/contracts-transfer-manager/contracts/interfaces/ITransferManager.sol";

import {VRFCoordinatorV2Interface} from "@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol";
import {VRFConsumerBaseV2} from "@chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol";
import "erc721a/contracts/ERC721A.sol";

import {UnsafeMathUint256} from "./libraries/UnsafeMathUint256.sol";

//                                            .:^^^^^^:::::::::::::::::::::::::::::::::::::::::::::.
//                                          :~7777!!!77?JJ??????!?YYYYYYYYJ?7~~!!!!!!!!!7???7~~~!~~^:.
//                                        :~!!!~~77JYYYJJYJJJJJ7J5PPPPP55?!!!!!!!7!!~~~~~~!77??7?!7!!~^.
//                                      .^~!!!7JYYYYYYJJJJJJJJJ7Y5PPPY?!!!!!!~~~~~~!7!!~~~~~~!????J??7!!^.
//                                   .:^!!?JYYYYYYYYJJJJJJJYJJ!J55YJ?!!!!!~~~~~~~~~~~!!7!!!!!7!!!!!77?JJ?!~:.
//                                 .:^~?YYYYYYYYYJJJJJJJJJJJJ??YYJ?!!!77!!!!!!!!!!!!!!~~!!!77!!!!!!!!!!!7?J7~:.
//                               .^~~!~JYYYYYYYYYJJJJJJJJ???~^??7^.........:::::::^^^^!!!!!77!!!!!!!!!!~~!!7?7!^.
//                             :^!!!!!~~JYYYYYYJJJJJJJ7!~^:::!????~....    ...:::::::::::^^~77!!!!!!!!!~~~!!!77!!^.
//                           :~77~!7!!~!JYJJJJJJJJJ!^^^^^^^:^JJ???7!^^::::::::..::::::::::::.:~!!!!!~7?!~~~~!!!!~~!^.
//                         :!?7!!!77!~~JJJJJJJJ?!^^^^^^^^^::J???5PPG##GPPP5555?77!::::::::.....::^!!!J5Y?!~~~~!77~~~!~:
//                      .:7J?!~!77!~~~!JJJJJ?~^^^^^^^^^^^::~?5##&@@@@@&BGBGPPPP555YJ!^::......:::...^?55YJ?!~~!!!!~~!!!~:
//                    .^7J?7!!!!!!~~~~JJJJ7~^^^^^^^^^^^^:^J##@@@@@@@@@@@&#GGPPP555PPP55?:...::::::.. :!?JJJJ7!~~!77!~!!~!~:.
//                  .:!?77!!!!!!~~~~~7JJ7~^^^^^^^^^^^^::~J#@@@@@@@@@@@@@@@#BGP55PPPPPGGGJ^......:::. ^~:^7???7!!!!!!~~!!!~!~:.
//                .:!7!~~!!!!!!!~~~~!J7~^^^^^^^^^^^^^::7PB&@@@@@@@@&&B55555YGGPPPPPPGGBBBG7......:::..:^::^!7777!!!!!~~!!!!~!~^.
//              .:^~!?J!~!7!!!!!~~~!~~^^~^^^^^:::::::.7PGB&&&&@@@&G?~~~!!!!~~~75GBBBBBBBB#B?  ......   .... :~!7!!!!~~!!!!!7!~7?~.
//            .:^~!?5PPJ!~!!!!!~!!^::!~!!!^:....... .^JPB&&&&&&&G?~~!!7?JJ7!~^:^!5###&#####P~       :^^:      .^!!~~!7777!!!!~7Y5J!.
//          .:^~!JY5PPPPY!~~~~!!^.   .:^!!^.       ::YBB####&&&P~^~!~~~^^^^:::::.^P&&&&&#&&&5    .:!????7!^::.  .^!!77777777!~!J5PPY!:
//        .:~~~?Y5555PP5Y?~~!!^.        .^:..^^^!77?!5BB######B~:^^^::::::::......^#&&&&&&&&5  .:!???????????7!!^::~7?7?77777777?Y555J~.
//       .:^~!!7?J??????7!!!7~.       .......:^77?JJ!5BBBBBBB#B^:::::....::::::::.~&@@@@&&&&5...^^^^^^^^^^^~^^^^^^:.~7!!~~~~~!!!!!77?7~:.
//         .:^~!~!77!!!!!~~~!!!^:..... .::~~:....:^^:?GBBBGPPP5~.....:::::::::::.:7&&&&&&&&&P:::^:^^^^^:. .:.    .^~~~~~~~~~~~~~!77!~:.
//           .:^~!!!77!!!~~~~~~!!^.   .::!77~^:......!Y555555555!:..::::::::::..:?#&&&&&&@@&5!7???????!. :~:.. .^!!~~~~~~~~~~~!!7!~:.
//            ..:^~!!7?!!~~~~~~~~!!~:.:^!7!^.:^: .....755PPPPPPGG57:..::::::..:7P#&&&&&&@@@P!7????JJJ!. :^::.:~!!~~~~~~~~!!!!!7!~:..
//           .....:^~!!77!~~~~~~~!!!!!^!7!:....^^  .. :?PPGGGGGBBBBPYJ^^^^^^JYG####&&&#&@@G?7????JJJ~. :^:.:!777!!!!!!!!!!!!7!~:.....
//         .........:^~!!77!~~~~~~!??JY?!:...  .^^  .. :?PGBBBB####&@&######&&&#######&&#P?7????JJ7~. :^:^!?77777777777!!!7!^:.........
//        ..........:::^~!!77!!~~~~!JJ5J7!:.    .^^. ....~PBB#####&&@@@@@@@@&&########&#J77????J?7:  :^^!?77777777??7!!!7!^:::...........
//      ..........:::::::^~~!7?7~~~~~7JY7!~~^.   .^^. .   ^7?G###&&&@@@@@@@@&&######GJY?77????J?7:  :!!!J?777777??7!!!!~^:::::::..........
//    ..........::::::::^^^^~~?J7!~~~~~??7^757^^. .^^.       :7?PBB#&&&&&&&&&&#BBP?7^!777????J?7..~~?5?!????????7!!!!~^^^^::::::::..........
//   ..........:::::::^^^^^^^^^!???!~~~~!?77J?:~~^^:^:  .       .::!JJJJJJJJJJ!^^^:..777??????!~^7J!JY77JJJJ??7!!!!~^^^^^^^^:::::::..........
//  .........:::::::^^^^^^~~~~^^^!7J?!!~~~77!^:~~!~~~~:...    .  .. .::::::::::::::.^777?77??7~~7J5!!7?JJJJ?7!!!!~^^~~~~^^^^^^:::::::.........
// .........:::::::^^^^^~~~~~~!~~^^!JJ?7!~!!!~^^^~~~~!??!^~^.... .. .:::::::::::::::77???Y5Y7~~?Y5YJJJJJJ??7~!!~~~!!~~~~~~^^^^^:::::::.........
// ........::::::^^^^^^~~~~~!!!!!!!~~!??77!!!~~~~:^~~~!?J???7777~^~^~~~~!!~~~~~~~!7JYYP5PG57^!?Y55YYYJJJJ7!!!~~!!!!!!!~~~~~^^^^^^::::::........
// ......:::::::^^^^^~~~~~~!!!!!7777!~~!??7777!~!~^^~!^!??J??????????555PP5555555J?55P5PP57^!?Y55P5YYYJ?!!!~~!7777!!!!!~~~~~~^^^^^:::::::......
// .....:::::::^^^^^~~~~~!!!!!!77777??7~~!???7?777!^~!!7???77???????JY55GG555555Y??5555PY?77JY55PPP5Y?!!!~!7??777777!!!!!~~~~~^^^^^^::::::.....
// ....::::::^^^^^^~~~~~!!!!!77777??????!^^!?YY??!!!^~!777!^!??7!!!!!7Y5PP5YYYYJ7~Y5P55?7?JJY5555PPY7!!^^!??????77777!!!!!~~~~~^^^^^^::::::....
// ...::::::^^^^^~~~~~!!!!!!77777??77!~~~~^:~7JP5J7^~~!!!7!7??!7777?JJ5YYYYPPP5J77555PJ77?JY555PP5J?7~^^~~~~!77??77777!!!!!!~~~~~^^^^^::::::...
// ..::::::^^^^^~~~~~!!!!!777777!!~~~~~!!!!!~^~?5PY7~~!77!!?7!!7????JJ55555555Y?7JP5YJ?7JJY55555Y?7~^~!!!!!~~~~~!!777777!!!!!~~~~~^^^^^::::::..
// ..::::::^^^^~~~~~!!!!!77!!~~~~~~~~7?JJJ?77!^:~?Y5Y!~!7!^7J7~~!7777?YYYYYYYYJ7?55J7JJ7J55555Y?!^:^!77?JJJ?7~~~~~~~~!!77!!!!!~~~~~^^^^^:::::..
// .::::::^^^^^~~~~!!!!!!!^^^^^^~!!7777JJY?77!!~^.^7YY?~^!!^?J7~^^!77?YYYYYYYY7~75Y7JJ?JY555Y?!^:^~!!77?YJJ7777!!~^^^^^^!!!!!!!~~~~^^^^^::::::.
// ::::::^^^^^~~~~~!!!!7!:!!^:^~~!!!7!777?JJ?77!~.::^7JJ7^^~~~????77?Y5PP5P55Y7?5Y?J???Y55Y?!^:::~!77?JJ?777!7!!!~~^:^!!^!7!!!!~~~~~^^^^^::::::
// :::::^^^^^~~~~~!!!!77!:J?!^^^~~~!!!!!777??777~.^^::^7YJ!^^!!77!!7JJY555555J7!!77J??JYY?!^::^^:!777??777!!!!!~~~^^^!?J^!77!!!!~~~~~^^^^^:::::
// :::::^^^^^~~~~!!!!!777~^!???7~^~~~!!!!!777777!.^~~~^^~?J!~^~~~!7??JJ55555Y?77!!???J?~^^:^~~~^:!777777!!!!!~~~^~7???!^~777!!!!!~~~~^^^^^:::::
// ::::^^^^^~~~~~!!!!77777~^^~!??7~^~~~~~!!!!!777!.^!!~!!^^!?7!77!~!?JJ5555YJ7~^7JJJ!~:.:!!~!!^:!777!!!!!~~~~~^~7??!~^^~77777!!!!~~~~~^^^^^::::
// ::::^^^^^~~~~!!!!!7777??7!^^^!??7~^~~~~~~!!!!!!.^~!!7??^.^!????????YPPPPJ~^~7JJ?!^:.^??7!!~^:!!!!!!~~~~~~^~7??!^^^!7??7777!!!!!~~~~^^^^^::::
// ::::^^^^~~~~~!!!!77777777??~^^^~7?7~^~^~~~~!~!~.:!!7!75J::::!7????7?PPP5!^~7777~::::J57!7!!^:!!~!~~~~^~^~7?7~^^^~??77777777!!!!~~~~~^^^^::::
// :::^^^^^~~~~!!!!!~~~^:::^^~7^:^^^~7?7!^^^^~~~~~..!!!77?5J:^^::~7?J?7JPPJ:~77!^::^^:J5?77!!!..~~~~~^^^^!7?7~^^^^~7~^^:::^~~~!!!!!~~~~^^^^^:::
// ::::^^^^~~~~!!!~^^^^~^^^^:.::::^~^:~7??!^::^^^: :~!!!77?5J:^~~::~?JJ?P5~!??~::~~^:J5?77!!!~: :^^^::^!??7~:^~^::::.:^^^^~^^^^~!!!~~~~^^^^::::
// ::::::^^~~~~!!~^^^~~~~^^^^:.::::^~^::~7??!^::::.::!7!!!7?5J^^~!!~^~?YPP?7~^~!!~^^J5?7!!!7!::.::::^!??7~::^~^::::.:^^^^~~~~^^^~!!~~~~^^::::::
// ^^^^~~^^^^~~!~:^^~~!~~~^^^^:.::^~~^^:::^!??!:~!~::^!!!!!7?5J^^~!77~^~??~^~77!~^^J5?7!!!!!^::~!~:!??!^:::^^~~^::.:^^^^~~~!~~^^:~!~~^^^^~~^^^^
// ^^^~~^:^^^^^~:^^~~!!!!!!!~~~^::~^^^^^^:::!J?!^!7!^::~!!!!7?5Y!^~!!7!~^^~!7!!~^!Y5?7!!!!~::^!7!^!?J!:::^^^^^^~::^~~~!!!!!!!~~^^:~^^^^::^~~^^^
// !!~!7^.::^^::.^~~!!!!!77?JJJJ?!~^::^^^^^^~7?~:!!77!^^~~!!!7?J5Y7~^^~!~~!~^^~7Y5J?7!!!~~^^!77!!:~?7~^^^^^^::^~!?JJJJ?77!!!!!~~^.::^^::.^7!~!!
// 777J?:.:^^^...:^~!!!7Y??7?777???!.:^~^^^~!~~!!!!!!7?7~^^^~~!77?JJ??~~~~~~??JJ?77!~~^^^~7?7!!!!!!~~!~^^^~^:.!??7777?7??Y7!!!~^:...^^^:.:?J777
// !!7Y?::!77~:^^:.:^~7J??!!!7^~!!77~.:~7~~~~^^?J?!^^~~!7??!~^^^~~!!7????????7!!~~^^^~!??7!~~^^!?J?^^~~~~7~:.~777~^~~7!!??J7~^:.:^^:~77!::?Y7!!
// !!7Y?::!!~:~?7~^:::^~~7!!7!^~~~7!!~.:~!!~~~^^^~: .:^^^^~~!7!~~~^:^^^^^^^^^^:^~~~!7!~~^^^^:. :~^^^~~~!!~:.~!!7!^~!~~7!7~~^:::^~7?~:~!!::?Y7!!
// ?77?Y7^:^:~!??J?7!^::^~!!!~~~~!!!!~^.:^7?!~~^^^^::.:^^~!!~~~~~~^^^^^^^^^^^^^^~~~~~~!!~^^:.::^^^^~~!?7^:.^~!!!!~~~~!!!~^::^!7?J??!~:^:^7Y?77?
// ??!7YJ^.:^!7???YYJ?7~~^^~~7!!!~~~~~~^::^~7??777!~!^^^^:::^~~~!!!!!!!!!!!!!!!!!!~~~^:::^^^^!~!777??7~^::^~~~~~~!!!7~~^^~~7?JYY???7!^:.^JY7!??
// ??77YJ~.^~!77?JJJYYYYJ7!^^^~!777!!~~~~^::^^~!77????77?7!!~~~~^::::::::::::::::^~~~~!!7?77????77!~^^::^~~~~!!777!~^^^!7JYYYYJJJ?77!~^.~JY77??
// J??77YJ~.^!!!JJ??777??YYJJ7!~^^~!77!~~~~~~~^^^^^~~!7777??????777777777777777777??????7777!~~^^^^^~~~~~~~!77!~^^~!7JJYY??777??JJ!!!^.~JY77??J
// YY?77JY!:^!!!YJ?7!!!~~!!??JYJJ7!~^~~!!!~!!!!7777~~~~^^^~~~~~!777777777777777777!~~~~~^^^~~~~7777!!!!~!!!~~^~!7JJYJ??!!~~!!!7?JY!!!^:!YJ77?YY
// YYJ?77JY!:~!!?Y?7!!!~~~~~~!!7?JYJ?7~^^~~!!!!7????????777777~~~~~~~~~~~~~~~~~~~~~~777777????????7!!!!~~^^~7?JYJ?7!!~~~~~~!!!7?Y?!!~:!YJ77?JYY
// YJYJJ?7?J?^:!!?J?!!!~~~~~~~~~~~!7JJYY?~^^~!!77!7777?????????JJJJJJJJJJJJJJJJJJJJ?????????7777!77!!~^^~?YYJJ7!~~~~~~~~~~~!!!?J?!!:^?J?7?JJYJY
contract Infiltration is
    IInfiltration,
    OwnableTwoSteps,
    ERC721A,
    VRFConsumerBaseV2,
    LowLevelERC20Transfer,
    LowLevelWETH,
    ProtocolFee,
    PackableReentrancyGuard
{
    using UnsafeMathUint256 for uint256;

    /**
     * @notice When the frontrun lock is unlocked, agents can escape or heal.
     */
    uint8 private constant FRONTRUN_LOCK__UNLOCKED = 1;

    /**
     * @notice When the frontrun lock is locked, agents cannot escape or heal.
     */
    uint8 private constant FRONTRUN_LOCK__LOCKED = 2;

    /**
     * @notice When VRF is being requested, agents cannot escape or heal. It unlocks when the randomness is fulfilled.
     * @dev frontrunLock is initially set as locked so that agents cannot escape or heal before the game starts.
     *      It is unlocked when the first round's randomness is fulfilled.
     */
    uint8 private frontrunLock = FRONTRUN_LOCK__LOCKED;

    /**
     * @notice 100% in basis points.
     */
    uint256 private constant ONE_HUNDRED_PERCENT_IN_BASIS_POINTS = 10_000;

    /**
     * @notice 100% in basis points squared.
     */
    uint256 private constant ONE_HUNDRED_PERCENT_IN_BASIS_POINTS_SQUARED = 10_000 ** 2;

    /**
     * @notice The number of secondary prize pool winners. Their entitled shares are based on their placements.
     *         When the number of active agents is less than or equal to this number, 1 agent is instantly killed
     *         in each round.
     */
    uint256 private constant NUMBER_OF_SECONDARY_PRIZE_POOL_WINNERS = 50;

    uint256 private constant PROBABILITY_PRECISION = 100_000_000;

    /**
     * @notice Max agent supply.
     */
    uint256 public immutable MAX_SUPPLY;

    /**
     * @notice Max mint per address.
     */
    uint256 public immutable MAX_MINT_PER_ADDRESS;

    /**
     * @notice The price of minting 1 agent.
     */
    uint256 public immutable PRICE;

    /**
     * @notice The number of blocks per round.
     */
    uint256 public immutable BLOCKS_PER_ROUND;

    /**
     * @notice The percentage of agents to wound per round in basis points.
     */
    uint256 public immutable AGENTS_TO_WOUND_PER_ROUND_IN_BASIS_POINTS;

    /**
     * @notice The number of rounds for agents to be wounded before getting killed.
     */
    uint256 public immutable ROUNDS_TO_BE_WOUNDED_BEFORE_DEAD;

    /**
     * @notice This value is used as the denominator in healProbability.
     */
    uint256 private immutable ROUNDS_TO_BE_WOUNDED_BEFORE_DEAD_MINUS_ONE;

    /**
     * @notice This value is used as the minuend in healProbability.
     */
    uint256 private immutable HEAL_PROBABILITY_MINUEND;

    /**
     * @notice The base cost of healing an agent. The cost increases for each successful heal.
     */
    uint256 public immutable HEAL_BASE_COST;

    /**
     * @notice WETH address.
     */
    address private immutable WETH;

    /**
     * @notice LOOKS address.
     */
    address private immutable LOOKS;

    /**
     * @notice Chainlink VRF key hash.
     */

    bytes32 private immutable KEY_HASH;

    /**
     * @notice Chainlink VRF coordinator.
     */
    VRFCoordinatorV2Interface private immutable VRF_COORDINATOR;

    /**
     * @notice Chainlink VRF subscription ID.
     */
    uint64 private immutable SUBSCRIPTION_ID;

    /**
     * @notice The transfer manager contract that manages LOOKS approvals.
     */
    ITransferManager private immutable TRANSFER_MANAGER;

    /**
     * @notice The timestamp at which the mint period starts.
     */
    uint40 public mintStart;

    /**
     * @notice The timestamp at which the mint period ends.
     */
    uint40 public mintEnd;

    /**
     * @notice The bitmap of the placements of the secondary prize pool winners.
     * @dev Only bit 1 to 50 are used. Bit 0 is not used.
     */
    uint56 private prizesClaimedBitmap;

    /**
     * @notice The base URI of the collection.
     */
    string private baseURI;

    /**
     * @notice Amount of agents minted per address.
     */
    mapping(address minter => uint256 amount) public amountMintedPerAddress;

    /**
     * @notice Chainlink randomness requests.
     */
    mapping(uint256 requestId => RandomnessRequest) public randomnessRequests;

    /**
     * @notice The mapping agents acts as an "array". In the beginning of the game, the "length" of the "array"
     *         is the total supply. As the game progresses, the "length" of the "array" decreases
     *         as agents are killed. The function agentsAlive() returns the "length" of the "array".
     *
     *         When an Agent struct has 0 value for every field with its index within the total supply,
     *         it means that the agent is active.
     *
     *         Index 0 is not used as agent ID starts from 1.
     */
    mapping(uint256 index => Agent) private agents;

    /**
     * @notice It is used to find the index of an agent in the agents mapping given its agent ID.
     *         If the index is 0, it means the agent's index is the same as its agent ID as no swaps
     *         have been made.
     */
    mapping(uint256 agentId => uint256 index) private agentIdToIndex;

    /**
     * @notice The maximum healing or wounded agents allowed per round.
     */
    uint256 private constant MAXIMUM_HEALING_OR_WOUNDED_AGENTS_PER_ROUND = 30;

    /**
     * @notice The maximum healing or wounded agents allowed per round + 1 for storing the array length.
     */
    uint256 private constant MAXIMUM_HEALING_OR_WOUNDED_AGENTS_PER_ROUND_AND_LENGTH = 31;

    /**
     * @notice The first element of the array is the length of the array.
     */
    mapping(uint256 roundId => uint16[MAXIMUM_HEALING_OR_WOUNDED_AGENTS_PER_ROUND_AND_LENGTH] agentIds)
        private woundedAgentIdsPerRound;

    /**
     * @notice The first element of the array is the length of the array.
     */
    mapping(uint256 roundId => uint16[MAXIMUM_HEALING_OR_WOUNDED_AGENTS_PER_ROUND_AND_LENGTH] agentIds)
        private healingAgentIdsPerRound;

    /**
     * @notice Game information.
     */
    GameInfo public gameInfo;

    /**
     * @dev Agent struct status offset for bitwise operations.
     */
    uint256 private constant AGENT__STATUS_OFFSET = 16;

    /**
     * @dev Agent struct wounded at offset for bitwise operations.
     */
    uint256 private constant AGENT__WOUNDED_AT_OFFSET = 24;

    /**
     * @dev Agent struct heal count offset for bitwise operations.
     */
    uint256 private constant AGENT__HEAL_COUNT_OFFSET = 64;

    /**
     * @dev GameInfo struct wounded agents offset for bitwise operations.
     */
    uint256 private constant GAME_INFO__WOUNDED_AGENTS_OFFSET = 16;

    /**
     * @dev GameInfo struct healing agents offset for bitwise operations.
     */
    uint256 private constant GAME_INFO__HEALING_AGENTS_OFFSET = 32;

    /**
     * @dev GameInfo struct dead agents offset for bitwise operations.
     */
    uint256 private constant GAME_INFO__DEAD_AGENTS_OFFSET = 48;

    /**
     * @dev GameInfo struct escaped agents offset for bitwise operations.
     */
    uint256 private constant GAME_INFO__ESCAPED_AGENTS_OFFSET = 64;

    /**
     * @dev GameInfo struct current round ID offset for bitwise operations.
     */
    uint256 private constant GAME_INFO__CURRENT_ROUND_ID_OFFSET = 80;

    /**
     * @dev GameInfo struct current round block number offset for bitwise operations.
     */
    uint256 private constant GAME_INFO__CURRENT_ROUND_BLOCK_NUMBER_OFFSET = 120;

    /**
     * @dev RandomnessRequest struct exists offset for bitwise operations.
     */
    uint256 private constant RANDOMNESS_REQUESTS__EXISTS_OFFSET = 8;

    /**
     * @dev 2 bytes bitmask.
     */
    uint256 private constant TWO_BYTES_BITMASK = 0xffff;

    /**
     * @dev 5 bytes bitmask.
     */
    uint256 private constant FIVE_BYTES_BITMASK = 0xffffffffff;

    /**
     * @param constructorCalldata Constructor calldata. See IInfiltration.ConstructorCalldata for its key values.
     */
    constructor(
        ConstructorCalldata memory constructorCalldata
    )
        OwnableTwoSteps(constructorCalldata.owner)
        ERC721A(constructorCalldata.name, constructorCalldata.symbol)
        VRFConsumerBaseV2(constructorCalldata.vrfCoordinator)
    {
        if (
            constructorCalldata.maxSupply <= NUMBER_OF_SECONDARY_PRIZE_POOL_WINNERS ||
            constructorCalldata.maxSupply > type(uint16).max
        ) {
            revert InvalidMaxSupply();
        }

        if (
            (constructorCalldata.maxSupply * constructorCalldata.agentsToWoundPerRoundInBasisPoints) >
            MAXIMUM_HEALING_OR_WOUNDED_AGENTS_PER_ROUND * ONE_HUNDRED_PERCENT_IN_BASIS_POINTS
        ) {
            revert WoundedAgentIdsPerRoundExceeded();
        }

        if (constructorCalldata.roundsToBeWoundedBeforeDead < 3) {
            revert RoundsToBeWoundedBeforeDeadTooLow();
        }

        PRICE = constructorCalldata.price;
        MAX_SUPPLY = constructorCalldata.maxSupply;
        MAX_MINT_PER_ADDRESS = constructorCalldata.maxMintPerAddress;
        BLOCKS_PER_ROUND = constructorCalldata.blocksPerRound;
        AGENTS_TO_WOUND_PER_ROUND_IN_BASIS_POINTS = constructorCalldata.agentsToWoundPerRoundInBasisPoints;
        ROUNDS_TO_BE_WOUNDED_BEFORE_DEAD = constructorCalldata.roundsToBeWoundedBeforeDead;

        // The next 2 values are used in healProbability
        ROUNDS_TO_BE_WOUNDED_BEFORE_DEAD_MINUS_ONE = ROUNDS_TO_BE_WOUNDED_BEFORE_DEAD.unsafeSubtract(1);
        HEAL_PROBABILITY_MINUEND =
            ((ROUNDS_TO_BE_WOUNDED_BEFORE_DEAD * 99 - 80) * PROBABILITY_PRECISION) /
            ROUNDS_TO_BE_WOUNDED_BEFORE_DEAD_MINUS_ONE;

        LOOKS = constructorCalldata.looks;
        HEAL_BASE_COST = constructorCalldata.healBaseCost;

        KEY_HASH = constructorCalldata.keyHash;
        VRF_COORDINATOR = VRFCoordinatorV2Interface(constructorCalldata.vrfCoordinator);
        SUBSCRIPTION_ID = constructorCalldata.subscriptionId;

        TRANSFER_MANAGER = ITransferManager(constructorCalldata.transferManager);
        WETH = constructorCalldata.weth;

        baseURI = constructorCalldata.baseURI;

        _updateProtocolFeeRecipient(constructorCalldata.protocolFeeRecipient);
        _updateProtocolFeeBp(constructorCalldata.protocolFeeBp);
    }

    /**
     * @dev updateProtocolFeeBp is not implemented in this contract.
     */
    function updateProtocolFeeBp(uint16) external pure override {
        revert Immutable();
    }

    /**
     * @dev updateProtocolFeeRecipient is not implemented in this contract.
     */
    function updateProtocolFeeRecipient(address) external pure override {
        revert Immutable();
    }

    /**
     * @inheritdoc IInfiltration
     */
    function setMintPeriod(uint40 newMintStart, uint40 newMintEnd) external onlyOwner {
        if (newMintStart >= newMintEnd) {
            revert InvalidMintPeriod();
        }

        if (newMintStart != 0) {
            if (block.timestamp > newMintStart) {
                revert MintStartIsInThePast();
            }

            uint256 currentMintStart = mintStart;
            if (currentMintStart != 0) {
                if (block.timestamp >= currentMintStart) {
                    revert MintAlreadyStarted();
                }
            }

            mintStart = newMintStart;
        }

        if (block.timestamp > newMintEnd || newMintEnd < mintEnd) {
            revert MintCanOnlyBeExtended();
        }

        mintEnd = newMintEnd;

        emit MintPeriodUpdated(newMintStart == 0 ? mintStart : newMintStart, newMintEnd);
    }

    /**
     * @inheritdoc IInfiltration
     * @notice As long as the game has not started (after mint end), the owner can still mint.
     */
    function premint(address to, uint256 quantity) external payable onlyOwner {
        _assertExactNativeTokensSupplied(quantity);
        _assertTotalSupplyNotBreached(quantity);
        _assertGameNotYetBegun();
        _mintERC2309(to, quantity);
    }

    /**
     * @inheritdoc IInfiltration
     */
    function mint(uint256 quantity) external payable nonReentrant {
        if (block.timestamp < mintStart || block.timestamp > mintEnd) {
            revert NotInMintPeriod();
        }

        _assertGameNotYetBegun();

        uint256 amountMinted = amountMintedPerAddress[msg.sender] + quantity;
        if (amountMinted > MAX_MINT_PER_ADDRESS) {
            revert TooManyMinted();
        }

        _assertExactNativeTokensSupplied(quantity);
        _assertTotalSupplyNotBreached(quantity);

        amountMintedPerAddress[msg.sender] = amountMinted;
        _mintERC2309(msg.sender, quantity);
    }

    /**
     * @inheritdoc IInfiltration
     * @dev If Chainlink randomness callback does not come back after 1 day, we can call
     *      startNewRound to trigger a new randomness request.
     */
    function startGame() external onlyOwner {
        uint256 numberOfAgents = totalSupply();
        if (numberOfAgents < MAX_SUPPLY) {
            if (block.timestamp < mintEnd) {
                revert StillMinting();
            }
        }
        if (numberOfAgents < NUMBER_OF_SECONDARY_PRIZE_POOL_WINNERS) {
            revert NotEnoughMinted();
        }

        _assertGameNotYetBegun();

        gameInfo.currentRoundId = 1;
        gameInfo.activeAgents = uint16(numberOfAgents);
        uint256 balance = address(this).balance;
        uint256 protocolFee = balance.unsafeMultiply(protocolFeeBp).unsafeDivide(ONE_HUNDRED_PERCENT_IN_BASIS_POINTS);
        unchecked {
            gameInfo.prizePool = balance - protocolFee;
        }

        emit RoundStarted(1);

        _transferETHAndWrapIfFailWithGasLimit(WETH, protocolFeeRecipient, protocolFee, gasleft());
        _requestForRandomness();
    }

    /**
     * @inheritdoc IInfiltration
     */
    function emergencyWithdraw() external onlyOwner {
        uint256 activeAgents;
        uint256 woundedAgents;
        uint256 healingAgents;
        uint256 escapedAgents;
        uint256 deadAgents;
        uint256 currentRoundId;
        uint256 currentRoundBlockNumber;

        assembly {
            let gameInfoSlot0Value := sload(gameInfo.slot)
            activeAgents := and(gameInfoSlot0Value, TWO_BYTES_BITMASK)
            woundedAgents := and(shr(GAME_INFO__WOUNDED_AGENTS_OFFSET, gameInfoSlot0Value), TWO_BYTES_BITMASK)
            healingAgents := and(shr(GAME_INFO__HEALING_AGENTS_OFFSET, gameInfoSlot0Value), TWO_BYTES_BITMASK)
            escapedAgents := and(shr(GAME_INFO__ESCAPED_AGENTS_OFFSET, gameInfoSlot0Value), TWO_BYTES_BITMASK)
            deadAgents := and(shr(GAME_INFO__DEAD_AGENTS_OFFSET, gameInfoSlot0Value), TWO_BYTES_BITMASK)
            currentRoundId := and(shr(GAME_INFO__CURRENT_ROUND_ID_OFFSET, gameInfoSlot0Value), FIVE_BYTES_BITMASK)
            currentRoundBlockNumber := and(
                shr(GAME_INFO__CURRENT_ROUND_BLOCK_NUMBER_OFFSET, gameInfoSlot0Value),
                FIVE_BYTES_BITMASK
            )
        }

        bool conditionOne = currentRoundId != 0 &&
            activeAgents + woundedAgents + healingAgents + escapedAgents + deadAgents != totalSupply();

        // 50 blocks per round * 216 = 10,800 blocks which is roughly 36 hours
        // Prefer not to hard code this number as BLOCKS_PER_ROUND is not always 50
        bool conditionTwo = currentRoundId != 0 &&
            activeAgents > 1 &&
            block.number > currentRoundBlockNumber + BLOCKS_PER_ROUND * 216;

        // Just in case startGame reverts, we can withdraw the ETH balance and redistribute to addresses that participated in the mint.
        bool conditionThree = currentRoundId == 0 && block.timestamp > uint256(mintEnd).unsafeAdd(36 hours);

        if (conditionOne || conditionTwo || conditionThree) {
            uint256 ethBalance = address(this).balance;
            _transferETHAndWrapIfFailWithGasLimit(WETH, msg.sender, ethBalance, gasleft());

            uint256 looksBalance = IERC20(LOOKS).balanceOf(address(this));
            _executeERC20DirectTransfer(LOOKS, msg.sender, looksBalance);

            emit EmergencyWithdrawal(ethBalance, looksBalance);
        }
    }

    /**
     * @inheritdoc IInfiltration
     * @dev If Chainlink randomness callback does not come back after 1 day, we can try by calling
     *      startNewRound again.
     */
    function startNewRound() external nonReentrant {
        uint256 currentRoundId = gameInfo.currentRoundId;
        if (currentRoundId == 0) {
            revert GameNotYetBegun();
        }

        if (block.number < uint256(gameInfo.currentRoundBlockNumber).unsafeAdd(BLOCKS_PER_ROUND)) {
            revert TooEarlyToStartNewRound();
        }

        if (block.timestamp < uint256(gameInfo.randomnessLastRequestedAt).unsafeAdd(1 days)) {
            revert TooEarlyToRetryRandomnessRequest();
        }

        uint256 agentsRemaining = agentsAlive();
        uint256 activeAgents = gameInfo.activeAgents;
        if (agentsRemaining == 1) {
            if (activeAgents == 1) {
                revert GameOver();
            }
        }

        if (activeAgents <= NUMBER_OF_SECONDARY_PRIZE_POOL_WINNERS) {
            uint256 woundedAgents = gameInfo.woundedAgents;

            if (woundedAgents != 0) {
                uint256 killRoundId = currentRoundId > ROUNDS_TO_BE_WOUNDED_BEFORE_DEAD
                    ? currentRoundId.unsafeSubtract(ROUNDS_TO_BE_WOUNDED_BEFORE_DEAD)
                    : 1;
                uint256 totalDeadAgentsFromKilling;
                while (woundedAgentIdsPerRound[killRoundId][0] != 0) {
                    uint256 deadAgentsFromKilling = _killWoundedAgents({
                        currentRoundId: currentRoundId,
                        roundId: killRoundId,
                        currentRoundAgentsAlive: agentsRemaining
                    });
                    unchecked {
                        totalDeadAgentsFromKilling += deadAgentsFromKilling;
                        agentsRemaining -= deadAgentsFromKilling;
                        ++killRoundId;
                    }
                }

                // This is equivalent to
                // unchecked {
                //     gameInfo.deadAgents += uint16(totalDeadAgentsFromKilling);
                // }
                // gameInfo.woundedAgents = 0;
                assembly {
                    let gameInfoSlot0Value := sload(gameInfo.slot)
                    let deadAgents := and(shr(GAME_INFO__DEAD_AGENTS_OFFSET, gameInfoSlot0Value), TWO_BYTES_BITMASK)

                    gameInfoSlot0Value := and(
                        gameInfoSlot0Value,
                        // This is equivalent to
                        // not(
                        //     or(
                        //         shl(GAME_INFO__WOUNDED_AGENTS_OFFSET, TWO_BYTES_BITMASK),
                        //         shl(GAME_INFO__DEAD_AGENTS_OFFSET, TWO_BYTES_BITMASK)
                        //     )
                        // )
                        0xffffffffffffffffffffffffffffffffffffffffffffffff0000ffff0000ffff
                    )

                    gameInfoSlot0Value := or(
                        gameInfoSlot0Value,
                        shl(GAME_INFO__DEAD_AGENTS_OFFSET, add(deadAgents, totalDeadAgentsFromKilling))
                    )

                    sstore(gameInfo.slot, gameInfoSlot0Value)
                }
            }

            if (agentsRemaining > 1) {
                _requestForRandomness();
            } else {
                _emitWonEventIfOnlyOneAgentRemaining(agentsRemaining, activeAgents);
            }
        } else {
            _requestForRandomness();
        }
    }

    /**
     * @inheritdoc IInfiltration
     */
    function claimGrandPrize() external nonReentrant {
        _assertGameOver();
        uint256 agentId = _agentIndexToId(agents[1], 1);
        _assertAgentOwnership(agentId);

        uint256 prizePool = gameInfo.prizePool;

        if (prizePool == 0) {
            revert NothingToClaim();
        }

        gameInfo.prizePool = 0;

        _transferETHAndWrapIfFailWithGasLimit(WETH, msg.sender, prizePool, gasleft());

        emit PrizeClaimed(agentId, address(0), prizePool);
    }

    /**
     * @inheritdoc IInfiltration
     */
    function claimSecondaryPrizes(uint256 agentId) external nonReentrant {
        _assertGameOver();
        _assertAgentOwnership(agentId);

        uint256 placement = agentIndex(agentId);
        _assertValidPlacement(placement);

        uint56 _prizesClaimedBitmap = prizesClaimedBitmap;
        if ((_prizesClaimedBitmap >> placement) & 1 != 0) {
            revert NothingToClaim();
        }

        prizesClaimedBitmap = _prizesClaimedBitmap | uint56(1 << placement);

        uint256 ethAmount = secondaryPrizePoolShareAmount(gameInfo.secondaryPrizePool, placement);
        if (ethAmount != 0) {
            _transferETHAndWrapIfFailWithGasLimit(WETH, msg.sender, ethAmount, gasleft());
            emit PrizeClaimed(agentId, address(0), ethAmount);
        }

        uint256 secondaryLooksPrizePool = gameInfo.secondaryLooksPrizePool;
        if (secondaryLooksPrizePool == 0) {
            secondaryLooksPrizePool = IERC20(LOOKS).balanceOf(address(this));
            if (secondaryLooksPrizePool == 0) {
                return;
            }
            gameInfo.secondaryLooksPrizePool = secondaryLooksPrizePool;
        }

        uint256 looksAmount = secondaryPrizePoolShareAmount(secondaryLooksPrizePool, placement);
        if (looksAmount != 0) {
            _executeERC20DirectTransfer(LOOKS, msg.sender, looksAmount);
            emit PrizeClaimed(agentId, LOOKS, looksAmount);
        }
    }

    /**
     * @inheritdoc IInfiltration
     */
    function escape(uint256[] calldata agentIds) external nonReentrant {
        _assertFrontrunLockIsOff();

        uint256 agentIdsCount = agentIds.length;
        _assertNotEmptyAgentIdsArrayProvided(agentIdsCount);

        uint256 activeAgents = gameInfo.activeAgents;
        uint256 activeAgentsAfterEscape = activeAgents - agentIdsCount;
        _assertGameIsNotOverAfterEscape(activeAgentsAfterEscape);

        uint256 currentRoundAgentsAlive = agentsAlive();

        uint256 prizePool = gameInfo.prizePool;
        uint256 secondaryPrizePool = gameInfo.secondaryPrizePool;
        uint256 reward;
        uint256[] memory rewards = new uint256[](agentIdsCount);

        for (uint256 i; i < agentIdsCount; ) {
            uint256 agentId = agentIds[i];
            _assertAgentOwnership(agentId);

            uint256 index = agentIndex(agentId);
            _assertAgentStatus(agents[index], agentId, AgentStatus.Active);

            uint256 totalEscapeValue = prizePool / currentRoundAgentsAlive;
            uint256 rewardForPlayer = (totalEscapeValue * _escapeMultiplier(currentRoundAgentsAlive)) /
                ONE_HUNDRED_PERCENT_IN_BASIS_POINTS;
            rewards[i] = rewardForPlayer;
            reward += rewardForPlayer;

            uint256 rewardToSecondaryPrizePool = (totalEscapeValue.unsafeSubtract(rewardForPlayer) *
                _escapeRewardSplitForSecondaryPrizePool(currentRoundAgentsAlive)) / ONE_HUNDRED_PERCENT_IN_BASIS_POINTS;

            unchecked {
                prizePool = prizePool - rewardForPlayer - rewardToSecondaryPrizePool;
            }
            secondaryPrizePool += rewardToSecondaryPrizePool;

            _swap({
                currentAgentIndex: index,
                lastAgentIndex: currentRoundAgentsAlive,
                agentId: agentId,
                newStatus: AgentStatus.Escaped
            });

            unchecked {
                --currentRoundAgentsAlive;
                ++i;
            }
        }

        // This is equivalent to
        // unchecked {
        //     gameInfo.activeAgents = uint16(activeAgentsAfterEscape);
        //     gameInfo.escapedAgents += uint16(agentIdsCount);
        // }
        assembly {
            let gameInfoSlot0Value := sload(gameInfo.slot)
            let escapedAgents := add(
                and(shr(GAME_INFO__ESCAPED_AGENTS_OFFSET, gameInfoSlot0Value), TWO_BYTES_BITMASK),
                agentIdsCount
            )

            gameInfoSlot0Value := and(
                gameInfoSlot0Value,
                // This is the equivalent of not(or(TWO_BYTES_BITMASK, shl(GAME_INFO__ESCAPED_AGENTS_OFFSET, TWO_BYTES_BITMASK)))
                0xffffffffffffffffffffffffffffffffffffffffffff0000ffffffffffff0000
            )
            gameInfoSlot0Value := or(gameInfoSlot0Value, activeAgentsAfterEscape)
            gameInfoSlot0Value := or(gameInfoSlot0Value, shl(GAME_INFO__ESCAPED_AGENTS_OFFSET, escapedAgents))
            sstore(gameInfo.slot, gameInfoSlot0Value)
        }

        gameInfo.prizePool = prizePool;
        gameInfo.secondaryPrizePool = secondaryPrizePool;

        _transferETHAndWrapIfFailWithGasLimit(WETH, msg.sender, reward, gasleft());
        emit Escaped(gameInfo.currentRoundId, agentIds, rewards);

        _emitWonEventIfOnlyOneAgentRemaining(currentRoundAgentsAlive, activeAgentsAfterEscape);
    }

    /**
     * @inheritdoc IInfiltration
     */
    function heal(uint256[] calldata agentIds) external nonReentrant {
        _assertFrontrunLockIsOff();

        if (gameInfo.activeAgents <= NUMBER_OF_SECONDARY_PRIZE_POOL_WINNERS) {
            revert HealingDisabled();
        }

        uint256 agentIdsCount = agentIds.length;
        _assertNotEmptyAgentIdsArrayProvided(agentIdsCount);

        uint256 currentRoundId = gameInfo.currentRoundId;
        uint16[MAXIMUM_HEALING_OR_WOUNDED_AGENTS_PER_ROUND_AND_LENGTH]
            storage healingAgentIds = healingAgentIdsPerRound[currentRoundId];
        uint256 currentHealingAgentIdsCount = healingAgentIds[0];

        uint256 newHealingAgentIdsCount = currentHealingAgentIdsCount.unsafeAdd(agentIdsCount);

        if (newHealingAgentIdsCount > MAXIMUM_HEALING_OR_WOUNDED_AGENTS_PER_ROUND) {
            revert MaximumHealingRequestPerRoundExceeded();
        }

        uint256 cost;
        uint256[] memory costs = new uint256[](agentIdsCount);

        for (uint256 i; i < agentIdsCount; ) {
            uint256 agentId = agentIds[i];

            uint256 index = agentIndex(agentId);
            _assertAgentStatus(agents[index], agentId, AgentStatus.Wounded);

            bytes32 agentSlot = _getAgentStorageSlot(index);
            uint256 agentSlotValue;
            uint256 woundedAt;

            // This is equivalent to
            // uint256 woundedAt = agent.woundedAt;
            assembly {
                agentSlotValue := sload(agentSlot)
                woundedAt := and(shr(AGENT__WOUNDED_AT_OFFSET, agentSlotValue), FIVE_BYTES_BITMASK)
            }

            // This is equivalent to
            // healCount = agent.healCount;
            // agent.status = AgentStatus.Healing;
            uint256 healCount;
            assembly {
                healCount := and(shr(AGENT__HEAL_COUNT_OFFSET, agentSlotValue), TWO_BYTES_BITMASK)

                agentSlotValue := and(
                    agentSlotValue,
                    // This is the equivalent of not(shl(AGENT__STATUS_OFFSET, 0xff))
                    0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ffff
                )
                agentSlotValue := or(
                    agentSlotValue,
                    // AgentStatus.Healing is 2
                    // This is equivalent to shl(AGENT__STATUS_OFFSET, 2)
                    0x20000
                )
                sstore(agentSlot, agentSlotValue)
            }

            costs[i] = _costToHeal(healCount);
            cost += costs[i];

            unchecked {
                ++i;
                healingAgentIds[currentHealingAgentIdsCount + i] = uint16(agentId);
            }
        }

        healingAgentIds[0] = uint16(newHealingAgentIdsCount);

        // This is equivalent to
        // unchecked {
        //     gameInfo.healingAgents += uint16(agentIdsCount);
        //     gameInfo.woundedAgents -= uint16(agentIdsCount);
        // }
        assembly {
            let gameInfoSlot0Value := sload(gameInfo.slot)
            let healingAgents := add(
                and(shr(GAME_INFO__HEALING_AGENTS_OFFSET, gameInfoSlot0Value), TWO_BYTES_BITMASK),
                agentIdsCount
            )
            let woundedAgents := sub(
                and(shr(GAME_INFO__WOUNDED_AGENTS_OFFSET, gameInfoSlot0Value), TWO_BYTES_BITMASK),
                agentIdsCount
            )

            gameInfoSlot0Value := and(
                gameInfoSlot0Value,
                // This is equivalent to
                // not(
                //     or(
                //         shl(GAME_INFO__HEALING_AGENTS_OFFSET, TWO_BYTES_BITMASK),
                //         shl(GAME_INFO__WOUNDED_AGENTS_OFFSET, TWO_BYTES_BITMASK)
                //     )
                // )
                0xffffffffffffffffffffffffffffffffffffffffffffffffffff00000000ffff
            )
            gameInfoSlot0Value := or(gameInfoSlot0Value, shl(GAME_INFO__HEALING_AGENTS_OFFSET, healingAgents))
            gameInfoSlot0Value := or(gameInfoSlot0Value, shl(GAME_INFO__WOUNDED_AGENTS_OFFSET, woundedAgents))
            sstore(gameInfo.slot, gameInfoSlot0Value)
        }

        TRANSFER_MANAGER.transferERC20(LOOKS, msg.sender, address(this), cost);
        _executeERC20DirectTransfer(LOOKS, 0x000000000000000000000000000000000000dEaD, cost / 4);

        emit HealRequestSubmitted(currentRoundId, agentIds, costs);
    }

    /**
     * @notice Only active and wounded agents are allowed to be transferred or traded.
     * @param from The current owner of the token.
     * @param to The new owner of the token.
     * @param tokenId The token ID.
     */
    function transferFrom(address from, address to, uint256 tokenId) public payable override {
        AgentStatus status = agents[agentIndex(tokenId)].status;
        if (status > AgentStatus.Wounded) {
            revert InvalidAgentStatus(tokenId, status);
        }
        super.transferFrom(from, to, tokenId);
    }

    /**
     * @inheritdoc IInfiltration
     */
    function getAgent(uint256 index) external view returns (Agent memory agent) {
        agent = agents[index];
        agent.agentId = uint16(_agentIndexToId(agents[index], index));
    }

    /**
     * @inheritdoc IInfiltration
     * @dev Unlike the actual heal function, this function does not revert if duplicated agent IDs are provided.
     */
    function costToHeal(uint256[] calldata agentIds) external view returns (uint256 cost) {
        uint256 agentIdsCount = agentIds.length;

        for (uint256 i; i < agentIdsCount; ) {
            uint256 agentId = agentIds[i];
            Agent storage agent = agents[agentIndex(agentId)];
            _assertAgentStatus(agent, agentId, AgentStatus.Wounded);

            cost += _costToHeal(agent.healCount);

            unchecked {
                ++i;
            }
        }
    }

    /**
     * @inheritdoc IInfiltration
     * @dev Unlike the actual escape function, this function does not revert if duplicated agent IDs are provided.
     */
    function escapeReward(uint256[] calldata agentIds) external view returns (uint256 reward) {
        uint256 agentIdsCount = agentIds.length;
        _assertGameIsNotOverAfterEscape(gameInfo.activeAgents - agentIdsCount);

        uint256 currentRoundAgentsAlive = agentsAlive();

        uint256 prizePool = gameInfo.prizePool;
        uint256 secondaryPrizePool = gameInfo.secondaryPrizePool;

        for (uint256 i; i < agentIdsCount; ) {
            uint256 agentId = agentIds[i];

            uint256 index = agentIndex(agentId);
            _assertAgentStatus(agents[index], agentId, AgentStatus.Active);

            uint256 totalEscapeValue = prizePool / currentRoundAgentsAlive;
            uint256 rewardForPlayer = (totalEscapeValue * _escapeMultiplier(currentRoundAgentsAlive)) /
                ONE_HUNDRED_PERCENT_IN_BASIS_POINTS;
            reward += rewardForPlayer;

            uint256 rewardToSecondaryPrizePool = (totalEscapeValue.unsafeSubtract(rewardForPlayer) *
                _escapeRewardSplitForSecondaryPrizePool(currentRoundAgentsAlive)) / ONE_HUNDRED_PERCENT_IN_BASIS_POINTS;

            secondaryPrizePool += rewardToSecondaryPrizePool;

            unchecked {
                prizePool = prizePool - rewardForPlayer - rewardToSecondaryPrizePool;
                --currentRoundAgentsAlive;
                ++i;
            }
        }
    }

    /**
     * @notice
     *
     * Variables:
     * Attempted_Heal_Round - the round at which a user attempts to heal - this is x
     * Heal_Rounds_Maximum - the maximum number of rounds after a user is wounded in which they can heal (ROUNDS_TO_BE_WOUNDED_BEFORE_DEAD) - this is x2
     * Heal_Rounds_Minimum - the minimum number of rounds after a user is wounded until they can heal (a user cannot heal the same round as wound, so we select one round after wound hence 1) - this is x1
     * Maximum_Heal_Percentage - the maximum % chance a user can heal for, this will be if they heal in Heal_Rounds_Minimum (we have set this to 99% of a successful healing) - this is y1
     * Minimum_Heal_Percentage - the minimum % chance a user can heal for, this will be if they heal in Heal_Rounds_Maximum (we have set this to 80% of a successful healing) - this is y2
     *
     * Equation:

     * If you substitute all of these into the following equation:
     * y = (( x * (y2-y1)) / (x2-x1)) + ((x2 * y1 - x1 * y2) / (x2 - x1))

     * You will get an equation for y which is the PercentageChanceToHealSuccessfully given an Attempted_Heal_Round number.

     * Explanation:
     * i.e if a user is wounded in round 2, and they try to heal in round 4, their Attempted_Heal_Round relative to themselves is 2, hence by subsituting 2 into the place of x in the above equation, their PercentageChanceToHealSuccessfully will be 98.59574468%.
     *
     * @param healingRoundsDelay The number of rounds elapsed since the agent was wounded.
     */
    function healProbability(uint256 healingRoundsDelay) public view returns (uint256 y) {
        if (healingRoundsDelay == 0 || healingRoundsDelay > ROUNDS_TO_BE_WOUNDED_BEFORE_DEAD) {
            revert InvalidHealingRoundsDelay();
        }

        y =
            HEAL_PROBABILITY_MINUEND -
            ((healingRoundsDelay * 19) * PROBABILITY_PRECISION) /
            ROUNDS_TO_BE_WOUNDED_BEFORE_DEAD_MINUS_ONE;
    }

    /**
     * @notice The formula is 80 - 50 * PercentageOfAgentsRemaining ** 2.
     */
    function escapeMultiplier() public view returns (uint256 multiplier) {
        multiplier = _escapeMultiplier(agentsAlive());
    }

    /**
     * @notice The formula is the lesser of (9,980 / 99) - (UsersRemaining / TotalUsers) * (8,000 / 99) and 100.
     */
    function escapeRewardSplitForSecondaryPrizePool() public view returns (uint256 split) {
        split = _escapeRewardSplitForSecondaryPrizePool(agentsAlive());
    }

    /**
     * @notice An agent's secondary prize pool share amount. The formula is 1.31487 * 995 / (placement * 49) - 15 / 49.
     * @param secondaryPrizePoolAmount The secondary prize pool amount.
     * @param placement The agent's rank in the leaderboard. This is not meant to be called with placement that is not between 1 and NUMBER_OF_SECONDARY_PRIZE_POOL_WINNERS.
     */
    function secondaryPrizePoolShareAmount(
        uint256 secondaryPrizePoolAmount,
        uint256 placement
    ) public pure returns (uint256 shareAmount) {
        shareAmount =
            (secondaryPrizePoolAmount * secondaryPrizePoolShareBp(placement)) /
            ONE_HUNDRED_PERCENT_IN_BASIS_POINTS;
    }

    /**
     * @notice An agent's secondary prize pool share in basis points. The formula is 1.31817 * 995 / (placement * 49) - 15 / 49.
     * @param placement The agent's rank in the leaderboard. This is not meant to be called with placement that is not between 1 and NUMBER_OF_SECONDARY_PRIZE_POOL_WINNERS.
     */
    function secondaryPrizePoolShareBp(uint256 placement) public pure returns (uint256 share) {
        share = (1_31817 * (995_000_000 / (placement * 49) - uint256(15_000_000) / 49)) / 1_000_000_000;
    }

    /**
     * @inheritdoc IInfiltration
     */
    function agentsAlive() public view returns (uint256) {
        return totalSupply() - gameInfo.deadAgents - gameInfo.escapedAgents;
    }

    /**
     * @inheritdoc IInfiltration
     */
    function agentIndex(uint256 agentId) public view returns (uint256 index) {
        index = agentIdToIndex[agentId];
        if (index == 0) {
            index = agentId;
        }
    }

    /**
     * @inheritdoc IInfiltration
     */
    function getRoundInfo(
        uint256 roundId
    ) external view returns (uint256[] memory woundedAgentIds, uint256[] memory healingAgentIds) {
        woundedAgentIds = _buildAgentIdsPerRoundArray(woundedAgentIdsPerRound[roundId]);
        healingAgentIds = _buildAgentIdsPerRoundArray(healingAgentIdsPerRound[roundId]);
    }

    /**
     * @param requestId The VRF request ID.
     * @param randomWords The random words returned from Chainlink. We only request 1 random word.
     */
    function fulfillRandomWords(uint256 requestId, uint256[] memory randomWords) internal override {
        RandomnessRequest storage randomnessRequest = randomnessRequests[requestId];

        uint256 currentRoundId = gameInfo.currentRoundId;
        uint256 randomnessRequestRoundId = randomnessRequest.roundId;
        if (
            randomnessRequestRoundId != currentRoundId || randomnessRequest.status != RandomnessRequestStatus.Requested
        ) {
            emit InvalidRandomnessFulfillment(requestId, randomnessRequestRoundId, currentRoundId);
            return;
        }

        randomnessRequest.randomWord = randomWords[0];
        randomnessRequest.status = RandomnessRequestStatus.Fulfilled;

        emit RandomnessFulfilled(randomnessRequest.roundId, requestId);
    }

    /**
     * @inheritdoc IInfiltration
     */
    function closeRound(uint256 requestId) external {
        uint256 currentRoundId = gameInfo.currentRoundId;
        RandomnessRequest storage randomnessRequest = randomnessRequests[requestId];
        if (
            randomnessRequest.roundId != currentRoundId || randomnessRequest.status != RandomnessRequestStatus.Fulfilled
        ) {
            revert InvalidRandomnessRequestId();
        }

        uint256 currentRandomWord = randomnessRequest.randomWord;

        uint256 currentRoundAgentsAlive = agentsAlive();
        uint256 activeAgents = gameInfo.activeAgents;
        uint256 healingAgents = gameInfo.healingAgents;

        uint256 deadAgentsFromHealing;

        if (healingAgents != 0) {
            uint256 healedAgents;
            (healedAgents, deadAgentsFromHealing, currentRandomWord) = _healRequestFulfilled(
                currentRoundId,
                currentRoundAgentsAlive,
                currentRandomWord
            );
            unchecked {
                currentRoundAgentsAlive -= deadAgentsFromHealing;
                activeAgents += healedAgents;
                gameInfo.healingAgents = uint16(healingAgents - healedAgents - deadAgentsFromHealing);
            }
        }

        if (activeAgents > NUMBER_OF_SECONDARY_PRIZE_POOL_WINNERS) {
            uint256 woundedAgents = _woundRequestFulfilled(
                currentRoundId,
                currentRoundAgentsAlive,
                activeAgents,
                currentRandomWord
            );

            uint256 deadAgentsFromKilling;
            if (currentRoundId > ROUNDS_TO_BE_WOUNDED_BEFORE_DEAD) {
                deadAgentsFromKilling = _killWoundedAgents({
                    currentRoundId: currentRoundId,
                    roundId: currentRoundId.unsafeSubtract(ROUNDS_TO_BE_WOUNDED_BEFORE_DEAD),
                    currentRoundAgentsAlive: currentRoundAgentsAlive
                });
            }

            // We only need to deduct wounded agents from active agents, dead agents from killing are already inactive.

            // This is equivalent to
            // unchecked {
            //     gameInfo.activeAgents = activeAgents - woundedAgents;
            //     gameInfo.woundedAgents = gameInfo.woundedAgents + woundedAgents - deadAgentsFromKilling;
            //     gameInfo.deadAgents += (deadAgentsFromHealing + deadAgentsFromKilling);
            // }
            // SSTORE is called in _incrementRound
            uint256 gameInfoSlot0Value;
            assembly {
                gameInfoSlot0Value := sload(gameInfo.slot)

                let currentWoundedAgents := and(
                    shr(GAME_INFO__WOUNDED_AGENTS_OFFSET, gameInfoSlot0Value),
                    TWO_BYTES_BITMASK
                )
                let currentDeadAgents := and(shr(GAME_INFO__DEAD_AGENTS_OFFSET, gameInfoSlot0Value), TWO_BYTES_BITMASK)

                gameInfoSlot0Value := and(
                    gameInfoSlot0Value,
                    // This is equivalent to
                    // not(
                    //     or(
                    //         TWO_BYTES_BITMASK,
                    //         or(
                    //             shl(GAME_INFO__WOUNDED_AGENTS_OFFSET, TWO_BYTES_BITMASK),
                    //             shl(GAME_INFO__DEAD_AGENTS_OFFSET, TWO_BYTES_BITMASK)
                    //         )
                    //     )
                    // )
                    0xffffffffffffffffffffffffffffffffffffffffffffffff0000ffff00000000
                )
                gameInfoSlot0Value := or(gameInfoSlot0Value, sub(activeAgents, woundedAgents))

                gameInfoSlot0Value := or(
                    gameInfoSlot0Value,
                    shl(
                        GAME_INFO__WOUNDED_AGENTS_OFFSET,
                        sub(add(currentWoundedAgents, woundedAgents), deadAgentsFromKilling)
                    )
                )

                gameInfoSlot0Value := or(
                    gameInfoSlot0Value,
                    shl(
                        GAME_INFO__DEAD_AGENTS_OFFSET,
                        add(currentDeadAgents, add(deadAgentsFromHealing, deadAgentsFromKilling))
                    )
                )
            }
            _incrementRound(currentRoundId, gameInfoSlot0Value);
        } else {
            bool shouldKillOneAgent = activeAgents > 1;
            if (shouldKillOneAgent) {
                uint256 killedAgentIndex = (currentRandomWord % activeAgents).unsafeAdd(1);
                Agent storage agentToKill = agents[killedAgentIndex];
                uint256 agentId = _agentIndexToId(agentToKill, killedAgentIndex);
                _swap({
                    currentAgentIndex: killedAgentIndex,
                    lastAgentIndex: currentRoundAgentsAlive,
                    agentId: agentId,
                    newStatus: AgentStatus.Dead
                });

                uint256[] memory killedAgentId = new uint256[](1);
                killedAgentId[0] = agentId;
                emit Killed(currentRoundId, killedAgentId);

                unchecked {
                    --activeAgents;
                    --currentRoundAgentsAlive;
                }
            }

            // This is equivalent to
            // unchecked {
            //     gameInfo.activeAgents = activeAgents;
            //     gameInfo.deadAgents = gameInfo.deadAgents + deadAgentsFromHealing + 1;
            // }
            // SSTORE is called in _incrementRound
            uint256 gameInfoSlot0Value;
            assembly {
                gameInfoSlot0Value := sload(gameInfo.slot)
                let deadAgents := and(shr(GAME_INFO__DEAD_AGENTS_OFFSET, gameInfoSlot0Value), TWO_BYTES_BITMASK)

                gameInfoSlot0Value := and(
                    gameInfoSlot0Value,
                    // This is equivalent to not(or(TWO_BYTES_BITMASK, shl(GAME_INFO__DEAD_AGENTS_OFFSET, TWO_BYTES_BITMASK)))
                    0xffffffffffffffffffffffffffffffffffffffffffffffff0000ffffffff0000
                )
                gameInfoSlot0Value := or(gameInfoSlot0Value, activeAgents)
                // If shouldKillOneAgent is true, then add 1. If false, then add 0.
                gameInfoSlot0Value := or(
                    gameInfoSlot0Value,
                    shl(GAME_INFO__DEAD_AGENTS_OFFSET, add(add(deadAgents, deadAgentsFromHealing), shouldKillOneAgent))
                )
            }

            _emitWonEventIfOnlyOneAgentRemaining(currentRoundAgentsAlive, activeAgents);
            _incrementRound(currentRoundId, gameInfoSlot0Value);
        }

        frontrunLock = FRONTRUN_LOCK__UNLOCKED;

        unchecked {
            emit RoundStarted(currentRoundId + 1);
        }
    }

    /**
     * @dev This function doesn't check currentRoundId to be <= type(uint40).max but it's fine as
     *      it's practically impossible to reach this number of rounds.
     * @param currentRoundId The current round ID.
     * @param gameInfoSlot0Value The value of gameInfo.slot.
     */
    function _incrementRound(uint256 currentRoundId, uint256 gameInfoSlot0Value) private {
        // This is equivalent to
        // unchecked {
        //     uint256 newRoundId = currentRoundId + 1;
        //     gameInfo.currentRoundId = newRoundId;
        //     gameInfo.currentRoundBlockNumber = uint40(block.number);
        //     gameInfo.randomnessLastRequestedAt = 0;
        // }
        assembly {
            gameInfoSlot0Value := and(
                gameInfoSlot0Value,
                // This is equivalent to
                // let gameInfoRandomnessLastRequestedAtOffset := 160
                // not(
                //     or(
                //         or(
                //             shl(GAME_INFO__CURRENT_ROUND_ID_OFFSET, FIVE_BYTES_BITMASK),
                //             shl(GAME_INFO__CURRENT_ROUND_BLOCK_NUMBER_OFFSET, FIVE_BYTES_BITMASK)
                //         ),
                //         shl(gameInfoRandomnessLastRequestedAtOffset, FIVE_BYTES_BITMASK)
                //     )
                // )
                0xffffffffffffff000000000000000000000000000000ffffffffffffffffffff
            )
            gameInfoSlot0Value := or(
                gameInfoSlot0Value,
                shl(GAME_INFO__CURRENT_ROUND_ID_OFFSET, add(currentRoundId, 1))
            )
            gameInfoSlot0Value := or(gameInfoSlot0Value, shl(GAME_INFO__CURRENT_ROUND_BLOCK_NUMBER_OFFSET, number()))
            sstore(gameInfo.slot, gameInfoSlot0Value)
        }
    }

    /**
     * @dev This function requests for a random word from Chainlink VRF for wounding and healing.
     */
    function _requestForRandomness() private {
        uint256 requestId = VRF_COORDINATOR.requestRandomWords({
            keyHash: KEY_HASH,
            subId: SUBSCRIPTION_ID,
            minimumRequestConfirmations: uint16(3),
            callbackGasLimit: uint32(2_500_000),
            numWords: uint32(1)
        });

        if (randomnessRequests[requestId].status != RandomnessRequestStatus.None) {
            revert RandomnessRequestAlreadyExists();
        }

        uint40 currentRoundId = gameInfo.currentRoundId;

        gameInfo.randomnessLastRequestedAt = uint40(block.timestamp);

        // This is equivalent to
        // randomnessRequests[requestId].status = RandomnessRequestStatus.Requested;
        // randomnessRequests[requestId].roundId = currentRoundId;
        assembly {
            // 1 is RandomnessRequestStatus.Requested
            let randomnessRequest := or(1, shl(RANDOMNESS_REQUESTS__EXISTS_OFFSET, currentRoundId))
            mstore(0x00, requestId)
            mstore(0x20, randomnessRequests.slot)
            let randomnessRequestStoragSlot := keccak256(0x00, 0x40)
            sstore(randomnessRequestStoragSlot, randomnessRequest)
        }

        frontrunLock = FRONTRUN_LOCK__LOCKED;

        emit RandomnessRequested(currentRoundId, requestId);
    }

    /**
     * @param roundId The current round ID.
     * @param currentRoundAgentsAlive The number of agents alive currently.
     * @param randomWord The random word returned from Chainlink.
     * @return healedAgentsCount The number of agents that were healed.
     * @return deadAgentsCount The number of agents that were killed.
     * @return currentRandomWord The current random word after running the function.
     */
    function _healRequestFulfilled(
        uint256 roundId,
        uint256 currentRoundAgentsAlive,
        uint256 randomWord
    ) private returns (uint256 healedAgentsCount, uint256 deadAgentsCount, uint256 currentRandomWord) {
        uint16[MAXIMUM_HEALING_OR_WOUNDED_AGENTS_PER_ROUND_AND_LENGTH]
            storage healingAgentIds = healingAgentIdsPerRound[roundId];
        uint256 healingAgentIdsCount = healingAgentIds[0];

        if (healingAgentIdsCount != 0) {
            HealResult[] memory healResults = new HealResult[](healingAgentIdsCount);

            for (uint256 i; i < healingAgentIdsCount; ) {
                uint256 healingAgentId = healingAgentIds[i.unsafeAdd(1)];
                uint256 index = agentIndex(healingAgentId);
                Agent storage agent = agents[index];

                healResults[i].agentId = healingAgentId;

                // 1. An agent's "healing at" round ID is always equal to the current round ID
                //    as it immediately settles upon randomness fulfillment.
                //
                // 2. 10_000_000_000 == 100 * PROBABILITY_PRECISION
                if (randomWord % 10_000_000_000 <= healProbability(roundId.unsafeSubtract(agent.woundedAt))) {
                    // This line is not needed as HealOutcome.Healed is 0. It is here for clarity.
                    // healResults[i].outcome = HealOutcome.Healed;
                    _healAgent(agent);
                } else {
                    healResults[i].outcome = HealOutcome.Killed;
                    _swap({
                        currentAgentIndex: index,
                        lastAgentIndex: currentRoundAgentsAlive - deadAgentsCount,
                        agentId: healingAgentId,
                        newStatus: AgentStatus.Dead
                    });
                    unchecked {
                        ++deadAgentsCount;
                    }
                }

                randomWord = _nextRandomWord(randomWord);

                unchecked {
                    ++i;
                }
            }

            unchecked {
                healedAgentsCount = healingAgentIdsCount - deadAgentsCount;
            }

            emit HealRequestFulfilled(roundId, healResults);
        }

        currentRandomWord = randomWord;
    }

    /**
     * @param roundId The current round ID.
     * @param currentRoundAgentsAlive The number of agents alive currently.
     * @param activeAgents The number of currently active agents.
     * @param randomWord The random word returned from Chainlink.
     * @return woundedAgentsCount The number of agents that were wounded.
     */
    function _woundRequestFulfilled(
        uint256 roundId,
        uint256 currentRoundAgentsAlive,
        uint256 activeAgents,
        uint256 randomWord
    ) private returns (uint256 woundedAgentsCount) {
        woundedAgentsCount =
            (activeAgents * AGENTS_TO_WOUND_PER_ROUND_IN_BASIS_POINTS) /
            ONE_HUNDRED_PERCENT_IN_BASIS_POINTS;
        // At some point the number of agents to wound will be 0 due to round down, so we set it to 1.
        if (woundedAgentsCount == 0) {
            woundedAgentsCount = 1;
        }

        uint256[] memory woundedAgentIds = new uint256[](woundedAgentsCount);
        uint16[MAXIMUM_HEALING_OR_WOUNDED_AGENTS_PER_ROUND_AND_LENGTH]
            storage currentRoundWoundedAgentIds = woundedAgentIdsPerRound[roundId];

        for (uint256 i; i < woundedAgentsCount; ) {
            uint256 woundedAgentIndex = (randomWord % currentRoundAgentsAlive).unsafeAdd(1);
            Agent storage agentToWound = agents[woundedAgentIndex];

            if (agentToWound.status == AgentStatus.Active) {
                // This is equivalent to
                // agentToWound.status = AgentStatus.Wounded;
                // agentToWound.woundedAt = roundId;
                assembly {
                    let agentSlotValue := sload(agentToWound.slot)
                    agentSlotValue := and(
                        agentSlotValue,
                        // This is equivalent to
                        // or(
                        //     TWO_BYTES_BITMASK,
                        //     shl(64, TWO_BYTES_BITMASK)
                        // )
                        0x00000000000000000000000000000000000000000000ffff000000000000ffff
                    )
                    // AgentStatus.Wounded is 1
                    agentSlotValue := or(agentSlotValue, shl(AGENT__STATUS_OFFSET, 1))
                    agentSlotValue := or(agentSlotValue, shl(AGENT__WOUNDED_AT_OFFSET, roundId))
                    sstore(agentToWound.slot, agentSlotValue)
                }

                uint256 woundedAgentId = _agentIndexToId(agentToWound, woundedAgentIndex);
                woundedAgentIds[i] = woundedAgentId;

                unchecked {
                    ++i;
                    currentRoundWoundedAgentIds[i] = uint16(woundedAgentId);
                }
            }

            randomWord = _nextRandomWord(randomWord);
        }

        currentRoundWoundedAgentIds[0] = uint16(woundedAgentsCount);

        emit Wounded(roundId, woundedAgentIds);
    }

    /**
     * @dev This function emits the Killed event but some agent IDs in the array can be 0 because
     *      they might have been healed or are dead already.
     * @param currentRoundId The current round ID.
     * @param roundId The round ID in which the wounded agents should be killed.
     * @param currentRoundAgentsAlive The number of agents alive currently.
     * @return deadAgentsCount The number of agents that were killed.
     */
    function _killWoundedAgents(
        uint256 currentRoundId,
        uint256 roundId,
        uint256 currentRoundAgentsAlive
    ) private returns (uint256 deadAgentsCount) {
        uint16[MAXIMUM_HEALING_OR_WOUNDED_AGENTS_PER_ROUND_AND_LENGTH]
            storage woundedAgentIdsInRound = woundedAgentIdsPerRound[roundId];
        uint256 woundedAgentIdsCount = woundedAgentIdsInRound[0];
        uint256[] memory woundedAgentIds = new uint256[](woundedAgentIdsCount);
        for (uint256 i; i < woundedAgentIdsCount; ) {
            uint256 woundedAgentId = woundedAgentIdsInRound[i.unsafeAdd(1)];
            uint256 index = agentIndex(woundedAgentId);
            Agent storage agent = agents[index];
            if (agent.status == AgentStatus.Wounded) {
                if (agent.woundedAt == roundId) {
                    woundedAgentIds[i] = woundedAgentId;
                    _swap({
                        currentAgentIndex: index,
                        lastAgentIndex: currentRoundAgentsAlive - deadAgentsCount,
                        agentId: woundedAgentId,
                        newStatus: AgentStatus.Dead
                    });
                    unchecked {
                        ++deadAgentsCount;
                    }
                }
            }

            unchecked {
                ++i;
            }
        }

        emit Killed(currentRoundId, woundedAgentIds);
    }

    /**
     * @param agent The agent to check.
     * @param index The agent's index in the agents mapping.
     * @return agentId The agent's ID.
     */
    function _agentIndexToId(Agent storage agent, uint256 index) private view returns (uint256 agentId) {
        agentId = agent.agentId;
        agentId = agentId == 0 ? index : agentId;
    }

    /**
     * @param healCount The number of times the agent has been successfully healed.
     * @return cost The cost to heal the agent based on the agent's successful heal count.
     */
    function _costToHeal(uint256 healCount) private view returns (uint256 cost) {
        cost = HEAL_BASE_COST * (2 ** healCount);
    }

    /**
     * @param agent The agent to heal.
     */
    function _healAgent(Agent storage agent) private {
        // This is equivalent to
        // agent.status = AgentStatus.Active;
        // agent.woundedAt = 0;
        // lastHealCount = agent.healCount;
        // ++agent.healCount;
        assembly {
            let agentSlotValue := sload(agent.slot)
            let lastHealCount := and(shr(AGENT__HEAL_COUNT_OFFSET, agentSlotValue), TWO_BYTES_BITMASK)
            agentSlotValue := and(agentSlotValue, TWO_BYTES_BITMASK)
            agentSlotValue := or(agentSlotValue, shl(AGENT__HEAL_COUNT_OFFSET, add(lastHealCount, 1)))
            sstore(agent.slot, agentSlotValue)
        }
    }

    /**
     * @notice An agent is killed by swapping it with the last agent in the agents mapping and decrementing `agentsAlive`
     *         by adding 1 to `gameInfo.deadAgents`.
     * @notice An agent escapes by swapping it with the last agent in the agents mapping and decrementing `agentsAlive`
     *         by adding 1 to `gameInfo.escapedAgents`.
     * @param currentAgentIndex The agent (whose status is being updated)'s index in the agents mapping.
     * @param lastAgentIndex Last agent's index in the agents mapping.
     * @param agentId The agent (whose status is being updated) 's ID.
     * @param newStatus The new status of the agent.
     */
    function _swap(uint256 currentAgentIndex, uint256 lastAgentIndex, uint256 agentId, AgentStatus newStatus) private {
        Agent storage lastAgent = agents[lastAgentIndex];
        uint256 lastAgentId = _agentIndexToId(lastAgent, lastAgentIndex);

        agentIdToIndex[agentId] = lastAgentIndex;
        agentIdToIndex[lastAgentId] = currentAgentIndex;

        /**
         * If last agent's agent ID is 0 that means it was never touched and is active.
         *
         * This is equivalent to
         *
         * agent.agentId = uint16(lastAgentId);
         * agent.status = lastAgent.status;
         * agent.woundedAt = lastAgent.woundedAt;
         * agent.healCount = lastAgent.healCount;

         * lastAgent.agentId = uint16(agentId);
         * lastAgent.status = newStatus;
         * lastAgent.woundedAt = 0;
         * lastAgent.healCount = 0;
         */
        bytes32 currentAgentSlot = _getAgentStorageSlot(currentAgentIndex);
        bytes32 lastAgentSlot = _getAgentStorageSlot(lastAgentIndex);

        assembly {
            let lastAgentCurrentValue := sload(lastAgentSlot)
            // The last agent's ID is either 0 or lastAgentId, so we do not need to clear the last 16 bits
            // as it can only be or(0, lastAgentId) or or(lastAgentId, lastAgentId) which both ends up being lastAgentId.
            lastAgentCurrentValue := or(lastAgentCurrentValue, lastAgentId)
            sstore(currentAgentSlot, lastAgentCurrentValue)

            let lastAgentNewValue := agentId
            lastAgentNewValue := or(lastAgentNewValue, shl(AGENT__STATUS_OFFSET, newStatus))
            sstore(lastAgentSlot, lastAgentNewValue)
        }
    }

    /**
     * @notice Returns the next random word by hashing.
     * @param randomWord The current random word.
     * @return nextRandomWord The next random word.
     */
    function _nextRandomWord(uint256 randomWord) private pure returns (uint256 nextRandomWord) {
        // This is equivalent to
        // randomWord = uint256(keccak256(abi.encode(randomWord)));
        assembly {
            mstore(0x00, randomWord)
            nextRandomWord := keccak256(0x00, 0x20)
        }
    }

    /**
     * @param index The agent's index in the agents mapping.
     * @return agentStorageSlot The agent's storage slot.
     */
    function _getAgentStorageSlot(uint256 index) private pure returns (bytes32 agentStorageSlot) {
        assembly {
            mstore(0x00, index)
            mstore(0x20, agents.slot)
            agentStorageSlot := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev ONE_HUNDRED_PERCENT_IN_BASIS_POINTS is used as an amplifier to prevent a loss of precision.
     * @param agentsRemaining The number of agents remaining including wounded and healing agents.
     * @return multiplier The escape multiplier in basis points. This portion of the reward goes to the owner of the escaping agent.
     */
    function _escapeMultiplier(uint256 agentsRemaining) private view returns (uint256 multiplier) {
        multiplier =
            ((80 *
                ONE_HUNDRED_PERCENT_IN_BASIS_POINTS_SQUARED -
                50 *
                (((agentsRemaining * ONE_HUNDRED_PERCENT_IN_BASIS_POINTS) / totalSupply()) ** 2)) * 100) /
            ONE_HUNDRED_PERCENT_IN_BASIS_POINTS_SQUARED;
    }

    /**
     * @dev ONE_HUNDRED_PERCENT_IN_BASIS_POINTS is used as an amplifier to prevent a loss of precision.
     * @param agentsRemaining The number of agents remaining including wounded and healing agents.
     * @return split The split of the remaining escape reward between the the secondary prize pool and the main prize pool in basis points.
     */
    function _escapeRewardSplitForSecondaryPrizePool(uint256 agentsRemaining) private view returns (uint256 split) {
        split =
            ((9_980 * ONE_HUNDRED_PERCENT_IN_BASIS_POINTS) /
                99 -
                (((agentsRemaining * ONE_HUNDRED_PERCENT_IN_BASIS_POINTS) / totalSupply()) * uint256(8_000)) /
                99) /
            100;
        if (split > ONE_HUNDRED_PERCENT_IN_BASIS_POINTS) {
            split = ONE_HUNDRED_PERCENT_IN_BASIS_POINTS;
        }
    }

    /**
     * @dev Emit the Won event if there is only 1 active agent remaining in the game.
     * @param agentsRemaining The number of alive agents.
     * @param activeAgentsRemaining The number of active agents remaining.
     */
    function _emitWonEventIfOnlyOneAgentRemaining(uint256 agentsRemaining, uint256 activeAgentsRemaining) private {
        if (agentsRemaining == 1) {
            if (activeAgentsRemaining == 1) {
                emit Won(gameInfo.currentRoundId, _agentIndexToId(agents[1], 1));
            }
        }
    }

    /**
     * @notice Validate max supply is not breached after minting "quantity" amount of agents
     * @param quantity The quantity of agents to mint.
     */
    function _assertTotalSupplyNotBreached(uint256 quantity) private view {
        if (totalSupply() + quantity > MAX_SUPPLY) {
            revert ExceededTotalSupply();
        }
    }

    /**
     * @notice Validate the game has not begun.
     */
    function _assertGameNotYetBegun() private view {
        if (gameInfo.currentRoundId != 0) {
            revert GameAlreadyBegun();
        }
    }

    /**
     * @notice Validate exact ETH amount has been paid for the mint.
     * @param quantity The quantity of agents to mint.
     */
    function _assertExactNativeTokensSupplied(uint256 quantity) private view {
        if (quantity * PRICE != msg.value) {
            revert InexactNativeTokensSupplied();
        }
    }

    /**
     * @notice Validate the msg.sender is the owner of the agent ID.
     * @param agentId The agent ID to validate.
     */
    function _assertAgentOwnership(uint256 agentId) private view {
        if (ownerOf(agentId) != msg.sender) {
            revert NotAgentOwner();
        }
    }

    /**
     * @notice Validate the agent's status is the expected status.
     * @param agent The agent to validate.
     * @param agentId The agent's ID.
     * @param status The expected status.
     */
    function _assertAgentStatus(Agent storage agent, uint256 agentId, AgentStatus status) private view {
        if (agent.status != status) {
            revert InvalidAgentStatus(agentId, status);
        }
    }

    /**
     * @notice Validate the placement is between 1 and 50.
     * @param placement The placement to validate.
     */
    function _assertValidPlacement(uint256 placement) private pure {
        if (placement == 0 || placement > NUMBER_OF_SECONDARY_PRIZE_POOL_WINNERS) {
            revert InvalidPlacement();
        }
    }

    /**
     * @notice Validate the game is over by checking there is only 1 active agent and 0 wounded/healing agents.
     */
    function _assertGameOver() private view {
        if (gameInfo.activeAgents != 1 || gameInfo.woundedAgents != 0 || gameInfo.healingAgents != 0) {
            revert GameIsStillRunning();
        }
    }

    /**
     * @notice Validate the frontrun lock is off.
     */
    function _assertFrontrunLockIsOff() private view {
        if (frontrunLock == FRONTRUN_LOCK__LOCKED) {
            revert FrontrunLockIsOn();
        }
    }

    /**
     * @notice Validate the agent IDs array is not empty.
     */
    function _assertNotEmptyAgentIdsArrayProvided(uint256 agentIdsCount) private pure {
        if (agentIdsCount == 0) {
            revert NoAgentsProvided();
        }
    }

    /**
     * @notice Validate the game's active agents to be greater than 0 after escape.
     */
    function _assertGameIsNotOverAfterEscape(uint256 activeAgentsAfterEscape) private pure {
        if (activeAgentsAfterEscape < 1) {
            revert NoAgentsLeft();
        }
    }

    /**
     * @notice The starting token ID is 1.
     */
    function _startTokenId() internal pure override returns (uint256) {
        return 1;
    }

    /**
     * @notice The base URI of the collection.
     */
    function _baseURI() internal view override returns (string memory) {
        return baseURI;
    }

    /**
     * @param agentIdsPerRound The storage pointer to either a round's woundedAgentIdsPerRound or healingAgentIdsPerRound.
     * @return agentIds The agent IDs (now dynamically sized) in the round with the length removed.
     */
    function _buildAgentIdsPerRoundArray(
        uint16[MAXIMUM_HEALING_OR_WOUNDED_AGENTS_PER_ROUND_AND_LENGTH] storage agentIdsPerRound
    ) private view returns (uint256[] memory agentIds) {
        uint256 count = agentIdsPerRound[0];
        agentIds = new uint256[](count);
        for (uint256 i; i < count; ) {
            unchecked {
                agentIds[i] = agentIdsPerRound[i + 1];
                ++i;
            }
        }
    }
}

// File: contracts/interfaces/IInfiltration.sol



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

interface IInfiltration {
    /**
     * @notice Agent statuses.
     *         1. Active: The agent is active.
     *         2. Wounded: The agent is wounded. The agent can be healed for a number of blocks.
     *         3. Healing: The agent is healing. The outcome of the healing is not yet known.
     *         4. Escaped: The agent escaped from the game and took some rewards with him.
     *         5. Dead: The agent is dead. It can be due to the agent being wounded for too long or a failed healing.
     */
    enum AgentStatus {
        Active,
        Wounded,
        Healing,
        Escaped,
        Dead
    }

    /**
     * @notice Heal outcomes. The agent can either be healed or killed.
     */
    enum HealOutcome {
        Healed,
        Killed
    }

    /**
     * @notice Randomness request statuses.
     */
    enum RandomnessRequestStatus {
        None,
        Requested,
        Fulfilled
    }

    /**
     * @notice An agent.
     * @dev The storage layout of an agent is as follows:
     * |---------------------------------------------------------------------------------------------------|
     * | empty (176 bits) | healCount (16 bits) | woundedAt (40 bits) | status (8 bits) | agentId (16 bits)|
     * |---------------------------------------------------------------------------------------------------|
     * @param agentId The ID of the agent.
     * @param status The status of the agent.
     * @param woundedAt The round number when the agent was wounded.
     * @param healCount The number of times the agent has been successfully healed.
     */
    struct Agent {
        uint16 agentId;
        AgentStatus status;
        uint40 woundedAt;
        uint16 healCount;
    }

    /**
     * @notice The constructor calldata.
     * @param owner The owner of the contract.
     * @param name The name of the collection.
     * @param symbol The symbol of the collection.
     * @param price The mint price.
     * @param maxSupply The maximum supply of the collection.
     * @param maxMintPerAddress The maximum number of agents that can be minted per address.
     * @param blocksPerRound The number of blocks per round.
     * @param agentsToWoundPerRoundInBasisPoints The number of agents to wound per round in basis points.
     * @param roundsToBeWoundedBeforeDead The number of rounds for an agent to be wounded before getting killed.
     * @param looks The LOOKS token address.
     * @param vrfCoordinator The VRF coordinator address.
     * @param keyHash The VRF key hash.
     * @param subscriptionId The VRF subscription ID.
     * @param transferManager The transfer manager address.
     * @param healBaseCost The base cost to heal an agent.
     * @param protocolFeeRecipient The protocol fee recipient.
     * @param protocolFeeBp The protocol fee basis points.
     * @param weth The WETH address.
     * @param baseURI The base URI of the collection.
     */
    struct ConstructorCalldata {
        address owner;
        string name;
        string symbol;
        uint256 price;
        uint256 maxSupply;
        uint256 maxMintPerAddress;
        uint256 blocksPerRound;
        uint256 agentsToWoundPerRoundInBasisPoints;
        uint256 roundsToBeWoundedBeforeDead;
        address looks;
        address vrfCoordinator;
        bytes32 keyHash;
        uint64 subscriptionId;
        address transferManager;
        uint256 healBaseCost;
        address protocolFeeRecipient;
        uint16 protocolFeeBp;
        address weth;
        string baseURI;
    }

    /**
     * @notice Game info.
     * @dev The storage layout of game info is as follows:
     * |-------------------------------------------------------------------------------------------------------------------------------|
     * | empty (56 bits) | randomnessLastRequestedAt (40 bits) | currentRoundBlockNumber (40 bits) | currentRoundId (40 bits)          |
     * | escapedAgents (16 bits) | deadAgents (16 bits) | healingAgents (16 bits) | woundedAgents (16 bits) | activeAgents (16 bits)   |
     * |-------------------------------------------------------------------------------------------------------------------------------|
     * | prizePool (256 bits)                                                                                                          |
     * |-------------------------------------------------------------------------------------------------------------------------------|
     * | secondaryPrizePool (256 bits)                                                                                                 |
     * |-------------------------------------------------------------------------------------------------------------------------------|
     * | secondaryLooksPrizePool (256 bits)                                                                                            |
     * |-------------------------------------------------------------------------------------------------------------------------------|
     * @param activeAgents The number of active agents.
     * @param woundedAgents The number of wounded agents.
     * @param healingAgents The number of healing agents.
     * @param deadAgents The number of dead agents.
     * @param escapedAgents The number of escaped agents.
     * @param currentRoundId The current round ID.
     * @param currentRoundBlockNumber The current round block number.
     * @param randomnessLastRequestedAt The timestamp when the randomness was last requested.
     * @param prizePool The ETH prize pool for the final winner.
     * @param secondaryPrizePool The secondary ETH prize pool for the top X winners.
     * @param secondaryLooksPrizePool The secondary LOOKS prize pool for the top X winners.
     */
    struct GameInfo {
        uint16 activeAgents;
        uint16 woundedAgents;
        uint16 healingAgents;
        uint16 deadAgents;
        uint16 escapedAgents;
        uint40 currentRoundId;
        uint40 currentRoundBlockNumber;
        uint40 randomnessLastRequestedAt;
        uint256 prizePool;
        uint256 secondaryPrizePool;
        uint256 secondaryLooksPrizePool;
    }

    /**
     * @notice A Chainlink randomness request.
     * @param status The status of the randomness request.
     * @param roundId The round ID when the randomness request occurred.
     * @param randomWord The returned random word.
     */
    struct RandomnessRequest {
        RandomnessRequestStatus status;
        uint40 roundId;
        uint256 randomWord;
    }

    /**
     * @notice A heal result that is used to emit events.
     * @param agentId The agent ID.
     * @param outcome The outcome of the healing.
     */
    struct HealResult {
        uint256 agentId;
        HealOutcome outcome;
    }

    event EmergencyWithdrawal(uint256 ethAmount, uint256 looksAmount);
    event MintPeriodUpdated(uint256 mintStart, uint256 mintEnd);
    event HealRequestSubmitted(uint256 roundId, uint256[] agentIds, uint256[] costs);
    event HealRequestFulfilled(uint256 roundId, HealResult[] healResults);
    event RandomnessRequested(uint256 roundId, uint256 requestId);
    event RandomnessFulfilled(uint256 roundId, uint256 requestId);
    event InvalidRandomnessFulfillment(uint256 requestId, uint256 randomnessRequestRoundId, uint256 currentRoundId);
    event RoundStarted(uint256 roundId);
    event Escaped(uint256 roundId, uint256[] agentIds, uint256[] rewards);
    event PrizeClaimed(uint256 agentId, address currency, uint256 amount);
    event Wounded(uint256 roundId, uint256[] agentIds);
    event Killed(uint256 roundId, uint256[] agentIds);
    event Won(uint256 roundId, uint256 agentId);

    error ExceededTotalSupply();
    error FrontrunLockIsOn();
    error GameAlreadyBegun();
    error GameNotYetBegun();
    error GameIsStillRunning();
    error GameOver();
    error HealingDisabled();
    error InexactNativeTokensSupplied();
    error InvalidAgentStatus(uint256 agentId, AgentStatus expectedStatus);
    error InvalidHealingRoundsDelay();
    error InvalidMaxSupply();
    error InvalidMintPeriod();
    error InvalidPlacement();
    error MaximumHealingRequestPerRoundExceeded();
    error MintAlreadyStarted();
    error MintCanOnlyBeExtended();
    error MintStartIsInThePast();
    error NoAgentsLeft();
    error NoAgentsProvided();
    error NotEnoughMinted();
    error NothingToClaim();
    error NotInMintPeriod();
    error NotAgentOwner();
    error Immutable();
    error RandomnessRequestAlreadyExists();
    error InvalidRandomnessRequestId();
    error RoundsToBeWoundedBeforeDeadTooLow();
    error StillMinting();
    error TooEarlyToStartNewRound();
    error TooEarlyToRetryRandomnessRequest();
    error TooManyMinted();
    error WoundedAgentIdsPerRoundExceeded();

    /**
     * @notice Sets the mint period.
     * @dev If _mintStart is 0, the function call is just a mint end extension.
     * @param _mintStart The starting timestamp of the mint period.
     * @param _mintEnd The ending timestamp of the mint period.
     */
    function setMintPeriod(uint40 _mintStart, uint40 _mintEnd) external;

    /**
     * @notice Mints a number of agents.
     * @param to The recipient
     * @param quantity The number of agents to mint.
     */
    function premint(address to, uint256 quantity) external payable;

    /**
     * @notice Mints a number of agents.
     * @param quantity The number of agents to mint.
     */
    function mint(uint256 quantity) external payable;

    /**
     * @notice This function is here in case the game's invariant condition does not hold or the game is stuck.
     *         Only callable by the contract owner.
     */
    function emergencyWithdraw() external;

    /**
     * @notice Starts the game.
     * @dev Starting the game sets the current round ID to 1.
     */
    function startGame() external;

    /**
     * @notice Starts a new round.
     */
    function startNewRound() external;

    /**
     * @notice Close a round after randomness is fullfilled by Chainlink.
     * @param requestId The Chainlink request ID.
     */
    function closeRound(uint256 requestId) external;

    /**
     * @notice Claims the grand prize. Only callable by the winner.
     */
    function claimGrandPrize() external;

    /**
     * @notice Claims the secondary prizes. Only callable by top 50 agents.
     * @param agentId The agent ID.
     */
    function claimSecondaryPrizes(uint256 agentId) external;

    /**
     * @notice Escape from the game and take some rewards. 80% of the prize pool is distributed to
     *         the escaped agents and the rest to the secondary prize pool.
     * @param agentIds The agent IDs to escape.
     */
    function escape(uint256[] calldata agentIds) external;

    /**
     * @notice Submits a heal request for the specified agent IDs.
     * @param agentIds The agent IDs to heal.
     */
    function heal(uint256[] calldata agentIds) external;

    /**
     * @notice Get the agent at the specified index.
     * @return agent The agent at the specified index.
     */
    function getAgent(uint256 index) external view returns (Agent memory agent);

    /**
     * @notice Returns the cost to heal the specified agents
     * @dev The cost doubles for each time the agent is healed.
     * @param agentIds The agent IDs to heal.
     * @return cost The cost to heal the specified agents.
     */
    function costToHeal(uint256[] calldata agentIds) external view returns (uint256 cost);

    /**
     * @notice Returns the reward for escaping the game.
     * @param agentIds The agent IDs to escape.
     * @return reward The reward for escaping the game.
     */
    function escapeReward(uint256[] calldata agentIds) external view returns (uint256 reward);

    /**
     * @notice Returns the total number of agents alive.
     */
    function agentsAlive() external view returns (uint256);

    /**
     * @notice Returns the index of a specific agent ID inside the agents mapping.
     * @param agentId The agent ID.
     * @return index The index of the agent ID.
     */
    function agentIndex(uint256 agentId) external view returns (uint256 index);

    /**
     * @notice Returns a specific round's information.
     * @param roundId The round ID.
     * @return woundedAgentIds The agent IDs of the wounded agents in the specified round.
     * @return healingAgentIds The agent IDs of the healing agents in the specified round.
     */
    function getRoundInfo(
        uint256 roundId
    ) external view returns (uint256[] memory woundedAgentIds, uint256[] memory healingAgentIds);
}

// File: node_modules/@looksrare/contracts-libs/contracts/OwnableTwoSteps.sol



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

// Interfaces
import {IOwnableTwoSteps} from "./interfaces/IOwnableTwoSteps.sol";

/**
 * @title OwnableTwoSteps
 * @notice This contract offers transfer of ownership in two steps with potential owner
 *         having to confirm the transaction to become the owner.
 *         Renouncement of the ownership is also a two-step process since the next potential owner is the address(0).
 * @author LooksRare protocol team (👀,💎)
 */
abstract contract OwnableTwoSteps is IOwnableTwoSteps {
    /**
     * @notice Address of the current owner.
     */
    address public owner;

    /**
     * @notice Address of the potential owner.
     */
    address public potentialOwner;

    /**
     * @notice Ownership status.
     */
    Status public ownershipStatus;

    /**
     * @notice Modifier to wrap functions for contracts that inherit this contract.
     */
    modifier onlyOwner() {
        _onlyOwner();
        _;
    }

    /**
     * @notice Constructor
     * @param _owner The contract's owner
     */
    constructor(address _owner) {
        owner = _owner;
        emit NewOwner(_owner);
    }

    /**
     * @notice This function is used to cancel the ownership transfer.
     * @dev This function can be used for both cancelling a transfer to a new owner and
     *      cancelling the renouncement of the ownership.
     */
    function cancelOwnershipTransfer() external onlyOwner {
        Status _ownershipStatus = ownershipStatus;
        if (_ownershipStatus == Status.NoOngoingTransfer) {
            revert NoOngoingTransferInProgress();
        }

        if (_ownershipStatus == Status.TransferInProgress) {
            delete potentialOwner;
        }

        delete ownershipStatus;

        emit CancelOwnershipTransfer();
    }

    /**
     * @notice This function is used to confirm the ownership renouncement.
     */
    function confirmOwnershipRenouncement() external onlyOwner {
        if (ownershipStatus != Status.RenouncementInProgress) {
            revert RenouncementNotInProgress();
        }

        delete owner;
        delete ownershipStatus;

        emit NewOwner(address(0));
    }

    /**
     * @notice This function is used to confirm the ownership transfer.
     * @dev This function can only be called by the current potential owner.
     */
    function confirmOwnershipTransfer() external {
        if (ownershipStatus != Status.TransferInProgress) {
            revert TransferNotInProgress();
        }

        if (msg.sender != potentialOwner) {
            revert WrongPotentialOwner();
        }

        owner = msg.sender;
        delete ownershipStatus;
        delete potentialOwner;

        emit NewOwner(msg.sender);
    }

    /**
     * @notice This function is used to initiate the transfer of ownership to a new owner.
     * @param newPotentialOwner New potential owner address
     */
    function initiateOwnershipTransfer(address newPotentialOwner) external onlyOwner {
        if (ownershipStatus != Status.NoOngoingTransfer) {
            revert TransferAlreadyInProgress();
        }

        ownershipStatus = Status.TransferInProgress;
        potentialOwner = newPotentialOwner;

        /**
         * @dev This function can only be called by the owner, so msg.sender is the owner.
         *      We don't have to SLOAD the owner again.
         */
        emit InitiateOwnershipTransfer(msg.sender, newPotentialOwner);
    }

    /**
     * @notice This function is used to initiate the ownership renouncement.
     */
    function initiateOwnershipRenouncement() external onlyOwner {
        if (ownershipStatus != Status.NoOngoingTransfer) {
            revert TransferAlreadyInProgress();
        }

        ownershipStatus = Status.RenouncementInProgress;

        emit InitiateOwnershipRenouncement();
    }

    function _onlyOwner() private view {
        if (msg.sender != owner) revert NotOwner();
    }
}

// File: node_modules/@looksrare/contracts-libs/contracts/interfaces/generic/IERC20.sol



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

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

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

    function totalSupply() external view returns (uint256);

    function balanceOf(address account) external view returns (uint256);

    function transfer(address to, uint256 amount) external returns (bool);

    function allowance(address owner, address spender) external view returns (uint256);

    function approve(address spender, uint256 amount) external returns (bool);

    function transferFrom(address from, address to, uint256 amount) external returns (bool);

    function decimals() external view returns (uint8);
}

// File: node_modules/@looksrare/contracts-libs/contracts/ProtocolFee.sol



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

/**
 * @title ProtocolFee
 * @notice This contract makes it possible for a contract to charge a protocol fee.
 * @author LooksRare protocol team (👀,💎)
 */
abstract contract ProtocolFee {
    /**
     * @dev Emitted when the protocol fee basis points is updated.
     */
    event ProtocolFeeBpUpdated(uint16 protocolFeeBp);

    /**
     * @dev Emitted when the protocol fee recipient is updated.
     */
    event ProtocolFeeRecipientUpdated(address protocolFeeRecipient);

    /**
     * @dev This error is used when the protocol fee basis points is too high
     *      or when the protocol fee recipient is a zero address.
     */
    error ProtocolFee__InvalidValue();

    /**
     * @notice The maximum protocol fee in basis points, which is 25%.
     */
    uint16 public constant MAXIMUM_PROTOCOL_FEE_BP = 2_500;

    /**
     * @notice The address of the protocol fee recipient.
     */
    address public protocolFeeRecipient;

    /**
     * @notice The protocol fee basis points.
     */
    uint16 public protocolFeeBp;

    /**
     * @dev This function is used to update the protocol fee recipient. It should be overridden
     *      by the contract that inherits from this contract. The function should be guarded
     *      by an access control mechanism to prevent unauthorized users from calling it.
     * @param _protocolFeeRecipient The address of the protocol fee recipient
     */
    function updateProtocolFeeRecipient(address _protocolFeeRecipient) external virtual;

    /**
     * @dev This function is used to update the protocol fee basis points. It should be overridden
     *      by the contract that inherits from this contract. The function should be guarded
     *      by an access control mechanism to prevent unauthorized users from calling it.
     * @param _protocolFeeBp The protocol fee basis points
     */
    function updateProtocolFeeBp(uint16 _protocolFeeBp) external virtual;

    /**
     * @param _protocolFeeRecipient The new protocol fee recipient address
     */
    function _updateProtocolFeeRecipient(address _protocolFeeRecipient) internal {
        if (_protocolFeeRecipient == address(0)) {
            revert ProtocolFee__InvalidValue();
        }
        protocolFeeRecipient = _protocolFeeRecipient;
        emit ProtocolFeeRecipientUpdated(_protocolFeeRecipient);
    }

    /**
     * @param _protocolFeeBp The new protocol fee in basis points
     */
    function _updateProtocolFeeBp(uint16 _protocolFeeBp) internal {
        if (_protocolFeeBp > MAXIMUM_PROTOCOL_FEE_BP) {
            revert ProtocolFee__InvalidValue();
        }
        protocolFeeBp = _protocolFeeBp;
        emit ProtocolFeeBpUpdated(_protocolFeeBp);
    }
}

// File: node_modules/@looksrare/contracts-libs/contracts/PackableReentrancyGuard.sol



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

// Interfaces
import {IReentrancyGuard} from "./interfaces/IReentrancyGuard.sol";

/**
 * @title PackableReentrancyGuard
 * @notice This contract protects against reentrancy attacks.
 *         It is adjusted from OpenZeppelin.
 *         The only difference between this contract and ReentrancyGuard
 *         is that _status is uint8 instead of uint256 so that it can be
 *         packed with other contracts' storage variables.
 * @author LooksRare protocol team (👀,💎)
 */
abstract contract PackableReentrancyGuard is IReentrancyGuard {
    uint8 private _status;

    /**
     * @notice Modifier to wrap functions to prevent reentrancy calls.
     */
    modifier nonReentrant() {
        if (_status == 2) {
            revert ReentrancyFail();
        }

        _status = 2;
        _;
        _status = 1;
    }

    constructor() {
        _status = 1;
    }
}

// File: node_modules/@looksrare/contracts-libs/contracts/lowLevelCallers/LowLevelERC20Transfer.sol



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

// Interfaces
import {IERC20} from "../interfaces/generic/IERC20.sol";

// Errors
import {ERC20TransferFail, ERC20TransferFromFail} from "../errors/LowLevelErrors.sol";
import {NotAContract} from "../errors/GenericErrors.sol";

/**
 * @title LowLevelERC20Transfer
 * @notice This contract contains low-level calls to transfer ERC20 tokens.
 * @author LooksRare protocol team (👀,💎)
 */
contract LowLevelERC20Transfer {
    /**
     * @notice Execute ERC20 transferFrom
     * @param currency Currency address
     * @param from Sender address
     * @param to Recipient address
     * @param amount Amount to transfer
     */
    function _executeERC20TransferFrom(address currency, address from, address to, uint256 amount) internal {
        if (currency.code.length == 0) {
            revert NotAContract();
        }

        (bool status, bytes memory data) = currency.call(abi.encodeCall(IERC20.transferFrom, (from, to, amount)));

        if (!status) {
            revert ERC20TransferFromFail();
        }

        if (data.length > 0) {
            if (!abi.decode(data, (bool))) {
                revert ERC20TransferFromFail();
            }
        }
    }

    /**
     * @notice Execute ERC20 (direct) transfer
     * @param currency Currency address
     * @param to Recipient address
     * @param amount Amount to transfer
     */
    function _executeERC20DirectTransfer(address currency, address to, uint256 amount) internal {
        if (currency.code.length == 0) {
            revert NotAContract();
        }

        (bool status, bytes memory data) = currency.call(abi.encodeCall(IERC20.transfer, (to, amount)));

        if (!status) {
            revert ERC20TransferFail();
        }

        if (data.length > 0) {
            if (!abi.decode(data, (bool))) {
                revert ERC20TransferFail();
            }
        }
    }
}

// File: node_modules/@looksrare/contracts-libs/contracts/lowLevelCallers/LowLevelWETH.sol



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

// Interfaces
import {IWETH} from "../interfaces/generic/IWETH.sol";

/**
 * @title LowLevelWETH
 * @notice This contract contains a function to transfer ETH with an option to wrap to WETH.
 *         If the ETH transfer fails within a gas limit, the amount in ETH is wrapped to WETH and then transferred.
 * @author LooksRare protocol team (👀,💎)
 */
contract LowLevelWETH {
    /**
     * @notice It transfers ETH to a recipient with a specified gas limit.
     *         If the original transfers fails, it wraps to WETH and transfers the WETH to recipient.
     * @param _WETH WETH address
     * @param _to Recipient address
     * @param _amount Amount to transfer
     * @param _gasLimit Gas limit to perform the ETH transfer
     */
    function _transferETHAndWrapIfFailWithGasLimit(
        address _WETH,
        address _to,
        uint256 _amount,
        uint256 _gasLimit
    ) internal {
        bool status;

        assembly {
            status := call(_gasLimit, _to, _amount, 0, 0, 0, 0)
        }

        if (!status) {
            IWETH(_WETH).deposit{value: _amount}();
            IWETH(_WETH).transfer(_to, _amount);
        }
    }
}

// File: node_modules/@looksrare/contracts-transfer-manager/contracts/interfaces/ITransferManager.sol



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

// Enums
import {TokenType} from "../enums/TokenType.sol";

/**
 * @title ITransferManager
 * @author LooksRare protocol team (👀,💎)
 */
interface ITransferManager {
    /**
     * @notice This struct is only used for transferBatchItemsAcrossCollections.
     * @param tokenAddress Token address
     * @param tokenType 0 for ERC721, 1 for ERC1155
     * @param itemIds Array of item ids to transfer
     * @param amounts Array of amounts to transfer
     */
    struct BatchTransferItem {
        address tokenAddress;
        TokenType tokenType;
        uint256[] itemIds;
        uint256[] amounts;
    }

    /**
     * @notice It is emitted if operators' approvals to transfer NFTs are granted by a user.
     * @param user Address of the user
     * @param operators Array of operator addresses
     */
    event ApprovalsGranted(address user, address[] operators);

    /**
     * @notice It is emitted if operators' approvals to transfer NFTs are revoked by a user.
     * @param user Address of the user
     * @param operators Array of operator addresses
     */
    event ApprovalsRemoved(address user, address[] operators);

    /**
     * @notice It is emitted if a new operator is added to the global allowlist.
     * @param operator Operator address
     */
    event OperatorAllowed(address operator);

    /**
     * @notice It is emitted if an operator is removed from the global allowlist.
     * @param operator Operator address
     */
    event OperatorRemoved(address operator);

    /**
     * @notice It is returned if the operator to approve has already been approved by the user.
     */
    error OperatorAlreadyApprovedByUser();

    /**
     * @notice It is returned if the operator to revoke has not been previously approved by the user.
     */
    error OperatorNotApprovedByUser();

    /**
     * @notice It is returned if the transfer caller is already allowed by the owner.
     * @dev This error can only be returned for owner operations.
     */
    error OperatorAlreadyAllowed();

    /**
     * @notice It is returned if the operator to approve is not in the global allowlist defined by the owner.
     * @dev This error can be returned if the user tries to grant approval to an operator address not in the
     *      allowlist or if the owner tries to remove the operator from the global allowlist.
     */
    error OperatorNotAllowed();

    /**
     * @notice It is returned if the transfer caller is invalid.
     *         For a transfer called to be valid, the operator must be in the global allowlist and
     *         approved by the 'from' user.
     */
    error TransferCallerInvalid();

    /**
     * @notice This function transfers ERC20 tokens.
     * @param tokenAddress Token address
     * @param from Sender address
     * @param to Recipient address
     * @param amount amount
     */
    function transferERC20(
        address tokenAddress,
        address from,
        address to,
        uint256 amount
    ) external;

    /**
     * @notice This function transfers a single item for a single ERC721 collection.
     * @param tokenAddress Token address
     * @param from Sender address
     * @param to Recipient address
     * @param itemId Item ID
     */
    function transferItemERC721(
        address tokenAddress,
        address from,
        address to,
        uint256 itemId
    ) external;

    /**
     * @notice This function transfers items for a single ERC721 collection.
     * @param tokenAddress Token address
     * @param from Sender address
     * @param to Recipient address
     * @param itemIds Array of itemIds
     * @param amounts Array of amounts
     */
    function transferItemsERC721(
        address tokenAddress,
        address from,
        address to,
        uint256[] calldata itemIds,
        uint256[] calldata amounts
    ) external;

    /**
     * @notice This function transfers a single item for a single ERC1155 collection.
     * @param tokenAddress Token address
     * @param from Sender address
     * @param to Recipient address
     * @param itemId Item ID
     * @param amount Amount
     */
    function transferItemERC1155(
        address tokenAddress,
        address from,
        address to,
        uint256 itemId,
        uint256 amount
    ) external;

    /**
     * @notice This function transfers items for a single ERC1155 collection.
     * @param tokenAddress Token address
     * @param from Sender address
     * @param to Recipient address
     * @param itemIds Array of itemIds
     * @param amounts Array of amounts
     * @dev It does not allow batch transferring if from = msg.sender since native function should be used.
     */
    function transferItemsERC1155(
        address tokenAddress,
        address from,
        address to,
        uint256[] calldata itemIds,
        uint256[] calldata amounts
    ) external;

    /**
     * @notice This function transfers items across an array of tokens that can be ERC20, ERC721 and ERC1155.
     * @param items Array of BatchTransferItem
     * @param from Sender address
     * @param to Recipient address
     */
    function transferBatchItemsAcrossCollections(
        BatchTransferItem[] calldata items,
        address from,
        address to
    ) external;

    /**
     * @notice This function allows a user to grant approvals for an array of operators.
     *         Users cannot grant approvals if the operator is not allowed by this contract's owner.
     * @param operators Array of operator addresses
     * @dev Each operator address must be globally allowed to be approved.
     */
    function grantApprovals(address[] calldata operators) external;

    /**
     * @notice This function allows a user to revoke existing approvals for an array of operators.
     * @param operators Array of operator addresses
     * @dev Each operator address must be approved at the user level to be revoked.
     */
    function revokeApprovals(address[] calldata operators) external;

    /**
     * @notice This function allows an operator to be added for the shared transfer system.
     *         Once the operator is allowed, users can grant NFT approvals to this operator.
     * @param operator Operator address to allow
     * @dev Only callable by owner.
     */
    function allowOperator(address operator) external;

    /**
     * @notice This function allows the user to remove an operator for the shared transfer system.
     * @param operator Operator address to remove
     * @dev Only callable by owner.
     */
    function removeOperator(address operator) external;

    /**
     * @notice This returns whether the user has approved the operator address.
     * The first address is the user and the second address is the operator.
     */
    function hasUserApprovedOperator(address user, address operator) external view returns (bool);
}

// File: node_modules/@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol



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

interface VRFCoordinatorV2Interface {
  /**
   * @notice Get configuration relevant for making requests
   * @return minimumRequestConfirmations global min for request confirmations
   * @return maxGasLimit global max for request gas limit
   * @return s_provingKeyHashes list of registered key hashes
   */
  function getRequestConfig()
    external
    view
    returns (
      uint16,
      uint32,
      bytes32[] memory
    );

  /**
   * @notice Request a set of random words.
   * @param keyHash - Corresponds to a particular oracle job which uses
   * that key for generating the VRF proof. Different keyHash's have different gas price
   * ceilings, so you can select a specific one to bound your maximum per request cost.
   * @param subId  - The ID of the VRF subscription. Must be funded
   * with the minimum subscription balance required for the selected keyHash.
   * @param minimumRequestConfirmations - How many blocks you'd like the
   * oracle to wait before responding to the request. See SECURITY CONSIDERATIONS
   * for why you may want to request more. The acceptable range is
   * [minimumRequestBlockConfirmations, 200].
   * @param callbackGasLimit - How much gas you'd like to receive in your
   * fulfillRandomWords callback. Note that gasleft() inside fulfillRandomWords
   * may be slightly less than this amount because of gas used calling the function
   * (argument decoding etc.), so you may need to request slightly more than you expect
   * to have inside fulfillRandomWords. The acceptable range is
   * [0, maxGasLimit]
   * @param numWords - The number of uint256 random values you'd like to receive
   * in your fulfillRandomWords callback. Note these numbers are expanded in a
   * secure way by the VRFCoordinator from a single random value supplied by the oracle.
   * @return requestId - A unique identifier of the request. Can be used to match
   * a request to a response in fulfillRandomWords.
   */
  function requestRandomWords(
    bytes32 keyHash,
    uint64 subId,
    uint16 minimumRequestConfirmations,
    uint32 callbackGasLimit,
    uint32 numWords
  ) external returns (uint256 requestId);

  /**
   * @notice Create a VRF subscription.
   * @return subId - A unique subscription id.
   * @dev You can manage the consumer set dynamically with addConsumer/removeConsumer.
   * @dev Note to fund the subscription, use transferAndCall. For example
   * @dev  LINKTOKEN.transferAndCall(
   * @dev    address(COORDINATOR),
   * @dev    amount,
   * @dev    abi.encode(subId));
   */
  function createSubscription() external returns (uint64 subId);

  /**
   * @notice Get a VRF subscription.
   * @param subId - ID of the subscription
   * @return balance - LINK balance of the subscription in juels.
   * @return reqCount - number of requests for this subscription, determines fee tier.
   * @return owner - owner of the subscription.
   * @return consumers - list of consumer address which are able to use this subscription.
   */
  function getSubscription(uint64 subId)
    external
    view
    returns (
      uint96 balance,
      uint64 reqCount,
      address owner,
      address[] memory consumers
    );

  /**
   * @notice Request subscription owner transfer.
   * @param subId - ID of the subscription
   * @param newOwner - proposed new owner of the subscription
   */
  function requestSubscriptionOwnerTransfer(uint64 subId, address newOwner) external;

  /**
   * @notice Request subscription owner transfer.
   * @param subId - ID of the subscription
   * @dev will revert if original owner of subId has
   * not requested that msg.sender become the new owner.
   */
  function acceptSubscriptionOwnerTransfer(uint64 subId) external;

  /**
   * @notice Add a consumer to a VRF subscription.
   * @param subId - ID of the subscription
   * @param consumer - New consumer which can use the subscription
   */
  function addConsumer(uint64 subId, address consumer) external;

  /**
   * @notice Remove a consumer from a VRF subscription.
   * @param subId - ID of the subscription
   * @param consumer - Consumer to remove from the subscription
   */
  function removeConsumer(uint64 subId, address consumer) external;

  /**
   * @notice Cancel a subscription
   * @param subId - ID of the subscription
   * @param to - Where to send the remaining LINK to
   */
  function cancelSubscription(uint64 subId, address to) external;

  /*
   * @notice Check to see if there exists a request commitment consumers
   * for all consumers and keyhashes for a given sub.
   * @param subId - ID of the subscription
   * @return true if there exists at least one unfulfilled request for the subscription, false
   * otherwise.
   */
  function pendingRequestExists(uint64 subId) external view returns (bool);
}

// File: node_modules/@chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol



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

/** ****************************************************************************
 * @notice Interface for contracts using VRF randomness
 * *****************************************************************************
 * @dev PURPOSE
 *
 * @dev Reggie the Random Oracle (not his real job) wants to provide randomness
 * @dev to Vera the verifier in such a way that Vera can be sure he's not
 * @dev making his output up to suit himself. Reggie provides Vera a public key
 * @dev to which he knows the secret key. Each time Vera provides a seed to
 * @dev Reggie, he gives back a value which is computed completely
 * @dev deterministically from the seed and the secret key.
 *
 * @dev Reggie provides a proof by which Vera can verify that the output was
 * @dev correctly computed once Reggie tells it to her, but without that proof,
 * @dev the output is indistinguishable to her from a uniform random sample
 * @dev from the output space.
 *
 * @dev The purpose of this contract is to make it easy for unrelated contracts
 * @dev to talk to Vera the verifier about the work Reggie is doing, to provide
 * @dev simple access to a verifiable source of randomness. It ensures 2 things:
 * @dev 1. The fulfillment came from the VRFCoordinator
 * @dev 2. The consumer contract implements fulfillRandomWords.
 * *****************************************************************************
 * @dev USAGE
 *
 * @dev Calling contracts must inherit from VRFConsumerBase, and can
 * @dev initialize VRFConsumerBase's attributes in their constructor as
 * @dev shown:
 *
 * @dev   contract VRFConsumer {
 * @dev     constructor(<other arguments>, address _vrfCoordinator, address _link)
 * @dev       VRFConsumerBase(_vrfCoordinator) public {
 * @dev         <initialization with other arguments goes here>
 * @dev       }
 * @dev   }
 *
 * @dev The oracle will have given you an ID for the VRF keypair they have
 * @dev committed to (let's call it keyHash). Create subscription, fund it
 * @dev and your consumer contract as a consumer of it (see VRFCoordinatorInterface
 * @dev subscription management functions).
 * @dev Call requestRandomWords(keyHash, subId, minimumRequestConfirmations,
 * @dev callbackGasLimit, numWords),
 * @dev see (VRFCoordinatorInterface for a description of the arguments).
 *
 * @dev Once the VRFCoordinator has received and validated the oracle's response
 * @dev to your request, it will call your contract's fulfillRandomWords method.
 *
 * @dev The randomness argument to fulfillRandomWords is a set of random words
 * @dev generated from your requestId and the blockHash of the request.
 *
 * @dev If your contract could have concurrent requests open, you can use the
 * @dev requestId returned from requestRandomWords to track which response is associated
 * @dev with which randomness request.
 * @dev See "SECURITY CONSIDERATIONS" for principles to keep in mind,
 * @dev if your contract could have multiple requests in flight simultaneously.
 *
 * @dev Colliding `requestId`s are cryptographically impossible as long as seeds
 * @dev differ.
 *
 * *****************************************************************************
 * @dev SECURITY CONSIDERATIONS
 *
 * @dev A method with the ability to call your fulfillRandomness method directly
 * @dev could spoof a VRF response with any random value, so it's critical that
 * @dev it cannot be directly called by anything other than this base contract
 * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
 *
 * @dev For your users to trust that your contract's random behavior is free
 * @dev from malicious interference, it's best if you can write it so that all
 * @dev behaviors implied by a VRF response are executed *during* your
 * @dev fulfillRandomness method. If your contract must store the response (or
 * @dev anything derived from it) and use it later, you must ensure that any
 * @dev user-significant behavior which depends on that stored value cannot be
 * @dev manipulated by a subsequent VRF request.
 *
 * @dev Similarly, both miners and the VRF oracle itself have some influence
 * @dev over the order in which VRF responses appear on the blockchain, so if
 * @dev your contract could have multiple VRF requests in flight simultaneously,
 * @dev you must ensure that the order in which the VRF responses arrive cannot
 * @dev be used to manipulate your contract's user-significant behavior.
 *
 * @dev Since the block hash of the block which contains the requestRandomness
 * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
 * @dev miner could, in principle, fork the blockchain to evict the block
 * @dev containing the request, forcing the request to be included in a
 * @dev different block with a different hash, and therefore a different input
 * @dev to the VRF. However, such an attack would incur a substantial economic
 * @dev cost. This cost scales with the number of blocks the VRF oracle waits
 * @dev until it calls responds to a request. It is for this reason that
 * @dev that you can signal to an oracle you'd like them to wait longer before
 * @dev responding to the request (however this is not enforced in the contract
 * @dev and so remains effective only in the case of unmodified oracle software).
 */
abstract contract VRFConsumerBaseV2 {
  error OnlyCoordinatorCanFulfill(address have, address want);
  address private immutable vrfCoordinator;

  /**
   * @param _vrfCoordinator address of VRFCoordinator contract
   */
  constructor(address _vrfCoordinator) {
    vrfCoordinator = _vrfCoordinator;
  }

  /**
   * @notice fulfillRandomness handles the VRF response. Your contract must
   * @notice implement it. See "SECURITY CONSIDERATIONS" above for important
   * @notice principles to keep in mind when implementing your fulfillRandomness
   * @notice method.
   *
   * @dev VRFConsumerBaseV2 expects its subcontracts to have a method with this
   * @dev signature, and will call it once it has verified the proof
   * @dev associated with the randomness. (It is triggered via a call to
   * @dev rawFulfillRandomness, below.)
   *
   * @param requestId The Id initially returned by requestRandomness
   * @param randomWords the VRF output expanded to the requested number of words
   */
  function fulfillRandomWords(uint256 requestId, uint256[] memory randomWords) internal virtual;

  // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
  // proof. rawFulfillRandomness then calls fulfillRandomness, after validating
  // the origin of the call
  function rawFulfillRandomWords(uint256 requestId, uint256[] memory randomWords) external {
    if (msg.sender != vrfCoordinator) {
      revert OnlyCoordinatorCanFulfill(msg.sender, vrfCoordinator);
    }
    fulfillRandomWords(requestId, randomWords);
  }
}

// File: node_modules/erc721a/contracts/ERC721A.sol



// SPDX-License-Identifier: MIT
// ERC721A Contracts v4.2.3
// 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()`.
 *
 * 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;

    // =============================================================
    //                          CONSTRUCTOR
    // =============================================================

    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
        _currentIndex = _startTokenId();
    }

    // =============================================================
    //                   TOKEN COUNTING OPERATIONS
    // =============================================================

    /**
     * @dev Returns the starting token ID.
     * To change the starting token ID, please override this function.
     */
    function _startTokenId() internal view virtual returns (uint256) {
        return 0;
    }

    /**
     * @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) {
        // Counter underflow is impossible as _burnCounter cannot be incremented
        // more than `_currentIndex - _startTokenId()` times.
        unchecked {
            return _currentIndex - _burnCounter - _startTokenId();
        }
    }

    /**
     * @dev Returns the total amount of tokens minted in the contract.
     */
    function _totalMinted() internal view virtual returns (uint256) {
        // Counter underflow is impossible as `_currentIndex` does not decrement,
        // and it is initialized to `_startTokenId()`.
        unchecked {
            return _currentIndex - _startTokenId();
        }
    }

    /**
     * @dev Returns the total number of tokens burned.
     */
    function _totalBurned() internal view virtual returns (uint256) {
        return _burnCounter;
    }

    // =============================================================
    //                    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();
        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();

        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 Initializes the ownership slot minted at `index` for efficiency purposes.
     */
    function _initializeOwnershipAt(uint256 index) internal virtual {
        if (_packedOwnerships[index] == 0) {
            _packedOwnerships[index] = _packedOwnershipOf(index);
        }
    }

    /**
     * Returns the packed ownership data of `tokenId`.
     */
    function _packedOwnershipOf(uint256 tokenId) private view returns (uint256) {
        uint256 curr = tokenId;

        unchecked {
            if (_startTokenId() <= curr)
                if (curr < _currentIndex) {
                    uint256 packed = _packedOwnerships[curr];
                    // If not burned.
                    if (packed & _BITMASK_BURNED == 0) {
                        // 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, `curr` will not underflow.
                        //
                        // We can directly compare the packed value.
                        // If the address is zero, packed will be zero.
                        while (packed == 0) {
                            packed = _packedOwnerships[--curr];
                        }
                        return packed;
                    }
                }
        }
        revert OwnerQueryForNonexistentToken();
    }

    /**
     * @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.
     * 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) public payable virtual override {
        address owner = ownerOf(tokenId);

        if (_msgSenderERC721A() != owner)
            if (!isApprovedForAll(owner, _msgSenderERC721A())) {
                revert ApprovalCallerNotOwnerNorApproved();
            }

        _tokenApprovals[tokenId].value = to;
        emit Approval(owner, to, tokenId);
    }

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

        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) {
        return
            _startTokenId() <= tokenId &&
            tokenId < _currentIndex && // If within bounds,
            _packedOwnerships[tokenId] & _BITMASK_BURNED == 0; // and not 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);

        if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner();

        (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();

        if (to == address(0)) revert TransferToZeroAddress();

        _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;
                    }
                }
            }
        }

        emit Transfer(from, to, tokenId);
        _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();
            }
    }

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

        _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:
            // - `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)
            );

            uint256 toMasked;
            uint256 end = startTokenId + quantity;

            // Use assembly to loop and emit the `Transfer` event for gas savings.
            // The duplicated `log4` removes an extra check and reduces stack juggling.
            // The assembly, together with the surrounding Solidity code, have been
            // delicately arranged to nudge the compiler into producing optimized opcodes.
            assembly {
                // Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean.
                toMasked := and(to, _BITMASK_ADDRESS)
                // 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`.
                    startTokenId // `tokenId`.
                )

                // The `iszero(eq(,))` check ensures that large values of `quantity`
                // that overflows uint256 will make the loop run out of gas.
                // The compiler will optimize the `iszero` away for performance.
                for {
                    let tokenId := add(startTokenId, 1)
                } iszero(eq(tokenId, end)) {
                    tokenId := add(tokenId, 1)
                } {
                    // Emit the `Transfer` event. Similar to above.
                    log4(0, 0, _TRANSFER_EVENT_SIGNATURE, 0, toMasked, tokenId)
                }
            }
            if (toMasked == 0) revert MintToZeroAddress();

            _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();
        if (quantity == 0) revert MintZeroQuantity();
        if (quantity > _MAX_MINT_ERC2309_QUANTITY_LIMIT) revert MintERC2309QuantityExceedsLimit();

        _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)
            );

            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();
                    }
                } while (index < end);
                // Reentrancy protection.
                if (_currentIndex != end) revert();
            }
        }
    }

    /**
     * @dev Equivalent to `_safeMint(to, quantity, '')`.
     */
    function _safeMint(address to, uint256 quantity) internal virtual {
        _safeMint(to, quantity, '');
    }

    // =============================================================
    //                        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();
        }

        _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 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();
        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)
        }
    }
}

// File: contracts/libraries/UnsafeMathUint256.sol



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

library UnsafeMathUint256 {
  function unsafeAdd(uint256 a, uint256 b) internal pure returns (uint256) {
      unchecked {
          return a + b;
      }
  }

  function unsafeSubtract(uint256 a, uint256 b) internal pure returns (uint256) {
      unchecked {
          return a - b;
      }
  }

  function unsafeMultiply(uint256 a, uint256 b) internal pure returns (uint256) {
      unchecked {
          return a * b;
      }
  }

  function unsafeDivide(uint256 a, uint256 b) internal pure returns (uint256) {
      unchecked {
          return a / b;
      }
  }
}

// File: node_modules/@looksrare/contracts-libs/contracts/interfaces/IOwnableTwoSteps.sol



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

/**
 * @title IOwnableTwoSteps
 * @author LooksRare protocol team (👀,💎)
 */
interface IOwnableTwoSteps {
    /**
     * @notice This enum keeps track of the ownership status.
     * @param NoOngoingTransfer The default status when the owner is set
     * @param TransferInProgress The status when a transfer to a new owner is initialized
     * @param RenouncementInProgress The status when a transfer to address(0) is initialized
     */
    enum Status {
        NoOngoingTransfer,
        TransferInProgress,
        RenouncementInProgress
    }

    /**
     * @notice This is returned when there is no transfer of ownership in progress.
     */
    error NoOngoingTransferInProgress();

    /**
     * @notice This is returned when the caller is not the owner.
     */
    error NotOwner();

    /**
     * @notice This is returned when there is no renouncement in progress but
     *         the owner tries to validate the ownership renouncement.
     */
    error RenouncementNotInProgress();

    /**
     * @notice This is returned when the transfer is already in progress but the owner tries
     *         initiate a new ownership transfer.
     */
    error TransferAlreadyInProgress();

    /**
     * @notice This is returned when there is no ownership transfer in progress but the
     *         ownership change tries to be approved.
     */
    error TransferNotInProgress();

    /**
     * @notice This is returned when the ownership transfer is attempted to be validated by the
     *         a caller that is not the potential owner.
     */
    error WrongPotentialOwner();

    /**
     * @notice This is emitted if the ownership transfer is cancelled.
     */
    event CancelOwnershipTransfer();

    /**
     * @notice This is emitted if the ownership renouncement is initiated.
     */
    event InitiateOwnershipRenouncement();

    /**
     * @notice This is emitted if the ownership transfer is initiated.
     * @param previousOwner Previous/current owner
     * @param potentialOwner Potential/future owner
     */
    event InitiateOwnershipTransfer(address previousOwner, address potentialOwner);

    /**
     * @notice This is emitted when there is a new owner.
     */
    event NewOwner(address newOwner);
}

// File: node_modules/@looksrare/contracts-libs/contracts/interfaces/IReentrancyGuard.sol



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

/**
 * @title IReentrancyGuard
 * @author LooksRare protocol team (👀,💎)
 */
interface IReentrancyGuard {
    /**
     * @notice This is returned when there is a reentrant call.
     */
    error ReentrancyFail();
}

// File: node_modules/@looksrare/contracts-libs/contracts/errors/LowLevelErrors.sol



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

/**
 * @notice It is emitted if the ETH transfer fails.
 */
error ETHTransferFail();

/**
 * @notice It is emitted if the ERC20 approval fails.
 */
error ERC20ApprovalFail();

/**
 * @notice It is emitted if the ERC20 transfer fails.
 */
error ERC20TransferFail();

/**
 * @notice It is emitted if the ERC20 transferFrom fails.
 */
error ERC20TransferFromFail();

/**
 * @notice It is emitted if the ERC721 transferFrom fails.
 */
error ERC721TransferFromFail();

/**
 * @notice It is emitted if the ERC1155 safeTransferFrom fails.
 */
error ERC1155SafeTransferFromFail();

/**
 * @notice It is emitted if the ERC1155 safeBatchTransferFrom fails.
 */
error ERC1155SafeBatchTransferFromFail();

// File: node_modules/@looksrare/contracts-libs/contracts/errors/GenericErrors.sol



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

/**
 * @notice It is emitted if the call recipient is not a contract.
 */
error NotAContract();

// File: node_modules/@looksrare/contracts-libs/contracts/interfaces/generic/IWETH.sol



// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;

interface IWETH {
    function deposit() external payable;

    function transfer(address dst, uint256 wad) external returns (bool);

    function withdraw(uint256 wad) external;
}

// File: node_modules/@looksrare/contracts-transfer-manager/contracts/enums/TokenType.sol



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

enum TokenType {
    ERC20,
    ERC721,
    ERC1155
}

// File: node_modules/erc721a/contracts/IERC721A.sol



// SPDX-License-Identifier: MIT
// ERC721A Contracts v4.2.3
// 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();

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