- We're indexing this chain right now. Some of the counts may be inaccurate.

Contract Address Details

0xb26b4DC365843cDaE996F526913D3D4F45343aE8

Creator
0x046bf7–da7b9c at 0x8234c9–ed9aa7
Balance
0 LIT
Tokens
Fetching tokens...
Transactions
11 Transactions
Transfers
0 Transfers
Gas Used
5,403,921
Last Balance Update
2793387
Contract is not verified. However, we found a verified contract with the same bytecode in Blockscout DB 0x32c6667e6c74053f249bf218b83a105c47247125.
All metadata displayed below is from that contract. In order to verify current contract, click Verify & Publish button
Verify & Publish
Contract name:
PubkeyRouter




Optimization enabled
false
Compiler version
v0.8.17+commit.8df45f5f




Verified at
2023-09-11T06:35:00.233288Z

contracts/lit-node/PubkeyRouter.sol

//SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.17;

import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { PKPNFT } from "./PKPNFT.sol";
import { Staking } from "./Staking.sol";
import { ContractResolver } from "../lit-core/ContractResolver.sol";
import { IKeyDeriver } from "./HDKeyDeriver.sol";
import "solidity-bytes-utils/contracts/BytesLib.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";

import "hardhat/console.sol";

// TODO: make the tests send PKPNFT into the constructor
// TODO: test interaction between PKPNFT and this contract, like mint a keypair and see if you can access it
// TODO: setRoutingData() for a batch of keys
interface IPubkeyRouter {
    struct RootKey {
        bytes pubkey;
        uint256 keyType; // 1 = BLS, 2 = ECDSA.  Not doing this in an enum so we can add more keytypes in the future without redeploying.
    }

    struct Signature {
        bytes32 r;
        bytes32 s;
        uint8 v;
    }
}

contract PubkeyRouter is AccessControl {
    using EnumerableSet for EnumerableSet.AddressSet;
    using EnumerableSet for EnumerableSet.Bytes32Set;
    using EnumerableSet for EnumerableSet.UintSet;
    using BytesLib for bytes;

    /* ========== TYPE DEFINITIONS ========== */

    bytes32 public constant ADMIN_ROLE = keccak256("ADMIN"); // 0xdf8b4c520ffe197c5343c6f5aec59570151ef9a492f2c624fd45ddde6135ec42

    /* ========== STATE VARIABLES ========== */

    ContractResolver public contractResolver;
    ContractResolver.Env public env;

    struct PubkeyRoutingData {
        bytes pubkey;
        uint256 keyType; // 1 = BLS, 2 = ECDSA.  Not doing this in an enum so we can add more keytypes in the future without redeploying.
        bytes32 derivedKeyId;
    }

    struct VoteToRegisterRootKey {
        uint256 votes;
        mapping(address => bool) voted;
    }

    // map staking address -> uncompressed pubkey -> VoteToRegisterRootKey
    mapping(address => mapping(bytes => VoteToRegisterRootKey))
        public votesToRegisterRootKeys;

    // map the keccack256(uncompressed pubkey) -> PubkeyRoutingData
    mapping(uint256 => PubkeyRoutingData) public pubkeys;

    // map the eth address to a pkp id
    mapping(address => uint256) public ethAddressToPkpId;

    // map staking contract to root keys
    mapping(address => IPubkeyRouter.RootKey[]) public rootKeys;

    /* ========== CONSTRUCTOR ========== */
    constructor(address _resolver, ContractResolver.Env _env) {
        contractResolver = ContractResolver(_resolver);
        env = _env;
        _grantRole(ADMIN_ROLE, msg.sender);
        _setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE);
    }

    /* ========== VIEWS ========== */

    function getPkpNftAddress() public view returns (address) {
        return
            contractResolver.getContract(
                contractResolver.PKP_NFT_CONTRACT(),
                env
            );
    }

    /// get root keys for a given staking contract
    function getRootKeys(
        address stakingContract
    ) public view returns (IPubkeyRouter.RootKey[] memory) {
        return rootKeys[stakingContract];
    }

    /// get the routing data for a given key hash
    function getRoutingData(
        uint256 tokenId
    ) external view returns (PubkeyRoutingData memory) {
        return pubkeys[tokenId];
    }

    /// get if a given pubkey has routing data associated with it or not
    function isRouted(uint256 tokenId) public view returns (bool) {
        PubkeyRoutingData memory prd = pubkeys[tokenId];
        return
            prd.pubkey.length != 0 &&
            prd.keyType != 0 &&
            prd.derivedKeyId != bytes32(0);
    }

    /// get the eth address for the keypair, as long as it's an ecdsa keypair
    function getEthAddress(uint256 tokenId) public view returns (address) {
        return deriveEthAddressFromPubkey(pubkeys[tokenId].pubkey);
    }

    /// includes the 0x04 prefix so you can pass this directly to ethers.utils.computeAddress
    function getPubkey(uint256 tokenId) public view returns (bytes memory) {
        return pubkeys[tokenId].pubkey;
    }

    function deriveEthAddressFromPubkey(
        bytes memory pubkey
    ) public pure returns (address) {
        // remove 0x04 prefix
        bytes32 hashed = keccak256(pubkey.slice(1, 64));
        return address(uint160(uint256(hashed)));
    }

    function checkNodeSignatures(
        IPubkeyRouter.Signature[] memory signatures,
        bytes memory signedMessage,
        address stakingContractAddress
    ) public view returns (bool) {
        Staking stakingContract = Staking(stakingContractAddress);
        require(
            signatures.length ==
                stakingContract.getValidatorsInCurrentEpochLength(),
            "PubkeyRouter: incorrect number of signatures on a given root key"
        );
        for (uint256 i = 0; i < signatures.length; i++) {
            IPubkeyRouter.Signature memory sig = signatures[i];
            address signer = ECDSA.recover(
                ECDSA.toEthSignedMessageHash(signedMessage),
                sig.v,
                sig.r,
                sig.s
            );
            // console.log("signer: ");
            // console.log(signer);
            require(
                stakingContract.isActiveValidatorByNodeAddress(signer),
                "PubkeyRouter: signer is not active validator"
            );
        }
        return true;
    }

    /* ========== MUTATIVE FUNCTIONS ========== */

    /// register a pubkey and routing data for a given key hash
    function setRoutingData(
        uint256 tokenId,
        bytes memory pubkey,
        address stakingContractAddress,
        uint256 keyType,
        bytes32 derivedKeyId
    ) public {
        require(
            msg.sender == address(getPkpNftAddress()),
            "setRoutingData must be called by PKPNFT contract"
        );

        require(
            tokenId == uint256(keccak256(pubkey)),
            "tokenId does not match hashed pubkey"
        );
        require(
            !isRouted(tokenId),
            "PubkeyRouter: pubkey already has routing data"
        );

        pubkeys[tokenId].pubkey = pubkey;
        pubkeys[tokenId].keyType = keyType;
        pubkeys[tokenId].derivedKeyId = derivedKeyId;

        address pkpAddress = deriveEthAddressFromPubkey(pubkey);
        ethAddressToPkpId[pkpAddress] = tokenId;

        emit PubkeyRoutingDataSet(
            tokenId,
            pubkey,
            stakingContractAddress,
            keyType,
            derivedKeyId
        );
    }

    /// Set the pubkey and routing data for a given key hash
    // this is only used by an admin in case of emergency.  can prob be removed.
    function setRoutingDataAsAdmin(
        uint256 tokenId,
        bytes memory pubkey,
        address stakingContract,
        uint256 keyType,
        bytes32 derivedKeyId
    ) public {
        require(
            hasRole(ADMIN_ROLE, msg.sender),
            "PubkeyRouter: must have admin role"
        );
        pubkeys[tokenId].pubkey = pubkey;
        pubkeys[tokenId].keyType = keyType;
        pubkeys[tokenId].derivedKeyId = derivedKeyId;

        address pkpAddress = deriveEthAddressFromPubkey(pubkey);
        ethAddressToPkpId[pkpAddress] = tokenId;

        emit PubkeyRoutingDataSet(
            tokenId,
            pubkey,
            stakingContract,
            keyType,
            derivedKeyId
        );
    }

    function setContractResolver(
        address newResolverAddress
    ) public onlyRole(ADMIN_ROLE) {
        contractResolver = ContractResolver(newResolverAddress);
        emit ContractResolverAddressSet(newResolverAddress);
    }

    function voteForRootKeys(
        address stakingContractAddress,
        IPubkeyRouter.RootKey[] memory newRootKeys
    ) public {
        Staking stakingContract = Staking(stakingContractAddress);
        require(
            stakingContract.isActiveValidatorByNodeAddress(msg.sender),
            "PubkeyRouter: txn sender is not active validator"
        );

        require(
            rootKeys[stakingContractAddress].length == 0,
            "PubkeyRouter: root keys already set for this staking contract"
        );

        // record the votes
        for (uint i = 0; i < newRootKeys.length; i++) {
            IPubkeyRouter.RootKey memory rootKey = newRootKeys[i];
            require(
                votesToRegisterRootKeys[stakingContractAddress][rootKey.pubkey]
                    .voted[msg.sender] == false,
                "PubkeyRouter: validator has already voted for this root key"
            );
            votesToRegisterRootKeys[stakingContractAddress][rootKey.pubkey]
                .votes += 1;
            votesToRegisterRootKeys[stakingContractAddress][rootKey.pubkey]
                .voted[msg.sender] = true;

            // if it has enough votes, register it
            if (
                votesToRegisterRootKeys[stakingContractAddress][rootKey.pubkey]
                    .votes ==
                stakingContract.getValidatorsInCurrentEpochLength()
            ) {
                rootKeys[stakingContractAddress].push(rootKey);
                emit RootKeySet(stakingContractAddress, rootKey);
            }
        }
    }

    function getDerivedPubkey(
        address stakingContract,
        bytes32 derivedKeyId
    ) public view returns (bytes memory) {
        IPubkeyRouter.RootKey[] memory rootPubkeys = getRootKeys(
            stakingContract
        );

        bytes memory pubkey = _computeHDPubkey(derivedKeyId, rootPubkeys, 2);

        return pubkey;
    }

    function _computeHDPubkey(
        bytes32 derivedKeyId,
        IPubkeyRouter.RootKey[] memory rootHDKeys,
        uint256 keyType
    ) internal view returns (bytes memory) {
        address deriverAddr = contractResolver.getContract(
            contractResolver.HD_KEY_DERIVER_CONTRACT(),
            env
        );
        (bool success, bytes memory pubkey) = IKeyDeriver(deriverAddr)
            .computeHDPubKey(derivedKeyId, rootHDKeys, keyType);

        require(success, "PubkeyRouter: Failed public key calculation");
        return pubkey;
    }

    /* ========== EVENTS ========== */

    event PubkeyRoutingDataSet(
        uint256 indexed tokenId,
        bytes pubkey,
        address stakingContract,
        uint256 keyType,
        bytes32 derivedKeyId
    );
    event ContractResolverAddressSet(address newResolverAddress);
    event RootKeySet(address stakingContract, IPubkeyRouter.RootKey rootKey);
}
        

@openzeppelin/contracts/utils/Strings.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

import "./math/Math.sol";
import "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toString(int256 value) internal pure returns (string memory) {
        return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return keccak256(bytes(a)) == keccak256(bytes(b));
    }
}
          

@openzeppelin/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}
          

solidity-bytes-utils/contracts/BytesLib.sol

// SPDX-License-Identifier: Unlicense
/*
 * @title Solidity Bytes Arrays Utils
 * @author Gonçalo Sá <goncalo.sa@consensys.net>
 *
 * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
 *      The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
 */
pragma solidity >=0.8.0 <0.9.0;


library BytesLib {
    function concat(
        bytes memory _preBytes,
        bytes memory _postBytes
    )
        internal
        pure
        returns (bytes memory)
    {
        bytes memory tempBytes;

        assembly {
            // Get a location of some free memory and store it in tempBytes as
            // Solidity does for memory variables.
            tempBytes := mload(0x40)

            // Store the length of the first bytes array at the beginning of
            // the memory for tempBytes.
            let length := mload(_preBytes)
            mstore(tempBytes, length)

            // Maintain a memory counter for the current write location in the
            // temp bytes array by adding the 32 bytes for the array length to
            // the starting location.
            let mc := add(tempBytes, 0x20)
            // Stop copying when the memory counter reaches the length of the
            // first bytes array.
            let end := add(mc, length)

            for {
                // Initialize a copy counter to the start of the _preBytes data,
                // 32 bytes into its memory.
                let cc := add(_preBytes, 0x20)
            } lt(mc, end) {
                // Increase both counters by 32 bytes each iteration.
                mc := add(mc, 0x20)
                cc := add(cc, 0x20)
            } {
                // Write the _preBytes data into the tempBytes memory 32 bytes
                // at a time.
                mstore(mc, mload(cc))
            }

            // Add the length of _postBytes to the current length of tempBytes
            // and store it as the new length in the first 32 bytes of the
            // tempBytes memory.
            length := mload(_postBytes)
            mstore(tempBytes, add(length, mload(tempBytes)))

            // Move the memory counter back from a multiple of 0x20 to the
            // actual end of the _preBytes data.
            mc := end
            // Stop copying when the memory counter reaches the new combined
            // length of the arrays.
            end := add(mc, length)

            for {
                let cc := add(_postBytes, 0x20)
            } lt(mc, end) {
                mc := add(mc, 0x20)
                cc := add(cc, 0x20)
            } {
                mstore(mc, mload(cc))
            }

            // Update the free-memory pointer by padding our last write location
            // to 32 bytes: add 31 bytes to the end of tempBytes to move to the
            // next 32 byte block, then round down to the nearest multiple of
            // 32. If the sum of the length of the two arrays is zero then add
            // one before rounding down to leave a blank 32 bytes (the length block with 0).
            mstore(0x40, and(
              add(add(end, iszero(add(length, mload(_preBytes)))), 31),
              not(31) // Round down to the nearest 32 bytes.
            ))
        }

        return tempBytes;
    }

    function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {
        assembly {
            // Read the first 32 bytes of _preBytes storage, which is the length
            // of the array. (We don't need to use the offset into the slot
            // because arrays use the entire slot.)
            let fslot := sload(_preBytes.slot)
            // Arrays of 31 bytes or less have an even value in their slot,
            // while longer arrays have an odd value. The actual length is
            // the slot divided by two for odd values, and the lowest order
            // byte divided by two for even values.
            // If the slot is even, bitwise and the slot with 255 and divide by
            // two to get the length. If the slot is odd, bitwise and the slot
            // with -1 and divide by two.
            let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
            let mlength := mload(_postBytes)
            let newlength := add(slength, mlength)
            // slength can contain both the length and contents of the array
            // if length < 32 bytes so let's prepare for that
            // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
            switch add(lt(slength, 32), lt(newlength, 32))
            case 2 {
                // Since the new array still fits in the slot, we just need to
                // update the contents of the slot.
                // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
                sstore(
                    _preBytes.slot,
                    // all the modifications to the slot are inside this
                    // next block
                    add(
                        // we can just add to the slot contents because the
                        // bytes we want to change are the LSBs
                        fslot,
                        add(
                            mul(
                                div(
                                    // load the bytes from memory
                                    mload(add(_postBytes, 0x20)),
                                    // zero all bytes to the right
                                    exp(0x100, sub(32, mlength))
                                ),
                                // and now shift left the number of bytes to
                                // leave space for the length in the slot
                                exp(0x100, sub(32, newlength))
                            ),
                            // increase length by the double of the memory
                            // bytes length
                            mul(mlength, 2)
                        )
                    )
                )
            }
            case 1 {
                // The stored value fits in the slot, but the combined value
                // will exceed it.
                // get the keccak hash to get the contents of the array
                mstore(0x0, _preBytes.slot)
                let sc := add(keccak256(0x0, 0x20), div(slength, 32))

                // save new length
                sstore(_preBytes.slot, add(mul(newlength, 2), 1))

                // The contents of the _postBytes array start 32 bytes into
                // the structure. Our first read should obtain the `submod`
                // bytes that can fit into the unused space in the last word
                // of the stored array. To get this, we read 32 bytes starting
                // from `submod`, so the data we read overlaps with the array
                // contents by `submod` bytes. Masking the lowest-order
                // `submod` bytes allows us to add that value directly to the
                // stored value.

                let submod := sub(32, slength)
                let mc := add(_postBytes, submod)
                let end := add(_postBytes, mlength)
                let mask := sub(exp(0x100, submod), 1)

                sstore(
                    sc,
                    add(
                        and(
                            fslot,
                            0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
                        ),
                        and(mload(mc), mask)
                    )
                )

                for {
                    mc := add(mc, 0x20)
                    sc := add(sc, 1)
                } lt(mc, end) {
                    sc := add(sc, 1)
                    mc := add(mc, 0x20)
                } {
                    sstore(sc, mload(mc))
                }

                mask := exp(0x100, sub(mc, end))

                sstore(sc, mul(div(mload(mc), mask), mask))
            }
            default {
                // get the keccak hash to get the contents of the array
                mstore(0x0, _preBytes.slot)
                // Start copying to the last used word of the stored array.
                let sc := add(keccak256(0x0, 0x20), div(slength, 32))

                // save new length
                sstore(_preBytes.slot, add(mul(newlength, 2), 1))

                // Copy over the first `submod` bytes of the new data as in
                // case 1 above.
                let slengthmod := mod(slength, 32)
                let mlengthmod := mod(mlength, 32)
                let submod := sub(32, slengthmod)
                let mc := add(_postBytes, submod)
                let end := add(_postBytes, mlength)
                let mask := sub(exp(0x100, submod), 1)

                sstore(sc, add(sload(sc), and(mload(mc), mask)))

                for {
                    sc := add(sc, 1)
                    mc := add(mc, 0x20)
                } lt(mc, end) {
                    sc := add(sc, 1)
                    mc := add(mc, 0x20)
                } {
                    sstore(sc, mload(mc))
                }

                mask := exp(0x100, sub(mc, end))

                sstore(sc, mul(div(mload(mc), mask), mask))
            }
        }
    }

    function slice(
        bytes memory _bytes,
        uint256 _start,
        uint256 _length
    )
        internal
        pure
        returns (bytes memory)
    {
        require(_length + 31 >= _length, "slice_overflow");
        require(_bytes.length >= _start + _length, "slice_outOfBounds");

        bytes memory tempBytes;

        assembly {
            switch iszero(_length)
            case 0 {
                // Get a location of some free memory and store it in tempBytes as
                // Solidity does for memory variables.
                tempBytes := mload(0x40)

                // The first word of the slice result is potentially a partial
                // word read from the original array. To read it, we calculate
                // the length of that partial word and start copying that many
                // bytes into the array. The first word we copy will start with
                // data we don't care about, but the last `lengthmod` bytes will
                // land at the beginning of the contents of the new array. When
                // we're done copying, we overwrite the full first word with
                // the actual length of the slice.
                let lengthmod := and(_length, 31)

                // The multiplication in the next line is necessary
                // because when slicing multiples of 32 bytes (lengthmod == 0)
                // the following copy loop was copying the origin's length
                // and then ending prematurely not copying everything it should.
                let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
                let end := add(mc, _length)

                for {
                    // The multiplication in the next line has the same exact purpose
                    // as the one above.
                    let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
                } lt(mc, end) {
                    mc := add(mc, 0x20)
                    cc := add(cc, 0x20)
                } {
                    mstore(mc, mload(cc))
                }

                mstore(tempBytes, _length)

                //update free-memory pointer
                //allocating the array padded to 32 bytes like the compiler does now
                mstore(0x40, and(add(mc, 31), not(31)))
            }
            //if we want a zero-length slice let's just return a zero-length array
            default {
                tempBytes := mload(0x40)
                //zero out the 32 bytes slice we are about to return
                //we need to do it because Solidity does not garbage collect
                mstore(tempBytes, 0)

                mstore(0x40, add(tempBytes, 0x20))
            }
        }

        return tempBytes;
    }

    function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
        require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
        address tempAddress;

        assembly {
            tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
        }

        return tempAddress;
    }

    function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {
        require(_bytes.length >= _start + 1 , "toUint8_outOfBounds");
        uint8 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x1), _start))
        }

        return tempUint;
    }

    function toUint16(bytes memory _bytes, uint256 _start) internal pure returns (uint16) {
        require(_bytes.length >= _start + 2, "toUint16_outOfBounds");
        uint16 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x2), _start))
        }

        return tempUint;
    }

    function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32) {
        require(_bytes.length >= _start + 4, "toUint32_outOfBounds");
        uint32 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x4), _start))
        }

        return tempUint;
    }

    function toUint64(bytes memory _bytes, uint256 _start) internal pure returns (uint64) {
        require(_bytes.length >= _start + 8, "toUint64_outOfBounds");
        uint64 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x8), _start))
        }

        return tempUint;
    }

    function toUint96(bytes memory _bytes, uint256 _start) internal pure returns (uint96) {
        require(_bytes.length >= _start + 12, "toUint96_outOfBounds");
        uint96 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0xc), _start))
        }

        return tempUint;
    }

    function toUint128(bytes memory _bytes, uint256 _start) internal pure returns (uint128) {
        require(_bytes.length >= _start + 16, "toUint128_outOfBounds");
        uint128 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x10), _start))
        }

        return tempUint;
    }

    function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256) {
        require(_bytes.length >= _start + 32, "toUint256_outOfBounds");
        uint256 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x20), _start))
        }

        return tempUint;
    }

    function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32) {
        require(_bytes.length >= _start + 32, "toBytes32_outOfBounds");
        bytes32 tempBytes32;

        assembly {
            tempBytes32 := mload(add(add(_bytes, 0x20), _start))
        }

        return tempBytes32;
    }

    function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
        bool success = true;

        assembly {
            let length := mload(_preBytes)

            // if lengths don't match the arrays are not equal
            switch eq(length, mload(_postBytes))
            case 1 {
                // cb is a circuit breaker in the for loop since there's
                //  no said feature for inline assembly loops
                // cb = 1 - don't breaker
                // cb = 0 - break
                let cb := 1

                let mc := add(_preBytes, 0x20)
                let end := add(mc, length)

                for {
                    let cc := add(_postBytes, 0x20)
                // the next line is the loop condition:
                // while(uint256(mc < end) + cb == 2)
                } eq(add(lt(mc, end), cb), 2) {
                    mc := add(mc, 0x20)
                    cc := add(cc, 0x20)
                } {
                    // if any of these checks fails then arrays are not equal
                    if iszero(eq(mload(mc), mload(cc))) {
                        // unsuccess:
                        success := 0
                        cb := 0
                    }
                }
            }
            default {
                // unsuccess:
                success := 0
            }
        }

        return success;
    }

    function equalStorage(
        bytes storage _preBytes,
        bytes memory _postBytes
    )
        internal
        view
        returns (bool)
    {
        bool success = true;

        assembly {
            // we know _preBytes_offset is 0
            let fslot := sload(_preBytes.slot)
            // Decode the length of the stored array like in concatStorage().
            let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
            let mlength := mload(_postBytes)

            // if lengths don't match the arrays are not equal
            switch eq(slength, mlength)
            case 1 {
                // slength can contain both the length and contents of the array
                // if length < 32 bytes so let's prepare for that
                // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
                if iszero(iszero(slength)) {
                    switch lt(slength, 32)
                    case 1 {
                        // blank the last byte which is the length
                        fslot := mul(div(fslot, 0x100), 0x100)

                        if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
                            // unsuccess:
                            success := 0
                        }
                    }
                    default {
                        // cb is a circuit breaker in the for loop since there's
                        //  no said feature for inline assembly loops
                        // cb = 1 - don't breaker
                        // cb = 0 - break
                        let cb := 1

                        // get the keccak hash to get the contents of the array
                        mstore(0x0, _preBytes.slot)
                        let sc := keccak256(0x0, 0x20)

                        let mc := add(_postBytes, 0x20)
                        let end := add(mc, mlength)

                        // the next line is the loop condition:
                        // while(uint256(mc < end) + cb == 2)
                        for {} eq(add(lt(mc, end), cb), 2) {
                            sc := add(sc, 1)
                            mc := add(mc, 0x20)
                        } {
                            if iszero(eq(sload(sc), mload(mc))) {
                                // unsuccess:
                                success := 0
                                cb := 0
                            }
                        }
                    }
                }
            }
            default {
                // unsuccess:
                success := 0
            }
        }

        return success;
    }
}
          

@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {
    /**
     * @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);
}
          

contracts/lit-node/PKPPermissions.sol

//SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.17;

import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { BitMaps } from "@openzeppelin/contracts/utils/structs/BitMaps.sol";
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { ContractResolver } from "../lit-core/ContractResolver.sol";
import { PubkeyRouter } from "./PubkeyRouter.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";

import { PKPNFT } from "./PKPNFT.sol";
import "solidity-bytes-utils/contracts/BytesLib.sol";

import "hardhat/console.sol";

contract PKPPermissions is Ownable {
    using EnumerableSet for EnumerableSet.AddressSet;
    using EnumerableSet for EnumerableSet.Bytes32Set;
    using EnumerableSet for EnumerableSet.UintSet;
    using BytesLib for bytes;
    using BitMaps for BitMaps.BitMap;

    /* ========== STATE VARIABLES ========== */

    ContractResolver public contractResolver;
    ContractResolver.Env public env;

    enum AuthMethodType {
        NULLMETHOD, // 0
        ADDRESS, // 1
        ACTION, // 2
        WEBAUTHN, // 3
        DISCORD, // 4
        GOOGLE, // 5
        GOOGLE_JWT, // 6
        OTP, // 7
        APPLE_JWT, // 8
        STYTCH_JWT // 9
    }

    struct AuthMethod {
        uint256 authMethodType; // 1 = address, 2 = action, 3 = WebAuthn, 4 = Discord, 5 = Google, 6 = Google JWT, 7 = OTP, 8 = Apple JWT.  Not doing this in an enum so that we can add more auth methods in the future without redeploying.
        bytes id; // the id of the auth method.  For address, this is an eth address.  For action, this is an IPFS CID.  For WebAuthn, this is the credentialId.  For Discord, this is the user's Discord ID.  For Google, this is the user's Google ID.
        bytes userPubkey; // the user's pubkey.  This is used for WebAuthn.
    }

    // map the keccack256(uncompressed pubkey) -> set of auth methods
    mapping(uint256 => EnumerableSet.UintSet) permittedAuthMethods;

    // map the keccack256(uncompressed pubkey) -> auth_method_id -> scope id
    mapping(uint256 => mapping(uint256 => BitMaps.BitMap)) permittedAuthMethodScopes;

    // map the keccack256(authMethodType, userId) -> the actual AuthMethod struct
    mapping(uint256 => AuthMethod) public authMethods;

    // map the AuthMethod hash to the pubkeys that it's allowed to sign for
    // this makes it possible to be given a discord id and then lookup all the pubkeys that are allowed to sign for that discord id
    mapping(uint256 => EnumerableSet.UintSet) authMethodToPkpIds;

    // map the keccack256(uncompressed pubkey) -> (group => merkle tree root hash)
    mapping(uint256 => mapping(uint256 => bytes32)) private _rootHashes;

    /* ========== CONSTRUCTOR ========== */
    constructor(address _resolver, ContractResolver.Env _env) {
        contractResolver = ContractResolver(_resolver);
        env = _env;
    }

    /* ========== Modifier ========== */
    modifier onlyPKPOwner(uint256 tokenId) {
        // check that user is allowed to set this
        PKPNFT pkpNFT = PKPNFT(getPkpNftAddress());
        address nftOwner = pkpNFT.ownerOf(tokenId);
        require(msg.sender == nftOwner, "Not PKP NFT owner");
        _;
    }

    /* ========== VIEWS ========== */

    function getPkpNftAddress() public view returns (address) {
        return
            contractResolver.getContract(
                contractResolver.PKP_NFT_CONTRACT(),
                env
            );
    }

    function getRouterAddress() public view returns (address) {
        return
            contractResolver.getContract(
                contractResolver.PUB_KEY_ROUTER_CONTRACT(),
                env
            );
    }

    /// get the eth address for the keypair, as long as it's an ecdsa keypair
    function getEthAddress(uint256 tokenId) public view returns (address) {
        PubkeyRouter router = PubkeyRouter(getRouterAddress());
        return router.getEthAddress(tokenId);
    }

    /// includes the 0x04 prefix so you can pass this directly to ethers.utils.computeAddress
    function getPubkey(uint256 tokenId) public view returns (bytes memory) {
        PubkeyRouter router = PubkeyRouter(getRouterAddress());
        return router.getPubkey(tokenId);
    }

    function getAuthMethodId(
        uint256 authMethodType,
        bytes memory id
    ) public pure returns (uint256) {
        return uint256(keccak256(abi.encode(authMethodType, id)));
    }

    /// get the user's pubkey given their authMethodType and userId
    function getUserPubkeyForAuthMethod(
        uint256 authMethodType,
        bytes calldata id
    ) external view returns (bytes memory) {
        uint256 authMethodId = getAuthMethodId(authMethodType, id);
        AuthMethod memory am = authMethods[authMethodId];
        return am.userPubkey;
    }

    function getTokenIdsForAuthMethod(
        uint256 authMethodType,
        bytes calldata id
    ) external view returns (uint256[] memory) {
        uint256 authMethodId = getAuthMethodId(authMethodType, id);

        uint256 pkpIdsLength = authMethodToPkpIds[authMethodId].length();
        uint256[] memory allPkpIds = new uint256[](pkpIdsLength);

        for (uint256 i = 0; i < pkpIdsLength; i++) {
            allPkpIds[i] = authMethodToPkpIds[authMethodId].at(i);
        }

        return allPkpIds;
    }

    function getPermittedAuthMethods(
        uint256 tokenId
    ) external view returns (AuthMethod[] memory) {
        uint256 permittedAuthMethodsLength = permittedAuthMethods[tokenId]
            .length();
        AuthMethod[] memory allPermittedAuthMethods = new AuthMethod[](
            permittedAuthMethodsLength
        );

        for (uint256 i = 0; i < permittedAuthMethodsLength; i++) {
            uint256 authMethodHash = permittedAuthMethods[tokenId].at(i);
            allPermittedAuthMethods[i] = authMethods[authMethodHash];
        }

        return allPermittedAuthMethods;
    }

    function getPermittedAuthMethodScopes(
        uint256 tokenId,
        uint256 authMethodType,
        bytes calldata id,
        uint256 maxScopeId
    ) public view returns (bool[] memory) {
        uint256 authMethodId = getAuthMethodId(authMethodType, id);
        BitMaps.BitMap
            storage permittedScopesBitMap = permittedAuthMethodScopes[tokenId][
                authMethodId
            ];
        bool[] memory allScopes = new bool[](maxScopeId);

        for (uint256 i = 0; i < maxScopeId; i++) {
            allScopes[i] = permittedScopesBitMap.get(i);
        }

        return allScopes;
    }

    function getPermittedActions(
        uint256 tokenId
    ) public view returns (bytes[] memory) {
        uint256 permittedAuthMethodsLength = permittedAuthMethods[tokenId]
            .length();

        // count the number of auth methods that are actions
        uint256 permittedActionsLength = 0;
        for (uint256 i = 0; i < permittedAuthMethodsLength; i++) {
            uint256 authMethodHash = permittedAuthMethods[tokenId].at(i);
            AuthMethod memory am = authMethods[authMethodHash];
            if (am.authMethodType == uint256(AuthMethodType.ACTION)) {
                permittedActionsLength++;
            }
        }

        bytes[] memory allPermittedActions = new bytes[](
            permittedActionsLength
        );

        uint256 permittedActionsIndex = 0;
        for (uint256 i = 0; i < permittedAuthMethodsLength; i++) {
            uint256 authMethodHash = permittedAuthMethods[tokenId].at(i);
            AuthMethod memory am = authMethods[authMethodHash];
            if (am.authMethodType == uint256(AuthMethodType.ACTION)) {
                allPermittedActions[permittedActionsIndex] = am.id;
                permittedActionsIndex++;
            }
        }

        return allPermittedActions;
    }

    function getPermittedAddresses(
        uint256 tokenId
    ) public view returns (address[] memory) {
        uint256 permittedAuthMethodsLength = permittedAuthMethods[tokenId]
            .length();

        // count the number of auth methods that are addresses
        uint256 permittedAddressLength = 0;
        for (uint256 i = 0; i < permittedAuthMethodsLength; i++) {
            uint256 authMethodHash = permittedAuthMethods[tokenId].at(i);
            AuthMethod memory am = authMethods[authMethodHash];
            if (am.authMethodType == uint256(AuthMethodType.ADDRESS)) {
                permittedAddressLength++;
            }
        }

        PKPNFT pkpNFT = PKPNFT(getPkpNftAddress());
        bool tokenExists = pkpNFT.exists(tokenId);
        address[] memory allPermittedAddresses;
        uint256 permittedAddressIndex = 0;
        if (tokenExists) {
            // token is not burned, so add the owner address
            allPermittedAddresses = new address[](permittedAddressLength + 1);

            // always add nft owner in first slot
            address nftOwner = pkpNFT.ownerOf(tokenId);
            allPermittedAddresses[0] = nftOwner;
            permittedAddressIndex++;
        } else {
            // token is burned, so don't add the owner address
            allPermittedAddresses = new address[](permittedAddressLength);
        }

        for (uint256 i = 0; i < permittedAuthMethodsLength; i++) {
            uint256 authMethodHash = permittedAuthMethods[tokenId].at(i);
            AuthMethod memory am = authMethods[authMethodHash];
            if (am.authMethodType == uint256(AuthMethodType.ADDRESS)) {
                address parsed;
                bytes memory id = am.id;

                // address was packed using abi.encodedPacked(address), so you need to pad left to get the correct bytes back
                assembly {
                    parsed := div(
                        mload(add(id, 32)),
                        0x1000000000000000000000000
                    )
                }
                allPermittedAddresses[permittedAddressIndex] = parsed;
                permittedAddressIndex++;
            }
        }

        return allPermittedAddresses;
    }

    /// get if a user is permitted to use a given pubkey.  returns true if it is permitted to use the pubkey in the permittedAuthMethods[tokenId] struct.
    function isPermittedAuthMethod(
        uint256 tokenId,
        uint256 authMethodType,
        bytes memory id
    ) public view returns (bool) {
        uint256 authMethodId = getAuthMethodId(authMethodType, id);
        bool permitted = permittedAuthMethods[tokenId].contains(authMethodId);
        if (!permitted) {
            return false;
        }
        return true;
    }

    function isPermittedAuthMethodScopePresent(
        uint256 tokenId,
        uint256 authMethodType,
        bytes calldata id,
        uint256 scopeId
    ) public view returns (bool) {
        uint256 authMethodId = getAuthMethodId(authMethodType, id);
        bool present = permittedAuthMethodScopes[tokenId][authMethodId].get(
            scopeId
        );
        return present;
    }

    function isPermittedAction(
        uint256 tokenId,
        bytes calldata ipfsCID
    ) public view returns (bool) {
        return
            isPermittedAuthMethod(
                tokenId,
                uint256(AuthMethodType.ACTION),
                ipfsCID
            );
    }

    function isPermittedAddress(
        uint256 tokenId,
        address user
    ) public view returns (bool) {
        PKPNFT pkpNFT = PKPNFT(getPkpNftAddress());
        bool userIsOwner = false;
        if (pkpNFT.exists(tokenId)) {
            address nftOwner = pkpNFT.ownerOf(tokenId);
            userIsOwner = nftOwner == user;
        }
        return
            isPermittedAuthMethod(
                tokenId,
                uint256(AuthMethodType.ADDRESS),
                abi.encodePacked(user)
            ) || userIsOwner;
    }

    /* ========== MUTATIVE FUNCTIONS ========== */

    function batchAddRemoveAuthMethods(
        uint256 tokenId,
        uint256[] memory permittedAuthMethodTypesToAdd,
        bytes[] memory permittedAuthMethodIdsToAdd,
        bytes[] memory permittedAuthMethodPubkeysToAdd,
        uint256[][] calldata permittedAuthMethodScopesToAdd,
        uint256[] memory permittedAuthMethodTypesToRemove,
        bytes[] memory permittedAuthMethodIdsToRemove
    ) public onlyPKPOwner(tokenId) {
        require(
            permittedAuthMethodTypesToAdd.length ==
                permittedAuthMethodIdsToAdd.length &&
                permittedAuthMethodIdsToAdd.length ==
                permittedAuthMethodPubkeysToAdd.length &&
                permittedAuthMethodPubkeysToAdd.length ==
                permittedAuthMethodScopesToAdd.length,
            "Must have same number of auth methods, ids, pubkeys, and scopes to add"
        );

        require(
            permittedAuthMethodTypesToRemove.length ==
                permittedAuthMethodIdsToRemove.length,
            "Must have same number of auth methods and ids to remove"
        );

        for (uint256 i = 0; i < permittedAuthMethodTypesToAdd.length; i++) {
            addPermittedAuthMethod(
                tokenId,
                AuthMethod(
                    permittedAuthMethodTypesToAdd[i],
                    permittedAuthMethodIdsToAdd[i],
                    permittedAuthMethodPubkeysToAdd[i]
                ),
                permittedAuthMethodScopesToAdd[i]
            );
        }

        for (uint256 i = 0; i < permittedAuthMethodTypesToRemove.length; i++) {
            removePermittedAuthMethod(
                tokenId,
                permittedAuthMethodTypesToRemove[i],
                permittedAuthMethodIdsToRemove[i]
            );
        }
    }

    /// Add a permitted auth method for a given pubkey
    function addPermittedAuthMethod(
        uint256 tokenId,
        AuthMethod memory authMethod,
        uint256[] calldata scopes
    ) public onlyPKPOwner(tokenId) {
        uint256 authMethodId = getAuthMethodId(
            authMethod.authMethodType,
            authMethod.id
        );

        // we need to ensure that someone with the same auth method type and id can't add a different pubkey
        if (authMethod.authMethodType == uint(AuthMethodType.WEBAUTHN)) {
            require(
                authMethods[authMethodId].userPubkey.length == 0 ||
                    keccak256(authMethods[authMethodId].userPubkey) ==
                    keccak256(authMethod.userPubkey),
                "Cannot add a different pubkey for the same auth method type and id"
            );
        }

        authMethods[authMethodId] = authMethod;

        EnumerableSet.UintSet
            storage newPermittedAuthMethods = permittedAuthMethods[tokenId];
        newPermittedAuthMethods.add(authMethodId);

        EnumerableSet.UintSet storage newPkpIds = authMethodToPkpIds[
            authMethodId
        ];
        newPkpIds.add(tokenId);

        for (uint256 i = 0; i < scopes.length; i++) {
            uint256 scopeId = scopes[i];

            permittedAuthMethodScopes[tokenId][authMethodId].set(scopeId);

            emit PermittedAuthMethodScopeAdded(
                tokenId,
                authMethodId,
                authMethod.id,
                scopeId
            );
        }

        emit PermittedAuthMethodAdded(
            tokenId,
            authMethod.authMethodType,
            authMethod.id,
            authMethod.userPubkey
        );
    }

    // Remove a permitted auth method for a given pubkey
    function removePermittedAuthMethod(
        uint256 tokenId,
        uint256 authMethodType,
        bytes memory id
    ) public onlyPKPOwner(tokenId) {
        uint256 authMethodId = getAuthMethodId(authMethodType, id);

        EnumerableSet.UintSet
            storage newPermittedAuthMethods = permittedAuthMethods[tokenId];
        newPermittedAuthMethods.remove(authMethodId);

        EnumerableSet.UintSet storage newPkpIds = authMethodToPkpIds[
            authMethodId
        ];
        newPkpIds.remove(tokenId);

        emit PermittedAuthMethodRemoved(tokenId, authMethodId, id);
    }

    function addPermittedAuthMethodScope(
        uint256 tokenId,
        uint256 authMethodType,
        bytes calldata id,
        uint256 scopeId
    ) public onlyPKPOwner(tokenId) {
        uint256 authMethodId = getAuthMethodId(authMethodType, id);

        permittedAuthMethodScopes[tokenId][authMethodId].set(scopeId);

        emit PermittedAuthMethodScopeAdded(tokenId, authMethodId, id, scopeId);
    }

    function removePermittedAuthMethodScope(
        uint256 tokenId,
        uint256 authMethodType,
        bytes calldata id,
        uint256 scopeId
    ) public onlyPKPOwner(tokenId) {
        uint256 authMethodId = getAuthMethodId(authMethodType, id);

        permittedAuthMethodScopes[tokenId][authMethodId].unset(scopeId);

        emit PermittedAuthMethodScopeRemoved(
            tokenId,
            authMethodType,
            id,
            scopeId
        );
    }

    /// Add a permitted action for a given pubkey
    function addPermittedAction(
        uint256 tokenId,
        bytes calldata ipfsCID,
        uint256[] calldata scopes
    ) public {
        addPermittedAuthMethod(
            tokenId,
            AuthMethod(uint256(AuthMethodType.ACTION), ipfsCID, ""),
            scopes
        );
    }

    function removePermittedAction(
        uint256 tokenId,
        bytes calldata ipfsCID
    ) public {
        removePermittedAuthMethod(
            tokenId,
            uint256(AuthMethodType.ACTION),
            ipfsCID
        );
    }

    function addPermittedAddress(
        uint256 tokenId,
        address user,
        uint256[] calldata scopes
    ) public {
        addPermittedAuthMethod(
            tokenId,
            AuthMethod(
                uint256(AuthMethodType.ADDRESS),
                abi.encodePacked(user),
                ""
            ),
            scopes
        );
    }

    function removePermittedAddress(uint256 tokenId, address user) public {
        removePermittedAuthMethod(
            tokenId,
            uint256(AuthMethodType.ADDRESS),
            abi.encodePacked(user)
        );
    }

    function setContractResolver(address newResolverAddress) public onlyOwner {
        contractResolver = ContractResolver(newResolverAddress);
        emit ContractResolverAddressSet(newResolverAddress);
    }

    /**
     * Update the root hash of the merkle tree representing off-chain states for the PKP
     */
    function setRootHash(
        uint256 tokenId,
        uint256 group,
        bytes32 root
    ) public onlyPKPOwner(tokenId) {
        _rootHashes[tokenId][group] = root;
        emit RootHashUpdated(tokenId, group, root);
    }

    /**
     * Verify the given leaf existing in the merkle tree
     */
    function verifyState(
        uint256 tokenId,
        uint256 group,
        bytes32[] memory proof,
        bytes32 leaf
    ) public view returns (bool) {
        bytes32 root = _rootHashes[tokenId][group];
        if (root == bytes32(0)) return false;
        return MerkleProof.verify(proof, root, leaf);
    }

    /**
     * Verify the given leaves existing in the merkle tree
     */
    function verifyStates(
        uint256 tokenId,
        uint256 group,
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32[] memory leaves
    ) public view returns (bool) {
        bytes32 root = _rootHashes[tokenId][group];
        if (root == bytes32(0)) return false;
        return MerkleProof.multiProofVerify(proof, proofFlags, root, leaves);
    }

    /* ========== EVENTS ========== */

    event PermittedAuthMethodAdded(
        uint256 indexed tokenId,
        uint256 authMethodType,
        bytes id,
        bytes userPubkey
    );
    event PermittedAuthMethodRemoved(
        uint256 indexed tokenId,
        uint256 authMethodType,
        bytes id
    );
    event PermittedAuthMethodScopeAdded(
        uint256 indexed tokenId,
        uint256 authMethodType,
        bytes id,
        uint256 scopeId
    );
    event PermittedAuthMethodScopeRemoved(
        uint256 indexed tokenId,
        uint256 authMethodType,
        bytes id,
        uint256 scopeId
    );
    event RootHashUpdated(
        uint256 indexed tokenId,
        uint256 indexed group,
        bytes32 root
    );
    event ContractResolverAddressSet(address newResolverAddress);
}
          

@openzeppelin/contracts/access/AccessControl.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol)

pragma solidity ^0.8.0;

import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControl is Context, IAccessControl, ERC165 {
    struct RoleData {
        mapping(address => bool) members;
        bytes32 adminRole;
    }

    mapping(bytes32 => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with a standardized message including the required role.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     *
     * _Available since v4.1._
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
        return _roles[role].members[account];
    }

    /**
     * @dev Revert with a standard message if `_msgSender()` is missing `role`.
     * Overriding this function changes the behavior of the {onlyRole} modifier.
     *
     * Format of the revert message is described in {_checkRole}.
     *
     * _Available since v4.6._
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Revert with a standard message if `account` is missing `role`.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert(
                string(
                    abi.encodePacked(
                        "AccessControl: account ",
                        Strings.toHexString(account),
                        " is missing role ",
                        Strings.toHexString(uint256(role), 32)
                    )
                )
            );
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address account) public virtual override {
        require(account == _msgSender(), "AccessControl: can only renounce roles for self");

        _revokeRole(role, account);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event. Note that unlike {grantRole}, this function doesn't perform any
     * checks on the calling account.
     *
     * May emit a {RoleGranted} event.
     *
     * [WARNING]
     * ====
     * This function should only be called from the constructor when setting
     * up the initial roles for the system.
     *
     * Using this function in any other way is effectively circumventing the admin
     * system imposed by {AccessControl}.
     * ====
     *
     * NOTE: This function is deprecated in favor of {_grantRole}.
     */
    function _setupRole(bytes32 role, address account) internal virtual {
        _grantRole(role, account);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual {
        if (!hasRole(role, account)) {
            _roles[role].members[account] = true;
            emit RoleGranted(role, account, _msgSender());
        }
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual {
        if (hasRole(role, account)) {
            _roles[role].members[account] = false;
            emit RoleRevoked(role, account, _msgSender());
        }
    }
}
          

@openzeppelin/contracts/utils/cryptography/ECDSA.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.0;

import "../Strings.sol";

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS,
        InvalidSignatureV // Deprecated in v4.8
    }

    function _throwError(RecoverError error) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert("ECDSA: invalid signature");
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert("ECDSA: invalid signature length");
        } else if (error == RecoverError.InvalidSignatureS) {
            revert("ECDSA: invalid signature 's' value");
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature` or error string. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            /// @solidity memory-safe-assembly
            assembly {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength);
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, signature);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {
        bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
        uint8 v = uint8((uint256(vs) >> 255) + 27);
        return tryRecover(hash, v, r, s);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     *
     * _Available since v4.2._
     */
    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, r, vs);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature);
        }

        return (signer, RecoverError.NoError);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from a `hash`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
        // 32 is the length in bytes of hash,
        // enforced by the type signature above
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, "\x19Ethereum Signed Message:\n32")
            mstore(0x1c, hash)
            message := keccak256(0x00, 0x3c)
        }
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from `s`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
    }

    /**
     * @dev Returns an Ethereum Signed Typed Data, created from a
     * `domainSeparator` and a `structHash`. This produces hash corresponding
     * to the one signed with the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
     * JSON-RPC method as part of EIP-712.
     *
     * See {recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, "\x19\x01")
            mstore(add(ptr, 0x02), domainSeparator)
            mstore(add(ptr, 0x22), structHash)
            data := keccak256(ptr, 0x42)
        }
    }

    /**
     * @dev Returns an Ethereum Signed Data with intended validator, created from a
     * `validator` and `data` according to the version 0 of EIP-191.
     *
     * See {recover}.
     */
    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x00", validator, data));
    }
}
          

@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)

pragma solidity ^0.8.0;

import "../IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Enumerable is IERC721 {
    /**
     * @dev Returns the total amount of tokens stored by the contract.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns a token ID owned by `owner` at a given `index` of its token list.
     * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);

    /**
     * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
     * Use along with {totalSupply} to enumerate all tokens.
     */
    function tokenByIndex(uint256 index) external view returns (uint256);
}
          

@openzeppelin/contracts/token/ERC721/IERC721.sol

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

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @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`.
     *
     * 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 calldata data) external;

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

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * 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;

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

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

@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)

pragma solidity ^0.8.0;

/**
 * @title ERC721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
     *
     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}
          

contracts/lit-core/ContractResolver.sol

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/access/AccessControl.sol";

import "hardhat/console.sol";

contract ContractResolver is AccessControl {
    /* ========== TYPE DEFINITIONS ========== */

    // the comments following each one of these are the keccak256 hashes of the string values
    // this is very useful if you have to manually set any of these, so that you
    // don't have to calculate the hahes yourself.

    bytes32 public constant ADMIN_ROLE = keccak256("ADMIN"); // 0xdf8b4c520ffe197c5343c6f5aec59570151ef9a492f2c624fd45ddde6135ec42

    bytes32 public constant RELEASE_REGISTER_CONTRACT =
        keccak256("RELEASE_REGISTER"); // 0x3a68dbfd8bbb64015c42bc131c388dea7965e28c1004d09b39f59500c3a763ec
    bytes32 public constant STAKING_CONTRACT = keccak256("STAKING"); // 0x080909c18c958ce5a2d36481697824e477319323d03154ceba3b78f28a61887b
    bytes32 public constant STAKING_BALANCES_CONTRACT =
        keccak256("STAKING_BALANCES"); // 0xaa06d108dbd7bf976b16b7bf5adb29d2d0ef2c385ca8b9d833cc802f33942d72
    bytes32 public constant MULTI_SENDER_CONTRACT = keccak256("MULTI_SENDER"); // 0xdd5b9b8a5e8e01f2962ed7e983d58fe32e1f66aa88dd7ab30770fa9b77da7243
    bytes32 public constant LIT_TOKEN_CONTRACT = keccak256("LIT_TOKEN");
    bytes32 public constant PUB_KEY_ROUTER_CONTRACT =
        keccak256("PUB_KEY_ROUTER"); // 0xb1f79813bc7630a52ae948bc99781397e409d0dd3521953bf7d8d7a2db6147f7
    bytes32 public constant PKP_NFT_CONTRACT = keccak256("PKP_NFT"); // 0xb7b4fde9944d3c13e9a78835431c33a5084d90a7f0c73def76d7886315fe87b0
    bytes32 public constant RATE_LIMIT_NFT_CONTRACT =
        keccak256("RATE_LIMIT_NFT"); // 0xb931b2719aeb2a65a5035fa0a190bfdc4c8622ce8cbff7a3d1ab42531fb1a918
    bytes32 public constant PKP_HELPER_CONTRACT = keccak256("PKP_HELPER"); // 0x27d764ea2a4a3865434bbf4a391110149644be31448f3479fd15b44388755765
    bytes32 public constant PKP_PERMISSIONS_CONTRACT =
        keccak256("PKP_PERMISSIONS"); // 0x54953c23068b8fc4c0736301b50f10027d6b469327de1fd42841a5072b1bcebe
    bytes32 public constant PKP_NFT_METADATA_CONTRACT =
        keccak256("PKP_NFT_METADATA"); // 0xf14f431dadc82e7dbc5e379f71234e5735c9187e4327a7c6ac014d55d1b7727a
    bytes32 public constant ALLOWLIST_CONTRACT = keccak256("ALLOWLIST"); // 0x74845de37cfabd357633214b47fa91ccd19b05b7c5a08ac22c187f811fb62bca
    bytes32 public constant DOMAIN_WALLET_ORACLE =
        keccak256("DOMAIN_WALLET_ORACLE");
    bytes32 public constant DOMAIN_WALLET_REGISTRY =
        keccak256("DOMAIN_WALLET_REGISTRY");
    bytes32 public constant HD_KEY_DERIVER_CONTRACT =
        keccak256("HD_KEY_DERIVER");

    enum Env {
        Dev,
        Staging,
        Prod
    }

    /* ========== ERRORS ========== */

    /// The ADMIN role is required to use this function
    error AdminRoleRequired();

    /* ========== EVENTS ========== */

    event AllowedEnvAdded(Env env);

    event AllowedEnvRemoved(Env env);

    event SetContract(bytes32 typ, Env env, address addr);

    /* ========== STATE VARIABLES ========== */

    mapping(Env => bool) allowedEnvs;
    mapping(bytes32 => mapping(Env => address)) public typeAddresses;

    /* ========== CONSTRUCTOR ========== */

    constructor(Env env) {
        _setupRole(ADMIN_ROLE, msg.sender);
        _setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE);

        allowedEnvs[env] = true;

        emit AllowedEnvAdded(env);
    }

    /* ========== MUTATIVE FUNCTIONS ========== */

    /// add an allowed env
    function addAllowedEnv(Env env) public {
        // Check roles
        if (!hasRole(ADMIN_ROLE, msg.sender)) {
            revert AdminRoleRequired();
        }

        allowedEnvs[env] = true;

        emit AllowedEnvAdded(env);
    }

    /// remove an allowed env
    function removeAllowedEnv(Env env) public {
        // Check roles
        if (!hasRole(ADMIN_ROLE, msg.sender)) {
            revert AdminRoleRequired();
        }

        delete allowedEnvs[env];

        emit AllowedEnvRemoved(env);
    }

    /// set the active address for a deployed contract
    function setContract(bytes32 typ, Env env, address addr) public {
        // Check roles
        if (!hasRole(ADMIN_ROLE, msg.sender)) {
            revert AdminRoleRequired();
        }

        // Ensure the env is available
        require(
            allowedEnvs[env] == true,
            "The provided Env is not valid for this contract"
        );

        // Set the contract address
        typeAddresses[typ][env] = addr;

        // Emit events
        emit SetContract(typ, env, addr);
    }

    function setAdmin(address newAdmin) public {
        if (!hasRole(ADMIN_ROLE, msg.sender)) {
            revert AdminRoleRequired();
        }
        _grantRole(ADMIN_ROLE, newAdmin);
        _revokeRole(ADMIN_ROLE, msg.sender);
    }

    /* ========== VIEWS ========== */

    /// Returns the matching contract address for a given type and env
    function getContract(bytes32 typ, Env env) public view returns (address) {
        return (typeAddresses[typ][env]);
    }
}
          

@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol)

pragma solidity ^0.8.0;

import "../ERC20.sol";
import "../../../utils/Context.sol";

/**
 * @dev Extension of {ERC20} that allows token holders to destroy both their own
 * tokens and those that they have an allowance for, in a way that can be
 * recognized off-chain (via event analysis).
 */
abstract contract ERC20Burnable is Context, ERC20 {
    /**
     * @dev Destroys `amount` tokens from the caller.
     *
     * See {ERC20-_burn}.
     */
    function burn(uint256 amount) public virtual {
        _burn(_msgSender(), amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, deducting from the caller's
     * allowance.
     *
     * See {ERC20-_burn} and {ERC20-allowance}.
     *
     * Requirements:
     *
     * - the caller must have allowance for ``accounts``'s tokens of at least
     * `amount`.
     */
    function burnFrom(address account, uint256 amount) public virtual {
        _spendAllowance(account, _msgSender(), amount);
        _burn(account, amount);
    }
}
          

@openzeppelin/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
          

contracts/lit-node/PKPNFT.sol

//SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.17;

import { ERC721 } from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import { IERC721 } from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IPubkeyRouter, PubkeyRouter } from "./PubkeyRouter.sol";
import { PKPPermissions } from "./PKPPermissions.sol";
import { PKPNFTMetadata } from "./PKPNFTMetadata.sol";
import { ContractResolver } from "../lit-core/ContractResolver.sol";
import { ERC721Burnable } from "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import { ERC721Enumerable } from "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import { IERC721Enumerable } from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import { IERC721Metadata } from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";

import "hardhat/console.sol";

// TODO: tests for the mintGrantAndBurn function, withdraw function, some of the setters, transfer function, freeMint and freeMintGrantAndBurn

/// @title Programmable Keypair NFT
///
/// @dev This is the contract for the PKP NFTs
///
/// Simply put, whomever owns a PKP NFT can ask that PKP to sign a message.
/// The owner can also grant signing permissions to other eth addresses
/// or lit actions
contract PKPNFT is
    ERC721("Programmable Keypair", "PKP"),
    Ownable,
    ERC721Burnable,
    ERC721Enumerable
{
    /* ========== STATE VARIABLES ========== */
    ContractResolver public contractResolver;
    uint256 public mintCost;
    address public freeMintSigner;
    ContractResolver.Env public env;

    mapping(uint256 => bool) public redeemedFreeMintIds;

    /* ========== CONSTRUCTOR ========== */
    constructor(address resolverAddress, ContractResolver.Env _env) {
        mintCost = 1; // 1 wei aka 0.000000000000000001 eth
        freeMintSigner = msg.sender;
        contractResolver = ContractResolver(resolverAddress);
        env = _env;
    }

    /* ========== VIEWS ========== */

    /// get the staking address from the resolver
    function getStakingAddress() public view returns (address) {
        return
            contractResolver.getContract(
                contractResolver.STAKING_CONTRACT(),
                env
            );
    }

    function getRouterAddress() public view returns (address) {
        return
            contractResolver.getContract(
                contractResolver.PUB_KEY_ROUTER_CONTRACT(),
                env
            );
    }

    function getPkpNftMetadataAddress() public view returns (address) {
        return
            contractResolver.getContract(
                contractResolver.PKP_NFT_METADATA_CONTRACT(),
                env
            );
    }

    function getPkpPermissionsAddress() public view returns (address) {
        return
            contractResolver.getContract(
                contractResolver.PKP_PERMISSIONS_CONTRACT(),
                env
            );
    }

    /// get the eth address for the keypair
    function getEthAddress(uint256 tokenId) public view returns (address) {
        PubkeyRouter router = PubkeyRouter(getRouterAddress());
        return router.getEthAddress(tokenId);
    }

    /// includes the 0x04 prefix so you can pass this directly to ethers.utils.computeAddress
    function getPubkey(uint256 tokenId) public view returns (bytes memory) {
        PubkeyRouter router = PubkeyRouter(getRouterAddress());
        return router.getPubkey(tokenId);
    }

    function supportsInterface(
        bytes4 interfaceId
    ) public view virtual override(ERC721, ERC721Enumerable) returns (bool) {
        return
            interfaceId == type(IERC721Enumerable).interfaceId ||
            interfaceId == type(IERC721Metadata).interfaceId ||
            interfaceId == type(IERC721).interfaceId;
    }

    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 tokenId,
        uint256 batchSize
    ) internal virtual override(ERC721, ERC721Enumerable) {
        ERC721Enumerable._beforeTokenTransfer(from, to, tokenId, batchSize);
    }

    function tokenURI(
        uint256 tokenId
    ) public view override returns (string memory) {
        PubkeyRouter router = PubkeyRouter(getRouterAddress());
        bytes memory pubKey = router.getPubkey(tokenId);
        address ethAddress = router.getEthAddress(tokenId);

        PKPNFTMetadata pkpNftMetadata = PKPNFTMetadata(
            getPkpNftMetadataAddress()
        );
        return pkpNftMetadata.tokenURI(tokenId, pubKey, ethAddress);
    }

    // Builds a prefixed hash to mimic the behavior of eth_sign.
    function prefixed(bytes32 hash) public pure returns (bytes32) {
        return
            keccak256(
                abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)
            );
    }

    function exists(uint256 tokenId) public view returns (bool) {
        return _exists(tokenId);
    }

    function getNextDerivedKeyId() public view returns (bytes32) {
        uint256 tokenCount = totalSupply() + 1;
        // hash(tokenCount, previousBlockHash)
        bytes32 derivedKeyId = keccak256(
            abi.encodePacked(tokenCount, blockhash(block.number - 1))
        );

        return derivedKeyId;
    }

    /* ========== MUTATIVE FUNCTIONS ========== */

    function mintNext(uint256 keyType) public payable returns (uint256) {
        require(msg.value == mintCost, "You must pay exactly mint cost");
        PubkeyRouter router = PubkeyRouter(getRouterAddress());
        bytes32 derivedKeyId = getNextDerivedKeyId();
        bytes memory pubkey = router.getDerivedPubkey(
            getStakingAddress(),
            derivedKeyId
        );
        uint256 tokenId = uint256(keccak256(pubkey));
        routeDerivedKey(keyType, derivedKeyId);
        _mintWithoutValueCheck(tokenId, msg.sender);
        return tokenId;
    }

    function claimAndMint(
        uint256 keyType,
        bytes32 derivedKeyId,
        IPubkeyRouter.Signature[] memory signatures
    ) public payable returns (uint256) {
        require(msg.value == mintCost, "You must pay exactly mint cost");
        PubkeyRouter router = PubkeyRouter(getRouterAddress());
        router.checkNodeSignatures(
            signatures,
            abi.encodePacked(derivedKeyId),
            getStakingAddress()
        );
        bytes memory pubkey = router.getDerivedPubkey(
            getStakingAddress(),
            derivedKeyId
        );
        uint256 tokenId = uint256(keccak256(pubkey));

        routeDerivedKey(keyType, derivedKeyId);
        _mintWithoutValueCheck(tokenId, msg.sender);

        return tokenId;
    }

    function mintGrantAndBurnNext(
        uint256 keyType,
        bytes memory ipfsCID
    ) public payable returns (uint256) {
        require(msg.value == mintCost, "You must pay exactly mint cost");
        PubkeyRouter router = PubkeyRouter(getRouterAddress());
        bytes32 derivedKeyId = getNextDerivedKeyId();
        bytes memory pubkey = router.getDerivedPubkey(
            getStakingAddress(),
            derivedKeyId
        );
        uint256 tokenId = uint256(keccak256(pubkey));
        routeDerivedKey(keyType, derivedKeyId);
        _mintWithoutValueCheck(tokenId, address(this));
        PKPPermissions pkpPermissions = PKPPermissions(
            getPkpPermissionsAddress()
        );
        pkpPermissions.addPermittedAction(tokenId, ipfsCID, new uint256[](0));
        _burn(tokenId);
        return tokenId;
    }

    function routeDerivedKey(uint256 keyType, bytes32 derivedKeyId) internal {
        PubkeyRouter router = PubkeyRouter(getRouterAddress());
        bytes memory pubkey = router.getDerivedPubkey(
            getStakingAddress(),
            derivedKeyId
        );
        uint256 tokenId = uint256(keccak256(pubkey));

        PubkeyRouter(getRouterAddress()).setRoutingData(
            tokenId,
            pubkey,
            address(getStakingAddress()),
            keyType,
            derivedKeyId
        );
    }

    function _mintWithoutValueCheck(uint256 tokenId, address to) internal {
        PubkeyRouter router = PubkeyRouter(getRouterAddress());
        require(router.isRouted(tokenId), "This PKP has not been routed yet");

        if (to == address(this)) {
            // permit unsafe transfer only to this contract, because it's going to be burned
            _mint(to, tokenId);
        } else {
            _safeMint(to, tokenId);
        }
        emit PKPMinted(tokenId, getPubkey(tokenId));
    }

    function setMintCost(uint256 newMintCost) public onlyOwner {
        mintCost = newMintCost;
        emit MintCostSet(newMintCost);
    }

    function setFreeMintSigner(address newFreeMintSigner) public onlyOwner {
        freeMintSigner = newFreeMintSigner;
        emit FreeMintSignerSet(newFreeMintSigner);
    }

    function setContractResolver(address newResolverAddress) public onlyOwner {
        contractResolver = ContractResolver(newResolverAddress);
        emit ContractResolverAddressSet(newResolverAddress);
    }

    function withdraw() public onlyOwner {
        uint256 withdrawAmount = address(this).balance;
        (bool sent, ) = payable(msg.sender).call{ value: withdrawAmount }("");
        require(sent);
        emit Withdrew(withdrawAmount);
    }

    /* ========== EVENTS ========== */

    event MintCostSet(uint256 newMintCost);
    event FreeMintSignerSet(address indexed newFreeMintSigner);
    event Withdrew(uint256 amount);
    event PKPMinted(uint256 indexed tokenId, bytes pubkey);
    event ContractResolverAddressSet(address newResolverAddress);
}
          

@openzeppelin/contracts/utils/cryptography/MerkleProof.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.2) (utils/cryptography/MerkleProof.sol)

pragma solidity ^0.8.0;

/**
 * @dev These functions deal with verification of Merkle Tree proofs.
 *
 * The tree and the proofs can be generated using our
 * https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
 * You will find a quickstart guide in the readme.
 *
 * WARNING: You should avoid using leaf values that are 64 bytes long prior to
 * hashing, or use a hash function other than keccak256 for hashing leaves.
 * This is because the concatenation of a sorted pair of internal nodes in
 * the merkle tree could be reinterpreted as a leaf value.
 * OpenZeppelin's JavaScript library generates merkle trees that are safe
 * against this attack out of the box.
 */
library MerkleProof {
    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     */
    function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
        return processProof(proof, leaf) == root;
    }

    /**
     * @dev Calldata version of {verify}
     *
     * _Available since v4.7._
     */
    function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
        return processProofCalldata(proof, leaf) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leafs & pre-images are assumed to be sorted.
     *
     * _Available since v4.4._
     */
    function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = _hashPair(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Calldata version of {processProof}
     *
     * _Available since v4.7._
     */
    function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = _hashPair(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * _Available since v4.7._
     */
    function multiProofVerify(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProof(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Calldata version of {multiProofVerify}
     *
     * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * _Available since v4.7._
     */
    function multiProofVerifyCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProofCalldata(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * CAUTION: Not all merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * _Available since v4.7._
     */
    function processMultiProof(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32[] memory leaves
    ) internal pure returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofLen = proof.length;
        uint256 totalHashes = proofFlags.length;

        // Check proof validity.
        require(leavesLen + proofLen - 1 == totalHashes, "MerkleProof: invalid multiproof");

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](totalHashes);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < totalHashes; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = _hashPair(a, b);
        }

        if (totalHashes > 0) {
            require(proofPos == proofLen, "MerkleProof: invalid multiproof");
            unchecked {
                return hashes[totalHashes - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Calldata version of {processMultiProof}.
     *
     * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * _Available since v4.7._
     */
    function processMultiProofCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32[] memory leaves
    ) internal pure returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofLen = proof.length;
        uint256 totalHashes = proofFlags.length;

        // Check proof validity.
        require(leavesLen + proofLen - 1 == totalHashes, "MerkleProof: invalid multiproof");

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](totalHashes);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < totalHashes; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = _hashPair(a, b);
        }

        if (totalHashes > 0) {
            require(proofPos == proofLen, "MerkleProof: invalid multiproof");
            unchecked {
                return hashes[totalHashes - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) {
        return a < b ? _efficientHash(a, b) : _efficientHash(b, a);
    }

    function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, a)
            mstore(0x20, b)
            value := keccak256(0x00, 0x40)
        }
    }
}
          

contracts/lit-node/PKPNFTMetadata.sol

//SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.17;

import { Base64 } from "@openzeppelin/contracts/utils/Base64.sol";
import { Strings } from "@openzeppelin/contracts/utils/Strings.sol";

import "hardhat/console.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import { ContractResolver } from "../lit-core/ContractResolver.sol";

/// @title Programmable Keypair NFT Metadata
///
/// @dev This is the contract for the PKP NFTs
///
/// Simply put, whomever owns a PKP NFT can ask that PKP to sign a message.
/// The owner can also grant signing permissions to other eth addresses
/// or lit actions
contract PKPNFTMetadata is AccessControl {
    using Strings for uint256;
    address pkpHelperAddress;
    string constant NULL = "";

    ContractResolver public contractResolver;
    ContractResolver.Env public env;

    // Admin for setting writer roles, defaults to the deployer.
    bytes32 public constant ADMIN_ROLE = keccak256("ADMIN");

    // role for allowing writes to metadata stores
    // will be the `PKPHeler` for now, although migrating ownership lookup to a central store might be helpful
    bytes32 public constant WRITER_ROLE = keccak256("WRITER");

    /* ========== STATE VARIABLES ========== */
    mapping(uint256 => string) pkpUrls;
    mapping(uint256 => string) pkpProfileImg;

    /* ========== CONSTRUCTOR ========== */
    constructor(address _resolver, ContractResolver.Env _env) {
        contractResolver = ContractResolver(_resolver);
        env = _env;
    }

    /* ========== VIEWS ========== */

    function bytesToHex(
        bytes memory buffer
    ) public pure returns (string memory) {
        // Fixed buffer size for hexadecimal convertion
        bytes memory converted = new bytes(buffer.length * 2);

        bytes memory _base = "0123456789abcdef";

        for (uint256 i = 0; i < buffer.length; i++) {
            converted[i * 2] = _base[uint8(buffer[i]) / _base.length];
            converted[i * 2 + 1] = _base[uint8(buffer[i]) % _base.length];
        }

        return string(abi.encodePacked("0x", converted));
    }

    function setUrlForPKP(uint256 tokenId, string memory url) public {
        require(
            msg.sender ==
                contractResolver.getContract(
                    contractResolver.PKP_HELPER_CONTRACT(),
                    env
                ),
            "PKPHelper: only the Domain Wallet registry is allowed to mint domain wallets, who are you?"
        );

        pkpUrls[tokenId] = url;
    }

    function setProfileForPKP(uint256 tokenId, string memory imgUrl) public {
        require(
            msg.sender ==
                contractResolver.getContract(
                    contractResolver.PKP_HELPER_CONTRACT(),
                    env
                ),
            "PKPHelper: only the Domain Wallet registry is allowed to mint domain wallets, who are you?"
        );

        pkpProfileImg[tokenId] = imgUrl;
    }

    function removeUrlForPKP(uint256 tokenId) public {
        require(
            msg.sender ==
                contractResolver.getContract(
                    contractResolver.PKP_HELPER_CONTRACT(),
                    env
                ),
            "PKPHelper: only the Domain Wallet registry is allowed to mint domain wallets, who are you?"
        );

        pkpUrls[tokenId] = "";
    }

    function removeProfileForPkp(uint256 tokenId) public {
        require(
            msg.sender ==
                contractResolver.getContract(
                    contractResolver.PKP_HELPER_CONTRACT(),
                    env
                ),
            "PKPHelper: only the Domain Wallet registry is allowed to mint domain wallets, who are you?"
        );

        pkpProfileImg[tokenId] = "";
    }

    function tokenURI(
        uint256 tokenId,
        bytes memory pubKey,
        address ethAddress
    ) public view returns (string memory) {
        string memory json = resolveMetaData(tokenId, pubKey, ethAddress);
        return string(abi.encodePacked("data:application/json;base64,", json));
    }

    function resolveMetaData(
        uint256 tokenId,
        bytes memory pubKey,
        address ethAddress
    ) private view returns (string memory) {
        string
            memory svgData = "<svg xmlns='http://www.w3.org/2000/svg' width='1080' height='1080' fill='none' xmlns:v='https://vecta.io/nano'><path d='M363.076 392.227s-.977 18.524-36.874 78.947c-41.576 70.018-45.481 151.978-3.017 220.4 89.521 144.245 332.481 141.52 422.556.089 34.832-54.707 44.816-117.479 32.924-181.248 0 0-28.819-133.144-127.237-217.099 1.553 1.308 5.369 19.122 6.101 26.722 2.241 23.354.045 47.838-7.787 70.062-5.746 16.33-13.711 30.467-27.178 41.368 0-3.811-.954-10.635-.976-12.918-.644-46.508-18.659-89.582-48.011-125.743-25.647-31.552-60.812-53.089-97.84-68.932.931 3.191 2.662 16.419 2.906 19.033 1.908 21.958 2.263 52.713-.621 74.649s-7.832 33.878-14.554 54.441c-10.184 31.175-24.05 54.285-41.621 82.004-3.24 5.096-12.913 19.078-18.082 26.146 0 0-8.897-56.191-40.667-87.921h-.022z' fill='#000'/><path d='M562.5 27.28l410.279 236.874c13.923 8.039 22.5 22.895 22.5 38.971v473.75c0 16.076-8.577 30.932-22.5 38.971L562.5 1052.72c-13.923 8.04-31.077 8.04-45 0L107.221 815.846c-13.923-8.039-22.5-22.895-22.5-38.971v-473.75a45 45 0 0 1 22.5-38.971L517.5 27.28a45 45 0 0 1 45 0z' stroke='#000' stroke-width='24.75'/></svg>";

        string memory pubkeyStr = bytesToHex(pubKey);
        // console.log("pubkeyStr");
        // console.log(pubkeyStr);

        string memory ethAddressStr = Strings.toHexString(ethAddress);
        // console.log("ethAddressStr");
        // console.log(ethAddressStr);

        string memory tokenIdStr = Strings.toString(tokenId);

        string memory name = pkpUrls[tokenId];

        string memory profileImage = pkpProfileImg[tokenId];

        /// name is not registed
        if (bytes(name).length == 0 && bytes(profileImage).length != 0) {
            name = string.concat("Lit PKP #", tokenIdStr);
            /// profile image is not defined
        } else if (bytes(name).length != 0 && bytes(profileImage).length == 0) {
            profileImage = svgData;
            /// neither name or profile url are defined
        } else if (bytes(name).length == 0 && bytes(profileImage).length == 0) {
            name = string.concat("Lit PKP #", tokenIdStr);
            profileImage = svgData;
        }

        return
            Base64.encode(
                bytes(
                    string(
                        abi.encodePacked(
                            '{"name":"',
                            name,
                            '", "description": "This NFT entitles the holder to use a Lit Protocol PKP, and to grant access to other users and Lit Actions to use this PKP","image_data": "',
                            bytes(profileImage),
                            '","attributes": [{"trait_type": "Public Key", "value": "',
                            pubkeyStr,
                            '"}, {"trait_type": "ETH Wallet Address", "value": "',
                            ethAddressStr,
                            '"}, {"trait_type": "Token ID", "value": "',
                            tokenIdStr,
                            '"}]}'
                        )
                    )
                )
            );
    }

    function setPKPHelperWriterAddress(address pkpHelperWriterAddress) public {
        require(
            hasRole(ADMIN_ROLE, msg.sender),
            "PKPNFTMetadata: must had admin role"
        );
        _grantRole(WRITER_ROLE, pkpHelperWriterAddress);
    }
}
          

contracts/lit-node/HDKeyDeriver.sol

//SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity ^0.8.17;
import "./PubkeyRouter.sol";

abstract contract IKeyDeriver {
    function computeHDPubKey(
        bytes32 derivedKeyId,
        IPubkeyRouter.RootKey[] memory rootHDKeys,
        uint256 keyType
    ) public view virtual returns (bool, bytes memory);
}

contract KeyDeriver is IKeyDeriver {
    // address for HD public KDF
    address public constant HD_KDF = 0x00000000000000000000000000000000000000F5;
    // hd kdf ctx
    string constant HD_KDF_CTX = "LIT_HD_KEY_ID_K256_XMD:SHA-256_SSWU_RO_NUL_";

    constructor() {}

    function computeHDPubKey(
        bytes32 derivedKeyId,
        IPubkeyRouter.RootKey[] memory rootHDKeys,
        uint256 keyType
    ) public view override returns (bool, bytes memory) {
        bytes memory args = _buildArgs(derivedKeyId, rootHDKeys, keyType);
        (bool success, bytes memory data) = HD_KDF.staticcall(args);
        return (success, data);
    }

    function _buildArgs(
        bytes32 derivedKeyId,
        IPubkeyRouter.RootKey[] memory rootHDKeys,
        uint256 keyType
    ) internal pure returns (bytes memory) {
        // empty array for concating pubkeys
        bytes memory rootPubkeys = new bytes(0);
        uint32 numRootPubkeys = 0;
        for (uint256 i = 0; i < rootHDKeys.length; i++) {
            if (rootHDKeys[i].keyType == keyType) {
                rootPubkeys = abi.encodePacked(
                    rootPubkeys,
                    rootHDKeys[i].pubkey
                );
                numRootPubkeys++;
            }
        }

        // so in Lit land, we use 2 for ECDSA secp256k1 keyType.
        // but the precompile expects 1 for secp256k1
        // someday, we may add keyType 3 for ECDSA p256, which the precompile expects as "0"
        if (keyType == 2) {
            keyType = 1;
            // assuming p256 curve type will be value '3'
        } else if (keyType == 3) {
            keyType = 0;
        }

        bytes memory CTX = bytes(HD_KDF_CTX);
        bytes1 kt = bytes1(uint8(keyType));
        bytes4 id_len = bytes4(uint32(derivedKeyId.length));
        bytes4 ctx_len = bytes4(uint32(CTX.length));
        bytes4 pubkey_len = bytes4(numRootPubkeys);

        bytes memory args_bytes = abi.encodePacked(
            kt, // 1st arg is a byte for the curve type, 0 is Nist Prime256, 1 is secp256k1
            id_len, // 2nd arg is a 4 byte big-endian integer for the number of bytes in id
            derivedKeyId, // 3rd arg is the byte sequence for id
            ctx_len, // 4th arg is a 4 byte big-endian integer for the number of bytes in cxt
            CTX, // 5th arg is the byte sequence for cxt
            pubkey_len, // 6th arg is a 4 byte big-endian integer for the number of root keys
            rootPubkeys // 7th arg is a variable number of root keys each 33 bytes (compressed) or 65 bytes (uncompressed) in length
        );

        return args_bytes;
    }
}

contract DevKeyDeriver is IKeyDeriver {
    constructor() {}

    function computeHDPubKey(
        bytes32 derivedKeyId,
        IPubkeyRouter.RootKey[] memory rootHDKeys,
        uint256 keyType
    ) public view override returns (bool, bytes memory) {
        // TODO: This is a temporary fix for lack of precompiles in test enviorments
        // this is a non ideal as it does not truly exercise our KDF
        // reference for followup refactor: https://linear.app/litprotocol/issue/LIT-1192/add-precompiles-to-anvil-through-forked-version-of-revm

        bytes
            memory pubkey = hex"047c3647345020536e8aaccac7f73c5248bf3609677997fb615c290cc58e8ac1dcad1fa1d4f6eedf516f023dee11fbc06310434c5a7ee40f5f8c49e255b1d1bfb6";
        return (true, pubkey);
    }
}
          

@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/extensions/ERC721Enumerable.sol)

pragma solidity ^0.8.0;

import "../ERC721.sol";
import "./IERC721Enumerable.sol";

/**
 * @dev This implements an optional extension of {ERC721} defined in the EIP that adds
 * enumerability of all the token ids in the contract as well as all token ids owned by each
 * account.
 */
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
    // Mapping from owner to list of owned token IDs
    mapping(address => mapping(uint256 => uint256)) private _ownedTokens;

    // Mapping from token ID to index of the owner tokens list
    mapping(uint256 => uint256) private _ownedTokensIndex;

    // Array with all token ids, used for enumeration
    uint256[] private _allTokens;

    // Mapping from token id to position in the allTokens array
    mapping(uint256 => uint256) private _allTokensIndex;

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
        return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
        require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
        return _ownedTokens[owner][index];
    }

    /**
     * @dev See {IERC721Enumerable-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _allTokens.length;
    }

    /**
     * @dev See {IERC721Enumerable-tokenByIndex}.
     */
    function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
        require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
        return _allTokens[index];
    }

    /**
     * @dev See {ERC721-_beforeTokenTransfer}.
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 firstTokenId,
        uint256 batchSize
    ) internal virtual override {
        super._beforeTokenTransfer(from, to, firstTokenId, batchSize);

        if (batchSize > 1) {
            // Will only trigger during construction. Batch transferring (minting) is not available afterwards.
            revert("ERC721Enumerable: consecutive transfers not supported");
        }

        uint256 tokenId = firstTokenId;

        if (from == address(0)) {
            _addTokenToAllTokensEnumeration(tokenId);
        } else if (from != to) {
            _removeTokenFromOwnerEnumeration(from, tokenId);
        }
        if (to == address(0)) {
            _removeTokenFromAllTokensEnumeration(tokenId);
        } else if (to != from) {
            _addTokenToOwnerEnumeration(to, tokenId);
        }
    }

    /**
     * @dev Private function to add a token to this extension's ownership-tracking data structures.
     * @param to address representing the new owner of the given token ID
     * @param tokenId uint256 ID of the token to be added to the tokens list of the given address
     */
    function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
        uint256 length = ERC721.balanceOf(to);
        _ownedTokens[to][length] = tokenId;
        _ownedTokensIndex[tokenId] = length;
    }

    /**
     * @dev Private function to add a token to this extension's token tracking data structures.
     * @param tokenId uint256 ID of the token to be added to the tokens list
     */
    function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
        _allTokensIndex[tokenId] = _allTokens.length;
        _allTokens.push(tokenId);
    }

    /**
     * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
     * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
     * gas optimizations e.g. when performing a transfer operation (avoiding double writes).
     * This has O(1) time complexity, but alters the order of the _ownedTokens array.
     * @param from address representing the previous owner of the given token ID
     * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
     */
    function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
        // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
        // then delete the last slot (swap and pop).

        uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
        uint256 tokenIndex = _ownedTokensIndex[tokenId];

        // When the token to delete is the last token, the swap operation is unnecessary
        if (tokenIndex != lastTokenIndex) {
            uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];

            _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
            _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
        }

        // This also deletes the contents at the last position of the array
        delete _ownedTokensIndex[tokenId];
        delete _ownedTokens[from][lastTokenIndex];
    }

    /**
     * @dev Private function to remove a token from this extension's token tracking data structures.
     * This has O(1) time complexity, but alters the order of the _allTokens array.
     * @param tokenId uint256 ID of the token to be removed from the tokens list
     */
    function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
        // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
        // then delete the last slot (swap and pop).

        uint256 lastTokenIndex = _allTokens.length - 1;
        uint256 tokenIndex = _allTokensIndex[tokenId];

        // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
        // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
        // an 'if' statement (like in _removeTokenFromOwnerEnumeration)
        uint256 lastTokenId = _allTokens[lastTokenIndex];

        _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
        _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index

        // This also deletes the contents at the last position of the array
        delete _allTokensIndex[tokenId];
        _allTokens.pop();
    }
}
          

@openzeppelin/contracts/token/ERC721/ERC721.sol

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

pragma solidity ^0.8.0;

import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";

/**
 * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
 * the Metadata extension, but not including the Enumerable extension, which is available separately as
 * {ERC721Enumerable}.
 */
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
    using Address for address;
    using Strings for uint256;

    // Token name
    string private _name;

    // Token symbol
    string private _symbol;

    // Mapping from token ID to owner address
    mapping(uint256 => address) private _owners;

    // Mapping owner address to token count
    mapping(address => uint256) private _balances;

    // Mapping from token ID to approved address
    mapping(uint256 => address) private _tokenApprovals;

    // Mapping from owner to operator approvals
    mapping(address => mapping(address => bool)) private _operatorApprovals;

    /**
     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
        return
            interfaceId == type(IERC721).interfaceId ||
            interfaceId == type(IERC721Metadata).interfaceId ||
            super.supportsInterface(interfaceId);
    }

    /**
     * @dev See {IERC721-balanceOf}.
     */
    function balanceOf(address owner) public view virtual override returns (uint256) {
        require(owner != address(0), "ERC721: address zero is not a valid owner");
        return _balances[owner];
    }

    /**
     * @dev See {IERC721-ownerOf}.
     */
    function ownerOf(uint256 tokenId) public view virtual override returns (address) {
        address owner = _ownerOf(tokenId);
        require(owner != address(0), "ERC721: invalid token ID");
        return owner;
    }

    /**
     * @dev See {IERC721Metadata-name}.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev See {IERC721Metadata-symbol}.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev See {IERC721Metadata-tokenURI}.
     */
    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        _requireMinted(tokenId);

        string memory baseURI = _baseURI();
        return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
    }

    /**
     * @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, can be overridden in child contracts.
     */
    function _baseURI() internal view virtual returns (string memory) {
        return "";
    }

    /**
     * @dev See {IERC721-approve}.
     */
    function approve(address to, uint256 tokenId) public virtual override {
        address owner = ERC721.ownerOf(tokenId);
        require(to != owner, "ERC721: approval to current owner");

        require(
            _msgSender() == owner || isApprovedForAll(owner, _msgSender()),
            "ERC721: approve caller is not token owner or approved for all"
        );

        _approve(to, tokenId);
    }

    /**
     * @dev See {IERC721-getApproved}.
     */
    function getApproved(uint256 tokenId) public view virtual override returns (address) {
        _requireMinted(tokenId);

        return _tokenApprovals[tokenId];
    }

    /**
     * @dev See {IERC721-setApprovalForAll}.
     */
    function setApprovalForAll(address operator, bool approved) public virtual override {
        _setApprovalForAll(_msgSender(), operator, approved);
    }

    /**
     * @dev See {IERC721-isApprovedForAll}.
     */
    function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
        return _operatorApprovals[owner][operator];
    }

    /**
     * @dev See {IERC721-transferFrom}.
     */
    function transferFrom(address from, address to, uint256 tokenId) public virtual override {
        //solhint-disable-next-line max-line-length
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");

        _transfer(from, to, tokenId);
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
        safeTransferFrom(from, to, tokenId, "");
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual override {
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");
        _safeTransfer(from, to, tokenId, data);
    }

    /**
     * @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.
     *
     * `data` is additional data, it has no specified format and it is sent in call to `to`.
     *
     * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
     * implement alternative mechanisms to perform token transfer, such as signature-based.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {
        _transfer(from, to, tokenId);
        require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer");
    }

    /**
     * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
     */
    function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
        return _owners[tokenId];
    }

    /**
     * @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 (`_mint`),
     * and stop existing when they are burned (`_burn`).
     */
    function _exists(uint256 tokenId) internal view virtual returns (bool) {
        return _ownerOf(tokenId) != address(0);
    }

    /**
     * @dev Returns whether `spender` is allowed to manage `tokenId`.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
        address owner = ERC721.ownerOf(tokenId);
        return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
    }

    /**
     * @dev Safely mints `tokenId` and transfers it to `to`.
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeMint(address to, uint256 tokenId) internal virtual {
        _safeMint(to, tokenId, "");
    }

    /**
     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {
        _mint(to, tokenId);
        require(
            _checkOnERC721Received(address(0), to, tokenId, data),
            "ERC721: transfer to non ERC721Receiver implementer"
        );
    }

    /**
     * @dev Mints `tokenId` and transfers it to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - `to` cannot be the zero address.
     *
     * Emits a {Transfer} event.
     */
    function _mint(address to, uint256 tokenId) internal virtual {
        require(to != address(0), "ERC721: mint to the zero address");
        require(!_exists(tokenId), "ERC721: token already minted");

        _beforeTokenTransfer(address(0), to, tokenId, 1);

        // Check that tokenId was not minted by `_beforeTokenTransfer` hook
        require(!_exists(tokenId), "ERC721: token already minted");

        unchecked {
            // Will not overflow unless all 2**256 token ids are minted to the same owner.
            // Given that tokens are minted one by one, it is impossible in practice that
            // this ever happens. Might change if we allow batch minting.
            // The ERC fails to describe this case.
            _balances[to] += 1;
        }

        _owners[tokenId] = to;

        emit Transfer(address(0), to, tokenId);

        _afterTokenTransfer(address(0), to, tokenId, 1);
    }

    /**
     * @dev Destroys `tokenId`.
     * The approval is cleared when the token is burned.
     * This is an internal function that does not check if the sender is authorized to operate on the token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     *
     * Emits a {Transfer} event.
     */
    function _burn(uint256 tokenId) internal virtual {
        address owner = ERC721.ownerOf(tokenId);

        _beforeTokenTransfer(owner, address(0), tokenId, 1);

        // Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook
        owner = ERC721.ownerOf(tokenId);

        // Clear approvals
        delete _tokenApprovals[tokenId];

        unchecked {
            // Cannot overflow, as that would require more tokens to be burned/transferred
            // out than the owner initially received through minting and transferring in.
            _balances[owner] -= 1;
        }
        delete _owners[tokenId];

        emit Transfer(owner, address(0), tokenId);

        _afterTokenTransfer(owner, address(0), tokenId, 1);
    }

    /**
     * @dev Transfers `tokenId` from `from` to `to`.
     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     *
     * Emits a {Transfer} event.
     */
    function _transfer(address from, address to, uint256 tokenId) internal virtual {
        require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
        require(to != address(0), "ERC721: transfer to the zero address");

        _beforeTokenTransfer(from, to, tokenId, 1);

        // Check that tokenId was not transferred by `_beforeTokenTransfer` hook
        require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");

        // Clear approvals from the previous owner
        delete _tokenApprovals[tokenId];

        unchecked {
            // `_balances[from]` cannot overflow for the same reason as described in `_burn`:
            // `from`'s balance is the number of token held, which is at least one before the current
            // transfer.
            // `_balances[to]` could overflow in the conditions described in `_mint`. That would require
            // all 2**256 token ids to be minted, which in practice is impossible.
            _balances[from] -= 1;
            _balances[to] += 1;
        }
        _owners[tokenId] = to;

        emit Transfer(from, to, tokenId);

        _afterTokenTransfer(from, to, tokenId, 1);
    }

    /**
     * @dev Approve `to` to operate on `tokenId`
     *
     * Emits an {Approval} event.
     */
    function _approve(address to, uint256 tokenId) internal virtual {
        _tokenApprovals[tokenId] = to;
        emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
    }

    /**
     * @dev Approve `operator` to operate on all of `owner` tokens
     *
     * Emits an {ApprovalForAll} event.
     */
    function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
        require(owner != operator, "ERC721: approve to caller");
        _operatorApprovals[owner][operator] = approved;
        emit ApprovalForAll(owner, operator, approved);
    }

    /**
     * @dev Reverts if the `tokenId` has not been minted yet.
     */
    function _requireMinted(uint256 tokenId) internal view virtual {
        require(_exists(tokenId), "ERC721: invalid token ID");
    }

    /**
     * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
     * The call is not executed if the target address is not a contract.
     *
     * @param from address representing the previous owner of the given token ID
     * @param to target address that will receive the tokens
     * @param tokenId uint256 ID of the token to be transferred
     * @param data bytes optional data to send along with the call
     * @return bool whether the call correctly returned the expected magic value
     */
    function _checkOnERC721Received(
        address from,
        address to,
        uint256 tokenId,
        bytes memory data
    ) private returns (bool) {
        if (to.isContract()) {
            try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
                return retval == IERC721Receiver.onERC721Received.selector;
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    revert("ERC721: transfer to non ERC721Receiver implementer");
                } else {
                    /// @solidity memory-safe-assembly
                    assembly {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        } else {
            return true;
        }
    }

    /**
     * @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is
     * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`.
     * - When `from` is zero, the tokens will be minted for `to`.
     * - When `to` is zero, ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     * - `batchSize` is non-zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {}

    /**
     * @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is
     * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`.
     * - When `from` is zero, the tokens were minted for `to`.
     * - When `to` is zero, ``from``'s tokens were burned.
     * - `from` and `to` are never both zero.
     * - `batchSize` is non-zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {}

    /**
     * @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
     *
     * WARNING: Anyone calling this MUST ensure that the balances remain consistent with the ownership. The invariant
     * being that for any address `a` the value returned by `balanceOf(a)` must be equal to the number of tokens such
     * that `ownerOf(tokenId)` is `a`.
     */
    // solhint-disable-next-line func-name-mixedcase
    function __unsafe_increaseBalance(address account, uint256 amount) internal {
        _balances[account] += amount;
    }
}
          

hardhat/console.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;

library console {
    address constant CONSOLE_ADDRESS =
        0x000000000000000000636F6e736F6c652e6c6f67;

    function _sendLogPayloadImplementation(bytes memory payload) internal view {
        address consoleAddress = CONSOLE_ADDRESS;
        /// @solidity memory-safe-assembly
        assembly {
            pop(
                staticcall(
                    gas(),
                    consoleAddress,
                    add(payload, 32),
                    mload(payload),
                    0,
                    0
                )
            )
        }
    }

    function _castToPure(
      function(bytes memory) internal view fnIn
    ) internal pure returns (function(bytes memory) pure fnOut) {
        assembly {
            fnOut := fnIn
        }
    }

    function _sendLogPayload(bytes memory payload) internal pure {
        _castToPure(_sendLogPayloadImplementation)(payload);
    }

    function log() internal pure {
        _sendLogPayload(abi.encodeWithSignature("log()"));
    }
    function logInt(int256 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(int256)", p0));
    }

    function logUint(uint256 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256)", p0));
    }

    function logString(string memory p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string)", p0));
    }

    function logBool(bool p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
    }

    function logAddress(address p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address)", p0));
    }

    function logBytes(bytes memory p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
    }

    function logBytes1(bytes1 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
    }

    function logBytes2(bytes2 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
    }

    function logBytes3(bytes3 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
    }

    function logBytes4(bytes4 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
    }

    function logBytes5(bytes5 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
    }

    function logBytes6(bytes6 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
    }

    function logBytes7(bytes7 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
    }

    function logBytes8(bytes8 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
    }

    function logBytes9(bytes9 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
    }

    function logBytes10(bytes10 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
    }

    function logBytes11(bytes11 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
    }

    function logBytes12(bytes12 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
    }

    function logBytes13(bytes13 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
    }

    function logBytes14(bytes14 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
    }

    function logBytes15(bytes15 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
    }

    function logBytes16(bytes16 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
    }

    function logBytes17(bytes17 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
    }

    function logBytes18(bytes18 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
    }

    function logBytes19(bytes19 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
    }

    function logBytes20(bytes20 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
    }

    function logBytes21(bytes21 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
    }

    function logBytes22(bytes22 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
    }

    function logBytes23(bytes23 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
    }

    function logBytes24(bytes24 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
    }

    function logBytes25(bytes25 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
    }

    function logBytes26(bytes26 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
    }

    function logBytes27(bytes27 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
    }

    function logBytes28(bytes28 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
    }

    function logBytes29(bytes29 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
    }

    function logBytes30(bytes30 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
    }

    function logBytes31(bytes31 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
    }

    function logBytes32(bytes32 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
    }

    function log(uint256 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256)", p0));
    }

    function log(string memory p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string)", p0));
    }

    function log(bool p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
    }

    function log(address p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address)", p0));
    }

    function log(uint256 p0, uint256 p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256)", p0, p1));
    }

    function log(uint256 p0, string memory p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string)", p0, p1));
    }

    function log(uint256 p0, bool p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool)", p0, p1));
    }

    function log(uint256 p0, address p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address)", p0, p1));
    }

    function log(string memory p0, uint256 p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256)", p0, p1));
    }

    function log(string memory p0, string memory p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
    }

    function log(string memory p0, bool p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
    }

    function log(string memory p0, address p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
    }

    function log(bool p0, uint256 p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256)", p0, p1));
    }

    function log(bool p0, string memory p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
    }

    function log(bool p0, bool p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
    }

    function log(bool p0, address p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
    }

    function log(address p0, uint256 p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256)", p0, p1));
    }

    function log(address p0, string memory p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
    }

    function log(address p0, bool p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
    }

    function log(address p0, address p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
    }

    function log(uint256 p0, uint256 p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256)", p0, p1, p2));
    }

    function log(uint256 p0, uint256 p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string)", p0, p1, p2));
    }

    function log(uint256 p0, uint256 p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool)", p0, p1, p2));
    }

    function log(uint256 p0, uint256 p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address)", p0, p1, p2));
    }

    function log(uint256 p0, string memory p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256)", p0, p1, p2));
    }

    function log(uint256 p0, string memory p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string)", p0, p1, p2));
    }

    function log(uint256 p0, string memory p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool)", p0, p1, p2));
    }

    function log(uint256 p0, string memory p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address)", p0, p1, p2));
    }

    function log(uint256 p0, bool p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256)", p0, p1, p2));
    }

    function log(uint256 p0, bool p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string)", p0, p1, p2));
    }

    function log(uint256 p0, bool p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool)", p0, p1, p2));
    }

    function log(uint256 p0, bool p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address)", p0, p1, p2));
    }

    function log(uint256 p0, address p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256)", p0, p1, p2));
    }

    function log(uint256 p0, address p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string)", p0, p1, p2));
    }

    function log(uint256 p0, address p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool)", p0, p1, p2));
    }

    function log(uint256 p0, address p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address)", p0, p1, p2));
    }

    function log(string memory p0, uint256 p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256)", p0, p1, p2));
    }

    function log(string memory p0, uint256 p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string)", p0, p1, p2));
    }

    function log(string memory p0, uint256 p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool)", p0, p1, p2));
    }

    function log(string memory p0, uint256 p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address)", p0, p1, p2));
    }

    function log(string memory p0, string memory p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256)", p0, p1, p2));
    }

    function log(string memory p0, string memory p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
    }

    function log(string memory p0, string memory p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
    }

    function log(string memory p0, string memory p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
    }

    function log(string memory p0, bool p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256)", p0, p1, p2));
    }

    function log(string memory p0, bool p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
    }

    function log(string memory p0, bool p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
    }

    function log(string memory p0, bool p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
    }

    function log(string memory p0, address p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256)", p0, p1, p2));
    }

    function log(string memory p0, address p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
    }

    function log(string memory p0, address p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
    }

    function log(string memory p0, address p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
    }

    function log(bool p0, uint256 p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256)", p0, p1, p2));
    }

    function log(bool p0, uint256 p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string)", p0, p1, p2));
    }

    function log(bool p0, uint256 p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool)", p0, p1, p2));
    }

    function log(bool p0, uint256 p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address)", p0, p1, p2));
    }

    function log(bool p0, string memory p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256)", p0, p1, p2));
    }

    function log(bool p0, string memory p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
    }

    function log(bool p0, string memory p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
    }

    function log(bool p0, string memory p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
    }

    function log(bool p0, bool p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256)", p0, p1, p2));
    }

    function log(bool p0, bool p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
    }

    function log(bool p0, bool p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
    }

    function log(bool p0, bool p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
    }

    function log(bool p0, address p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256)", p0, p1, p2));
    }

    function log(bool p0, address p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
    }

    function log(bool p0, address p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
    }

    function log(bool p0, address p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
    }

    function log(address p0, uint256 p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256)", p0, p1, p2));
    }

    function log(address p0, uint256 p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string)", p0, p1, p2));
    }

    function log(address p0, uint256 p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool)", p0, p1, p2));
    }

    function log(address p0, uint256 p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address)", p0, p1, p2));
    }

    function log(address p0, string memory p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256)", p0, p1, p2));
    }

    function log(address p0, string memory p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
    }

    function log(address p0, string memory p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
    }

    function log(address p0, string memory p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
    }

    function log(address p0, bool p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256)", p0, p1, p2));
    }

    function log(address p0, bool p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
    }

    function log(address p0, bool p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
    }

    function log(address p0, bool p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
    }

    function log(address p0, address p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256)", p0, p1, p2));
    }

    function log(address p0, address p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
    }

    function log(address p0, address p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
    }

    function log(address p0, address p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
    }

    function log(uint256 p0, uint256 p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, uint256 p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, uint256 p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, uint256 p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,address)", p0, p1, p2, p3));
    }

    function log(uint256 p0, uint256 p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, uint256 p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, uint256 p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, uint256 p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,address)", p0, p1, p2, p3));
    }

    function log(uint256 p0, uint256 p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, uint256 p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, uint256 p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, uint256 p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,address)", p0, p1, p2, p3));
    }

    function log(uint256 p0, uint256 p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, uint256 p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, uint256 p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, uint256 p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,address)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,address)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,address)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,address)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,address)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,address)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,address)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,address)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,address)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,address)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,address)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,address)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,string)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,address)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,string)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,address)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,string)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,address)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,string)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,address)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,string)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,address)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,string)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,address)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,string)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,address)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,string)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,bool)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,address)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,string)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,bool)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,address)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,string)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,bool)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,address)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,string)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,bool)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,address)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,string)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,bool)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,address)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,string)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,bool)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,address)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,string)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,bool)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,address)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
    }

}
          

@openzeppelin/contracts/utils/Base64.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)

pragma solidity ^0.8.0;

/**
 * @dev Provides a set of functions to operate with Base64 strings.
 *
 * _Available since v4.5._
 */
library Base64 {
    /**
     * @dev Base64 Encoding/Decoding Table
     */
    string internal constant _TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

    /**
     * @dev Converts a `bytes` to its Bytes64 `string` representation.
     */
    function encode(bytes memory data) internal pure returns (string memory) {
        /**
         * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence
         * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol
         */
        if (data.length == 0) return "";

        // Loads the table into memory
        string memory table = _TABLE;

        // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter
        // and split into 4 numbers of 6 bits.
        // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up
        // - `data.length + 2`  -> Round up
        // - `/ 3`              -> Number of 3-bytes chunks
        // - `4 *`              -> 4 characters for each chunk
        string memory result = new string(4 * ((data.length + 2) / 3));

        /// @solidity memory-safe-assembly
        assembly {
            // Prepare the lookup table (skip the first "length" byte)
            let tablePtr := add(table, 1)

            // Prepare result pointer, jump over length
            let resultPtr := add(result, 32)

            // Run over the input, 3 bytes at a time
            for {
                let dataPtr := data
                let endPtr := add(data, mload(data))
            } lt(dataPtr, endPtr) {

            } {
                // Advance 3 bytes
                dataPtr := add(dataPtr, 3)
                let input := mload(dataPtr)

                // To write each character, shift the 3 bytes (18 bits) chunk
                // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)
                // and apply logical AND with 0x3F which is the number of
                // the previous character in the ASCII table prior to the Base64 Table
                // The result is then added to the table to get the character to write,
                // and finally write it in the result pointer but with a left shift
                // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits

                mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance

                mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance

                mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance

                mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance
            }

            // When data `bytes` is not exactly 3 bytes long
            // it is padded with `=` characters at the end
            switch mod(mload(data), 3)
            case 1 {
                mstore8(sub(resultPtr, 1), 0x3d)
                mstore8(sub(resultPtr, 2), 0x3d)
            }
            case 2 {
                mstore8(sub(resultPtr, 1), 0x3d)
            }
        }

        return result;
    }
}
          

@openzeppelin/contracts/utils/math/Math.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1, "Math: mulDiv overflow");

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
            // See https://cs.stackexchange.com/q/138556/92363.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
        }
    }
}
          

@openzeppelin/contracts/utils/math/SignedMath.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}
          

@openzeppelin/contracts/utils/Address.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}
          

contracts/lit-node/Staking.sol

//SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.17;

import { ERC20Burnable } from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { StakingBalances } from "./StakingBalances.sol";
import { ContractResolver } from "../lit-core/ContractResolver.sol";

import "hardhat/console.sol";

contract Staking is Ownable {
    using EnumerableSet for EnumerableSet.AddressSet;

    /* ========== STATE VARIABLES ========== */

    enum States {
        Active,
        NextValidatorSetLocked,
        ReadyForNextEpoch,
        Unlocked,
        Paused
    }

    States public state = States.Active;

    struct Validator {
        uint32 ip;
        uint128 ipv6;
        uint32 port;
        address nodeAddress;
        uint256 reward;
        uint256 senderPubKey;
        uint256 receiverPubKey;
    }

    struct VoteToKickValidatorInNextEpoch {
        uint256 votes;
        mapping(address => bool) voted;
    }

    struct Epoch {
        uint256 epochLength; // in seconds
        uint256 number; // the current epoch number
        uint256 endTime; // the end timestamp where the next epoch can be kicked off
        uint256 retries; // incremented upon failure to advance and subsequent unlock
        uint256 timeout; // timeout in seconds, where the nodes can be unlocked.
    }

    Epoch public epoch;

    struct Config {
        uint256 tokenRewardPerTokenPerEpoch;
        uint256 complaintTolerance; // cycles after which to escalate peer complaints to chain
        uint256 complaintIntervalSecs;
        // the key type of the node.  // 1 = BLS, 2 = ECDSA.  Not doing this in an enum so we can add more keytypes in the future without redeploying.
        uint256[] keyTypes;
        // don't start the DKG or let nodes leave the validator set
        // if there are less than this many nodes
        uint256 minimumValidatorCount;
    }

    Config public config;

    uint256 public totalStaked;

    EnumerableSet.AddressSet validatorsInCurrentEpoch;
    EnumerableSet.AddressSet validatorsInNextEpoch;
    EnumerableSet.AddressSet validatorsKickedFromNextEpoch;

    ContractResolver public contractResolver;
    ContractResolver.Env public env;

    // errors
    error MustBeInActiveOrUnlockedState(States state);
    error MustBeInNextValidatorSetLockedOrReadyForNextEpochState(States state);
    error MustBeInNextValidatorSetLockedState(States state);
    error MustBeInReadyForNextEpochState(States state);
    error MustBeInActiveOrUnlockedOrPausedState(States state);
    error NotEnoughValidatorsInNextEpoch(
        uint256 validatorCount,
        uint256 minimumValidatorCount
    );
    error ValidatorIsNotInNextEpoch(
        address validator,
        address[] validatorsInNextEpoch
    );
    error NotEnoughValidatorsReadyForNextEpoch(
        uint256 currentReadyValidatorCount,
        uint256 nextReadyValidatorCount,
        uint256 minimumValidatorCountToBeReady
    );
    error CannotStakeZero();
    error CannotRejoinUntilNextEpochBecauseKicked(address stakingAddress);
    error ActiveValidatorsCannotLeave();
    error TryingToWithdrawMoreThanStaked(
        uint256 yourBalance,
        uint256 requestedWithdrawlAmount
    );
    error CouldNotMapNodeAddressToStakerAddress(address nodeAddress);
    error MustBeValidatorInNextEpochToKick(address stakerAddress);
    error CannotVoteTwice(address stakerAddress);
    error NotEnoughTimeElapsedSinceLastEpoch(
        uint256 currentTimestamp,
        uint256 epochEndTime
    );
    error NotEnoughTimeElapsedForTimeoutSinceLastEpoch(
        uint256 currentTimestamp,
        uint256 epochEndTime,
        uint256 timeout
    );
    error CannotWithdrawZero();
    error CannotReuseCommsKeys(uint256 senderPubKey, uint256 receiverPubKey);
    error StakerNotPermitted(address stakerAddress);
    error SignaledReadyForWrongEpochNumber(
        uint256 currentEpochNumber,
        uint256 receivedEpochNumber
    );

    // list of all validators, even ones that are not in the current or next epoch
    // maps STAKER address to Validator struct
    mapping(address => Validator) public validators;

    // stakers join by staking, but nodes need to be able to vote to kick.
    // to avoid node operators having to run a hotwallet with their staking private key,
    // the node gets it's own private key that it can use to vote to kick,
    // or signal that the next epoch is ready.
    // this mapping lets you go from the nodeAddressto the stakingAddress.
    mapping(address => address) public nodeAddressToStakerAddress;

    // after the validator set is locked, nodes vote that they have successfully completed the PSS
    // operation.  Once a threshold of nodes have voted that they are ready, then the epoch can advance
    mapping(address => bool) public readyForNextEpoch;

    // nodes can vote to kick another node.  If a threshold of nodes vote to kick someone, they
    // are removed from the next validator set
    mapping(uint256 => mapping(address => VoteToKickValidatorInNextEpoch))
        public votesToKickValidatorsInNextEpoch;

    // maps kick reason to amount to slash
    mapping(uint256 => uint256) public kickPenaltyPercentByReason;

    // maps hash(comms_sender_pubkey,comms_receiver_pubkey) to a boolean to show if
    // the set of comms keys has been used or not
    mapping(bytes32 => bool) public usedCommsKeys;

    /* ========== CONSTRUCTOR ========== */
    constructor(
        address _resolver,
        uint256[] memory _keyTypes,
        ContractResolver.Env _env
    ) {
        contractResolver = ContractResolver(_resolver);
        env = _env;
        // 0.05 tokens per token staked meaning a 5% per epoch inflation rate
        ERC20Burnable stakingToken = ERC20Burnable(getTokenAddress());
        config = Config({
            tokenRewardPerTokenPerEpoch: (10 ** stakingToken.decimals()) / 20,
            complaintTolerance: 15,
            complaintIntervalSecs: 60,
            keyTypes: _keyTypes,
            minimumValidatorCount: 2
        });
        uint256 epochLengthSeconds = 1;
        epoch = Epoch({
            epochLength: epochLengthSeconds,
            number: 1,
            endTime: block.timestamp + epochLengthSeconds,
            retries: 0,
            timeout: 60
        });
        // set default kick penalty to 1% for reason "1"
        kickPenaltyPercentByReason[1] = 1;
        state = States.Paused;
    }

    /* ========== VIEWS ========== */
    function getKeyTypes() external view returns (uint256[] memory) {
        return config.keyTypes;
    }

    /// get the token address from the resolver
    function getTokenAddress() public view returns (address) {
        return
            contractResolver.getContract(
                contractResolver.LIT_TOKEN_CONTRACT(),
                env
            );
    }

    // get the staking balances address from the resolver
    function getStakingBalancesAddress() public view returns (address) {
        return
            contractResolver.getContract(
                contractResolver.STAKING_BALANCES_CONTRACT(),
                env
            );
    }

    function isActiveValidator(address account) external view returns (bool) {
        return validatorsInCurrentEpoch.contains(account);
    }

    function isActiveValidatorByNodeAddress(
        address account
    ) external view returns (bool) {
        return
            validatorsInCurrentEpoch.contains(
                nodeAddressToStakerAddress[account]
            );
    }

    function getVotingStatusToKickValidator(
        uint256 epochNumber,
        address validatorStakerAddress,
        address voterStakerAddress
    ) external view returns (uint256, bool) {
        VoteToKickValidatorInNextEpoch
            storage votingStatus = votesToKickValidatorsInNextEpoch[
                epochNumber
            ][validatorStakerAddress];
        return (votingStatus.votes, votingStatus.voted[voterStakerAddress]);
    }

    function getValidatorsInCurrentEpoch()
        public
        view
        returns (address[] memory)
    {
        address[] memory values = new address[](
            validatorsInCurrentEpoch.length()
        );
        uint256 validatorLength = validatorsInCurrentEpoch.length();
        for (uint256 i = 0; i < validatorLength; i++) {
            values[i] = validatorsInCurrentEpoch.at(i);
        }
        return values;
    }

    function getValidatorsInCurrentEpochLength()
        external
        view
        returns (uint256)
    {
        return validatorsInCurrentEpoch.length();
    }

    function getValidatorsInNextEpoch() public view returns (address[] memory) {
        address[] memory values = new address[](validatorsInNextEpoch.length());
        uint256 validatorLength = validatorsInNextEpoch.length();
        for (uint256 i = 0; i < validatorLength; i++) {
            values[i] = validatorsInNextEpoch.at(i);
        }
        return values;
    }

    function getValidatorsStructs(
        address[] memory addresses
    ) public view returns (Validator[] memory) {
        Validator[] memory values = new Validator[](addresses.length);
        for (uint256 i = 0; i < addresses.length; i++) {
            values[i] = validators[addresses[i]];
        }
        return values;
    }

    function getValidatorsStructsInCurrentEpoch()
        external
        view
        returns (Validator[] memory)
    {
        address[] memory addresses = getValidatorsInCurrentEpoch();
        return getValidatorsStructs(addresses);
    }

    function getValidatorsStructsInNextEpoch()
        external
        view
        returns (Validator[] memory)
    {
        address[] memory addresses = getValidatorsInNextEpoch();
        return getValidatorsStructs(addresses);
    }

    function countOfCurrentValidatorsReadyForNextEpoch()
        public
        view
        returns (uint256)
    {
        uint256 total = 0;
        uint256 validatorLength = validatorsInCurrentEpoch.length();
        for (uint256 i = 0; i < validatorLength; i++) {
            if (readyForNextEpoch[validatorsInCurrentEpoch.at(i)]) {
                total++;
            }
        }
        return total;
    }

    function countOfNextValidatorsReadyForNextEpoch()
        public
        view
        returns (uint256)
    {
        uint256 total = 0;
        uint256 validatorLength = validatorsInNextEpoch.length();
        for (uint256 i = 0; i < validatorLength; i++) {
            if (readyForNextEpoch[validatorsInNextEpoch.at(i)]) {
                total++;
            }
        }
        return total;
    }

    function isReadyForNextEpoch() public view returns (bool) {
        // confirm that current validator set is ready
        if (
            countOfCurrentValidatorsReadyForNextEpoch() <
            currentValidatorCountForConsensus()
        ) {
            return false;
        }

        // confirm that next validator set is ready
        if (
            countOfNextValidatorsReadyForNextEpoch() <
            nextValidatorCountForConsensus()
        ) {
            return false;
        }

        return true;
    }

    function shouldKickValidator(
        address stakerAddress
    ) public view returns (bool) {
        VoteToKickValidatorInNextEpoch
            storage vk = votesToKickValidatorsInNextEpoch[epoch.number][
                stakerAddress
            ];
        if (vk.votes >= currentValidatorCountForConsensus()) {
            // 2/3 of validators must vote
            return true;
        }
        return false;
    }

    // currently set to 2/3.  this could be changed to be configurable.
    function currentValidatorCountForConsensus() public view returns (uint256) {
        if (validatorsInCurrentEpoch.length() == 2) {
            return 1;
        }

        return (validatorsInCurrentEpoch.length() * 2) / 3;
    }

    /// require all nodes in the next validator set to vote that they're ready
    /// any offline nodes will be kicked from the next validator set so that's why this is safe
    function nextValidatorCountForConsensus() public view returns (uint256) {
        return validatorsInNextEpoch.length();
    }

    function getKickedValidators() public view returns (address[] memory) {
        address[] memory values = new address[](
            validatorsKickedFromNextEpoch.length()
        );
        uint256 validatorLength = validatorsKickedFromNextEpoch.length();
        for (uint256 i = 0; i < validatorLength; i++) {
            values[i] = validatorsKickedFromNextEpoch.at(i);
        }
        return values;
    }

    /* ========== MUTATIVE FUNCTIONS ========== */

    /// Lock in the validators for the next epoch
    function lockValidatorsForNextEpoch() public {
        if (block.timestamp < epoch.endTime) {
            revert NotEnoughTimeElapsedSinceLastEpoch(
                block.timestamp,
                epoch.endTime
            );
        }
        if (!(state == States.Active || state == States.Unlocked)) {
            revert MustBeInActiveOrUnlockedState(state);
        }
        if (validatorsInNextEpoch.length() < config.minimumValidatorCount) {
            revert NotEnoughValidatorsInNextEpoch(
                validatorsInNextEpoch.length(),
                config.minimumValidatorCount
            );
        }

        state = States.NextValidatorSetLocked;
        emit StateChanged(state);
    }

    /// After proactive secret sharing is complete, the nodes may signal that they are ready for the next epoch.  Note that this function is called by the node itself, and so msg.sender is the nodeAddress and not the stakerAddress.
    function signalReadyForNextEpoch(uint256 epochNumber) public {
        if (epoch.number != epochNumber) {
            revert SignaledReadyForWrongEpochNumber(epoch.number, epochNumber);
        }

        address stakerAddress = nodeAddressToStakerAddress[msg.sender];
        if (
            !(state == States.NextValidatorSetLocked ||
                state == States.ReadyForNextEpoch)
        ) {
            revert MustBeInNextValidatorSetLockedOrReadyForNextEpochState(
                state
            );
        }
        // at the first epoch, validatorsInCurrentEpoch is empty
        if (epoch.number != 1) {
            if (!validatorsInNextEpoch.contains(stakerAddress)) {
                revert ValidatorIsNotInNextEpoch(
                    stakerAddress,
                    getValidatorsInNextEpoch()
                );
            }
        }
        readyForNextEpoch[stakerAddress] = true;
        emit ReadyForNextEpoch(stakerAddress, epoch.number);

        if (isReadyForNextEpoch()) {
            state = States.ReadyForNextEpoch;
            emit StateChanged(state);
        }
    }

    /// If the nodes fail to advance (e.g. because dkg failed), anyone can call to unlock and allow retry
    function unlockValidatorsForNextEpoch() public {
        // the deadline to advance is thus epoch.endBlock + epoch.timeout
        if (block.timestamp < epoch.endTime + epoch.timeout) {
            revert NotEnoughTimeElapsedForTimeoutSinceLastEpoch(
                block.timestamp,
                epoch.endTime,
                epoch.timeout
            );
        }
        if (state != States.NextValidatorSetLocked) {
            revert MustBeInNextValidatorSetLockedState(state);
        }

        uint256 validatorLength = validatorsInNextEpoch.length();
        for (uint256 i = 0; i < validatorLength; i++) {
            readyForNextEpoch[validatorsInNextEpoch.at(i)] = false;
        }

        epoch.retries++;

        state = States.Unlocked;
        emit StateChanged(state);
    }

    /// Advance to the next Epoch.  Rewards validators, adds the joiners, and removes the leavers
    function advanceEpoch() public {
        if (block.timestamp < epoch.endTime) {
            revert NotEnoughTimeElapsedSinceLastEpoch(
                block.timestamp,
                epoch.endTime
            );
        }
        if (state != States.ReadyForNextEpoch) {
            revert MustBeInReadyForNextEpochState(state);
        }
        if (!isReadyForNextEpoch()) {
            revert NotEnoughValidatorsReadyForNextEpoch(
                countOfCurrentValidatorsReadyForNextEpoch(),
                countOfNextValidatorsReadyForNextEpoch(),
                currentValidatorCountForConsensus()
            );
        }

        // reward the validators
        uint256 validatorLength = validatorsInCurrentEpoch.length();
        for (uint256 i = 0; i < validatorLength; i++) {
            address validatorAddress = validatorsInCurrentEpoch.at(i);
            ERC20Burnable stakingToken = ERC20Burnable(getTokenAddress());
            StakingBalances stakingBalances = StakingBalances(
                getStakingBalancesAddress()
            );
            uint256 reward = (config.tokenRewardPerTokenPerEpoch *
                stakingBalances.balanceOf(validatorAddress)) /
                10 ** stakingToken.decimals();
            stakingBalances.rewardValidator(reward, validatorAddress);
        }

        // set the validators to the new validator set
        // ideally we could just do this:
        // validatorsInCurrentEpoch = validatorsInNextEpoch;
        // but solidity doesn't allow that, so we have to do it manually

        // clear out validators in current epoch
        while (validatorsInCurrentEpoch.length() > 0) {
            validatorsInCurrentEpoch.remove(validatorsInCurrentEpoch.at(0));
        }

        // copy validators from next epoch to current epoch
        validatorLength = validatorsInNextEpoch.length();
        for (uint256 i = 0; i < validatorLength; i++) {
            validatorsInCurrentEpoch.add(validatorsInNextEpoch.at(i));

            // clear out readyForNextEpoch
            readyForNextEpoch[validatorsInNextEpoch.at(i)] = false;
        }

        epoch.number++;
        epoch.endTime = block.timestamp + epoch.epochLength;

        state = States.Active;
        emit StateChanged(state);
    }

    /// Stake and request to join the validator set
    /// @param amount The amount of tokens to stake
    /// @param ip The IP address of the node
    /// @param port The port of the node
    function stakeAndJoin(
        uint256 amount,
        uint32 ip,
        uint128 ipv6,
        uint32 port,
        address nodeAddress,
        uint256 senderPubKey,
        uint256 receiverPubKey
    ) public {
        stake(amount);
        requestToJoin(
            ip,
            ipv6,
            port,
            nodeAddress,
            senderPubKey,
            receiverPubKey
        );
    }

    function stake(uint256 amount) public {
        StakingBalances stakingBalances = StakingBalances(
            getStakingBalancesAddress()
        );
        stakingBalances.stake(amount, msg.sender);
    }

    function requestToJoin(
        uint32 ip,
        uint128 ipv6,
        uint32 port,
        address nodeAddress,
        uint256 senderPubKey,
        uint256 receiverPubKey
    ) public {
        StakingBalances stakingBalances = StakingBalances(
            getStakingBalancesAddress()
        );
        stakingBalances.checkStakingAmounts(msg.sender);

        if (
            !(state == States.Active ||
                state == States.Unlocked ||
                state == States.Paused)
        ) {
            revert MustBeInActiveOrUnlockedOrPausedState(state);
        }

        // make sure they haven't been kicked
        if (validatorsKickedFromNextEpoch.contains(msg.sender)) {
            revert CannotRejoinUntilNextEpochBecauseKicked(msg.sender);
        }

        bytes32 commsKeysHash = keccak256(
            abi.encodePacked(senderPubKey, receiverPubKey)
        );
        if (usedCommsKeys[commsKeysHash]) {
            revert CannotReuseCommsKeys(senderPubKey, receiverPubKey);
        }
        usedCommsKeys[commsKeysHash] = true;

        if (stakingBalances.permittedStakersOn()) {
            if (!stakingBalances.isPermittedStaker(msg.sender)) {
                revert StakerNotPermitted(msg.sender);
            }
        }

        validators[msg.sender].ip = ip;
        validators[msg.sender].ipv6 = ipv6;
        validators[msg.sender].port = port;
        validators[msg.sender].nodeAddress = nodeAddress;
        validators[msg.sender].senderPubKey = senderPubKey;
        validators[msg.sender].receiverPubKey = receiverPubKey;
        nodeAddressToStakerAddress[nodeAddress] = msg.sender;

        validatorsInNextEpoch.add(msg.sender);

        emit RequestToJoin(msg.sender);
    }

    /// Withdraw staked tokens.  This can only be done by users who are not active in the validator set.
    /// @param amount The amount of tokens to withdraw
    function withdraw(uint256 amount) public {
        StakingBalances stakingBalances = StakingBalances(
            getStakingBalancesAddress()
        );
        stakingBalances.withdraw(amount, msg.sender);
    }

    /// Request to leave in the next Epoch
    function requestToLeave() public {
        if (
            !(state == States.Active ||
                state == States.Unlocked ||
                state == States.Paused)
        ) {
            revert MustBeInActiveOrUnlockedOrPausedState(state);
        }
        if (validatorsInNextEpoch.length() - 1 < config.minimumValidatorCount) {
            revert NotEnoughValidatorsInNextEpoch(
                validatorsInNextEpoch.length(),
                config.minimumValidatorCount
            );
        }
        removeValidatorFromNextEpoch(msg.sender);
        emit RequestToLeave(msg.sender);
    }

    /// Transfer any outstanding reward tokens
    function getReward() public {
        StakingBalances stakingBalances = StakingBalances(
            getStakingBalancesAddress()
        );
        stakingBalances.getReward(msg.sender);
    }

    /// Exit staking and get any outstanding rewards
    function exit() public {
        StakingBalances stakingBalances = StakingBalances(
            getStakingBalancesAddress()
        );
        stakingBalances.withdraw(
            stakingBalances.balanceOf(msg.sender),
            msg.sender
        );
        stakingBalances.getReward(msg.sender);
    }

    /// If more than the threshold of validators vote to kick someone, kick them.
    /// It's expected that this will be called by the node directly, so msg.sender will be the nodeAddress
    function kickValidatorInNextEpoch(
        address validatorStakerAddress,
        uint256 reason,
        bytes calldata data
    ) public {
        address stakerAddressOfSender = nodeAddressToStakerAddress[msg.sender];
        if (stakerAddressOfSender == address(0)) {
            revert CouldNotMapNodeAddressToStakerAddress(msg.sender);
        }
        if (!validatorsInNextEpoch.contains(stakerAddressOfSender)) {
            revert MustBeValidatorInNextEpochToKick(stakerAddressOfSender);
        }
        if (
            votesToKickValidatorsInNextEpoch[epoch.number][
                validatorStakerAddress
            ].voted[stakerAddressOfSender]
        ) {
            revert CannotVoteTwice(stakerAddressOfSender);
        }

        // Vote to kick
        votesToKickValidatorsInNextEpoch[epoch.number][validatorStakerAddress]
            .votes++;
        votesToKickValidatorsInNextEpoch[epoch.number][validatorStakerAddress]
            .voted[stakerAddressOfSender] = true;

        if (
            validatorsInNextEpoch.contains(validatorStakerAddress) &&
            shouldKickValidator(validatorStakerAddress)
        ) {
            // remove them from the validator set
            removeValidatorFromNextEpoch(validatorStakerAddress);
            // block them from rejoining the next epoch
            validatorsKickedFromNextEpoch.add(validatorStakerAddress);
            // slash the stake
            uint256 kickPenaltyPercent = kickPenaltyPercentByReason[reason];

            StakingBalances stakingBalances = StakingBalances(
                getStakingBalancesAddress()
            );
            uint256 amountToPenalize = (stakingBalances.balanceOf(
                validatorStakerAddress
            ) * kickPenaltyPercent) / 100;

            stakingBalances.penalizeTokens(
                amountToPenalize,
                validatorStakerAddress
            );

            // shame them with an event
            emit ValidatorKickedFromNextEpoch(
                validatorStakerAddress,
                amountToPenalize
            );
        }

        emit VotedToKickValidatorInNextEpoch(
            stakerAddressOfSender,
            validatorStakerAddress,
            reason,
            data
        );
    }

    /// Set the IP and port of your node
    /// @param ip The ip address of your node
    /// @param port The port of your node
    function setIpPortNodeAddressAndCommunicationPubKeys(
        uint32 ip,
        uint128 ipv6,
        uint32 port,
        address nodeAddress,
        uint256 senderPubKey,
        uint256 receiverPubKey
    ) public {
        validators[msg.sender].ip = ip;
        validators[msg.sender].ipv6 = ipv6;
        validators[msg.sender].port = port;
        validators[msg.sender].nodeAddress = nodeAddress;
        validators[msg.sender].senderPubKey = senderPubKey;
        validators[msg.sender].receiverPubKey = receiverPubKey;
    }

    function setEpochLength(uint256 newEpochLength) public onlyOwner {
        epoch.epochLength = newEpochLength;
        emit EpochLengthSet(newEpochLength);
    }

    function setEpochTimeout(uint256 newEpochTimeout) public onlyOwner {
        epoch.timeout = newEpochTimeout;
        emit EpochTimeoutSet(newEpochTimeout);
    }

    function setEpochEndTime(uint256 newEpochEndTime) public onlyOwner {
        epoch.endTime = newEpochEndTime;
        emit EpochEndTimeSet(newEpochEndTime);
    }

    function setContractResolver(address newResolverAddress) public onlyOwner {
        contractResolver = ContractResolver(newResolverAddress);
        emit ResolverContractAddressSet(newResolverAddress);
    }

    function setKickPenaltyPercent(
        uint256 reason,
        uint256 newKickPenaltyPercent
    ) public onlyOwner {
        kickPenaltyPercentByReason[reason] = newKickPenaltyPercent;
        emit KickPenaltyPercentSet(reason, newKickPenaltyPercent);
    }

    function setEpochState(States newState) public onlyOwner {
        state = newState;
        emit StateChanged(newState);
    }

    function pauseEpoch() public onlyOwner {
        state = States.Paused;
        emit StateChanged(States.Paused);
    }

    function adminKickValidatorInNextEpoch(
        address validatorStakerAddress
    ) public onlyOwner {
        // remove from next validator set
        validatorsInNextEpoch.remove(validatorStakerAddress);
        // block them from rejoining the next epoch
        validatorsKickedFromNextEpoch.add(validatorStakerAddress);
        removeValidatorFromNextEpoch(msg.sender);
        emit ValidatorKickedFromNextEpoch(validatorStakerAddress, 0);
    }

    function adminSlashValidator(
        address validatorStakerAddress,
        uint256 amountToPenalize
    ) public onlyOwner {
        StakingBalances stakingBalances = StakingBalances(
            getStakingBalancesAddress()
        );
        stakingBalances.penalizeTokens(
            amountToPenalize,
            validatorStakerAddress
        );
    }

    function removeValidatorFromNextEpoch(address staker) internal {
        if (validatorsInNextEpoch.contains(staker)) {
            // remove them
            validatorsInNextEpoch.remove(staker);
        }
        Validator memory validator = validators[staker];
        bytes32 commsKeysHash = keccak256(
            abi.encodePacked(validator.senderPubKey, validator.receiverPubKey)
        );
        usedCommsKeys[commsKeysHash] = false;
    }

    function adminRejoinValidator(address staker) public onlyOwner {
        // remove from kicked list
        validatorsKickedFromNextEpoch.remove(staker);
        // add to next validator set
        validatorsInNextEpoch.add(staker);
        emit ValidatorRejoinedNextEpoch(staker);
    }

    function setConfig(
        uint256 newTokenRewardPerTokenPerEpoch,
        uint256 newComplaintTolerance,
        uint256 newComplaintIntervalSecs,
        uint256[] memory newKeyTypes,
        uint256 newMinimumValidatorCount
    ) public onlyOwner {
        config.tokenRewardPerTokenPerEpoch = newTokenRewardPerTokenPerEpoch;
        config.complaintTolerance = newComplaintTolerance;
        config.complaintIntervalSecs = newComplaintIntervalSecs;
        config.keyTypes = newKeyTypes;
        config.minimumValidatorCount = newMinimumValidatorCount;
        emit ConfigSet(
            newTokenRewardPerTokenPerEpoch,
            newComplaintTolerance,
            newComplaintIntervalSecs,
            newKeyTypes,
            newMinimumValidatorCount
        );
    }

    /* ========== EVENTS ========== */

    event RewardsDurationUpdated(uint256 newDuration);
    event RequestToJoin(address indexed staker);
    event RequestToLeave(address indexed staker);
    event Recovered(address token, uint256 amount);
    event ReadyForNextEpoch(address indexed staker, uint256 epochNumber);
    event StateChanged(States newState);
    event VotedToKickValidatorInNextEpoch(
        address indexed reporter,
        address indexed validatorStakerAddress,
        uint256 indexed reason,
        bytes data
    );
    event ValidatorKickedFromNextEpoch(
        address indexed staker,
        uint256 amountBurned
    );

    // onlyOwner events
    event EpochLengthSet(uint256 newEpochLength);
    event EpochTimeoutSet(uint256 newEpochTimeout);
    event EpochEndTimeSet(uint256 newEpochEndTime);
    event StakingTokenSet(address newStakingTokenAddress);
    event KickPenaltyPercentSet(uint256 reason, uint256 newKickPenaltyPercent);
    event ResolverContractAddressSet(address newResolverContractAddress);
    event ConfigSet(
        uint256 newTokenRewardPerTokenPerEpoch,
        uint256 newComplaintTolerance,
        uint256 newComplaintIntervalSecs,
        uint256[] newKeyTypes,
        uint256 newMinimumValidatorCount
    );
    event ValidatorRejoinedNextEpoch(address staker);
}
          

@openzeppelin/contracts/token/ERC20/ERC20.sol

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

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20 is Context, IERC20, IERC20Metadata {
    mapping(address => uint256) private _balances;

    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual override returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `amount`.
     */
    function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, allowance(owner, spender) + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        address owner = _msgSender();
        uint256 currentAllowance = allowance(owner, spender);
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(address from, address to, uint256 amount) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
            // decrementing then incrementing.
            _balances[to] += amount;
        }

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        unchecked {
            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
            _balances[account] += amount;
        }
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
            // Overflow not possible: amount <= accountBalance <= totalSupply.
            _totalSupply -= amount;
        }

        emit Transfer(account, address(0), amount);

        _afterTokenTransfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(address owner, address spender, uint256 amount) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
     *
     * Does not update the allowance amount in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Might emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC20: insufficient allowance");
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}
          

@openzeppelin/contracts/utils/structs/EnumerableSet.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

pragma solidity ^0.8.0;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position of the value in the `values` array, plus 1 because index 0
        // means a value is not in the set.
        mapping(bytes32 => uint256) _indexes;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._indexes[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We read and store the value's index to prevent multiple reads from the same storage slot
        uint256 valueIndex = set._indexes[value];

        if (valueIndex != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 toDeleteIndex = valueIndex - 1;
            uint256 lastIndex = set._values.length - 1;

            if (lastIndex != toDeleteIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the last value to the index where the value to delete is
                set._values[toDeleteIndex] = lastValue;
                // Update the index for the moved value
                set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the index for the deleted slot
            delete set._indexes[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._indexes[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }
}
          

contracts/lit-node/StakingBalances.sol

//SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.17;

import { ERC20Burnable } from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { ContractResolver } from "../lit-core/ContractResolver.sol";
import { Staking } from "./Staking.sol";

import "hardhat/console.sol";

contract StakingBalances is Ownable {
    using EnumerableSet for EnumerableSet.AddressSet;

    ContractResolver public contractResolver;

    mapping(address => uint256) public balances;
    mapping(address => uint256) public rewards;

    // allowed stakers
    mapping(address => bool) public permittedStakers;

    struct VoteToKickValidatorInNextEpoch {
        uint256 votes;
        mapping(address => bool) voted;
    }

    // maps alias address to real staker address
    mapping(address => address) public aliases;
    // maps staker address to alias count
    mapping(address => uint256) public aliasCounts;

    uint256 public minimumStake;
    uint256 public maximumStake;
    uint256 public totalStaked;

    ContractResolver.Env public env;

    bool public permittedStakersOn;

    uint256 public maxAliasCount;

    uint256 public penaltyBalance;

    error CannotStakeZero();
    error StakeMustBeGreaterThanMinimumStake(
        uint256 amountStaked,
        uint256 minimumStake
    );
    error StakeMustBeLessThanMaximumStake(
        uint256 amountStaked,
        uint256 maximumStake
    );
    error TryingToWithdrawMoreThanStaked(
        uint256 yourBalance,
        uint256 requestedWithdrawlAmount
    );
    error CannotWithdrawZero();
    error OnlyStakingContract(address sender);
    error StakerNotPermitted(address stakerAddress);
    error ActiveValidatorsCannotLeave();
    error MaxAliasCountReached(uint256 aliasCount);
    error AliasNotOwnedBySender(address aliasAccount, address stakerAddress);
    error CannotRemoveAliasOfActiveValidator(address aliasAccount);

    modifier onlyStakingContract() {
        if (msg.sender != getStakingAddress()) {
            revert OnlyStakingContract(msg.sender);
        }
        _;
    }

    /* ========== CONSTRUCTOR ========== */
    constructor(address _resolver, ContractResolver.Env _env) {
        contractResolver = ContractResolver(_resolver);
        env = _env;
        ERC20Burnable stakingToken = ERC20Burnable(getTokenAddress());
        minimumStake = 1 * (10 ** stakingToken.decimals());
        maximumStake = minimumStake;
        maxAliasCount = 1;
    }

    /* ========== VIEWS ========== */
    /// get the staking address from the resolver
    function getStakingAddress() public view returns (address) {
        return
            contractResolver.getContract(
                contractResolver.STAKING_CONTRACT(),
                env
            );
    }

    /// get the token address from the resolver
    function getTokenAddress() public view returns (address) {
        return
            contractResolver.getContract(
                contractResolver.LIT_TOKEN_CONTRACT(),
                env
            );
    }

    function balanceOf(address account) external view returns (uint256) {
        // support aliases
        if (aliases[account] != address(0)) {
            account = aliases[account];
        }
        return balances[account];
    }

    function rewardOf(address account) external view returns (uint256) {
        // support aliases
        if (aliases[account] != address(0)) {
            account = aliases[account];
        }
        return rewards[account];
    }

    function isPermittedStaker(address staker) public view returns (bool) {
        // support aliases
        if (aliases[staker] != address(0)) {
            staker = aliases[staker];
        }
        return permittedStakers[staker];
    }

    function checkStakingAmounts(address account) public view returns (bool) {
        // support aliases
        if (aliases[account] != address(0)) {
            account = aliases[account];
        }
        uint256 amountStaked = balances[account];
        if (amountStaked < minimumStake) {
            revert StakeMustBeGreaterThanMinimumStake(
                amountStaked,
                minimumStake
            );
        }
        if (amountStaked > maximumStake) {
            revert StakeMustBeLessThanMaximumStake(amountStaked, maximumStake);
        }
        return true;
    }

    /* ========== MUTATIVE FUNCTIONS ========== */
    /// Stake tokens for a validator
    function stake(uint256 amount, address account) public onlyStakingContract {
        if (amount == 0) {
            revert CannotStakeZero();
        }

        if (permittedStakersOn && !permittedStakers[account]) {
            revert StakerNotPermitted(account);
        }

        ERC20Burnable stakingToken = ERC20Burnable(getTokenAddress());
        stakingToken.transferFrom(account, address(this), amount);
        balances[account] += amount;

        totalStaked += amount;

        emit Staked(account, amount);
    }

    /// Withdraw staked tokens.  This can only be done by users who are not active in the validator set.
    /// @param amount The amount of tokens to withdraw
    function withdraw(
        uint256 amount,
        address account
    ) public onlyStakingContract {
        if (amount == 0) {
            revert CannotWithdrawZero();
        }
        Staking staking = Staking(getStakingAddress());
        address[] memory validatorsInCurrentEpoch = staking
            .getValidatorsInCurrentEpoch();
        bool isValidatorInCurrentEpoch = false;
        for (uint256 i = 0; i < validatorsInCurrentEpoch.length; i++) {
            if (validatorsInCurrentEpoch[i] == account) {
                isValidatorInCurrentEpoch = true;
                break;
            }
        }
        if (isValidatorInCurrentEpoch) {
            revert ActiveValidatorsCannotLeave();
        }

        if (balances[account] < amount) {
            revert TryingToWithdrawMoreThanStaked(balances[account], amount);
        }

        totalStaked = totalStaked - amount;
        balances[account] = balances[account] - amount;

        ERC20Burnable stakingToken = ERC20Burnable(getTokenAddress());
        stakingToken.transfer(account, amount);
        emit Withdrawn(account, amount);
    }

    function rewardValidator(
        uint256 amount,
        address account
    ) public onlyStakingContract {
        // support aliases
        if (aliases[account] != address(0)) {
            // only reward if the main staking account is not an active validator, too
            Staking staking = Staking(getStakingAddress());
            if (staking.isActiveValidator(aliases[account])) {
                emit ValidatorNotRewardedBecauseAlias(
                    aliases[account],
                    account
                );
                return;
            }
            account = aliases[account];
        }
        rewards[account] += amount;
        emit ValidatorRewarded(account, amount);
    }

    function penalizeTokens(
        uint256 amount,
        address account
    ) public onlyStakingContract {
        if (aliases[account] != address(0)) {
            account = aliases[account];
        }

        balances[account] -= amount;
        totalStaked -= amount;

        penaltyBalance += amount;
        emit ValidatorTokensPenalized(account, amount);
    }

    /// Transfer any outstanding reward tokens
    function getReward(address account) public onlyStakingContract {
        if (aliases[account] != address(0)) {
            account = aliases[account];
        }

        uint256 reward = rewards[account];
        if (reward > 0) {
            rewards[account] = 0;
            ERC20Burnable stakingToken = ERC20Burnable(getStakingAddress());
            stakingToken.transfer(account, reward);
            emit RewardPaid(account, reward);
        }
    }

    /// Add an alias.  Must come from staker address.
    function addAlias(address aliasAccount) public {
        if (aliasCounts[msg.sender] >= maxAliasCount) {
            revert MaxAliasCountReached(aliasCounts[msg.sender]);
        }
        aliases[aliasAccount] = msg.sender;
        aliasCounts[msg.sender] += 1;
        emit AliasAdded(msg.sender, aliasAccount);
    }

    /// Remove an alias.  Must come from staker address.
    function removeAlias(address aliasAccount) public {
        // auth
        if (aliases[aliasAccount] != msg.sender) {
            revert AliasNotOwnedBySender(aliasAccount, msg.sender);
        }
        // don't let them remove an alias of an active validator
        Staking staking = Staking(getStakingAddress());
        if (staking.isActiveValidator(aliasAccount)) {
            revert CannotRemoveAliasOfActiveValidator(aliasAccount);
        }

        delete aliases[aliasAccount];
        aliasCounts[msg.sender] -= 1;
        emit AliasRemoved(msg.sender, aliasAccount);
    }

    // function adminSlashValidator(
    //     address validatorStakerAddress,
    //     uint256 amountToBurn
    // ) public onlyOwner {
    //     validators[validatorStakerAddress].balance -= amountToBurn;
    //     totalStaked -= amountToBurn;
    //     stakingToken.burn(amountToBurn);
    //     emit ValidatorKickedFromNextEpoch(validatorStakerAddress, amountToBurn);
    // }

    function withdrawPenaltyTokens(uint256 balance) public onlyOwner {
        require(balance <= penaltyBalance, "Not enough penalty balance");

        penaltyBalance -= balance;

        ERC20Burnable stakingToken = ERC20Burnable(getTokenAddress());
        stakingToken.transfer(msg.sender, balance);
    }

    function transferPenaltyTokens(
        uint256 balance,
        address recipient
    ) public onlyOwner {
        require(balance <= penaltyBalance, "Not enough penalty balance");

        penaltyBalance -= balance;

        ERC20Burnable stakingToken = ERC20Burnable(getTokenAddress());
        stakingToken.transfer(recipient, balance);
    }

    function restakePenaltyTokens(
        address staker,
        uint256 balance
    ) public onlyOwner {
        require(balance <= penaltyBalance, "Not enough penalty balance");

        totalStaked += balance;
        penaltyBalance -= balance;

        balances[staker] += balance;

        ERC20Burnable stakingToken = ERC20Burnable(getTokenAddress());
        stakingToken.transfer(address(this), balance);
    }

    /// this is for if someone accidently sends unwrapped tokens
    function withdraw() public onlyOwner {
        uint256 withdrawAmount = address(this).balance;
        (bool sent, ) = payable(msg.sender).call{ value: withdrawAmount }("");
        require(sent);
    }

    function addPermittedStakers(address[] memory stakers) public onlyOwner {
        for (uint256 i = 0; i < stakers.length; i++) {
            addPermittedStaker(stakers[i]);
        }
    }

    function addPermittedStaker(address staker) public onlyOwner {
        permittedStakers[staker] = true;
        emit PermittedStakerAdded(staker);
    }

    function removePermittedStaker(address staker) public onlyOwner {
        permittedStakers[staker] = false;
        emit PermittedStakerRemoved(staker);
    }

    function setPermittedStakersOn(bool permitted) public onlyOwner {
        permittedStakersOn = permitted;
        emit PermittedStakersOnChanged(permitted);
    }

    function setMinimumStake(uint256 newMinimumStake) public onlyOwner {
        minimumStake = newMinimumStake;
        emit MinimumStakeSet(newMinimumStake);
    }

    function setMaximumStake(uint256 newMaximumStake) public onlyOwner {
        maximumStake = newMaximumStake;
        emit MaximumStakeSet(newMaximumStake);
    }

    function setContractResolver(address newResolverAddress) public onlyOwner {
        contractResolver = ContractResolver(newResolverAddress);
        emit ResolverContractAddressSet(newResolverAddress);
    }

    function setMaxAliasCount(uint256 newMaxAliasCount) public onlyOwner {
        maxAliasCount = newMaxAliasCount;
        emit MaxAliasCountSet(newMaxAliasCount);
    }

    /* ========== EVENTS ========== */

    event Staked(address indexed staker, uint256 amount);
    event Withdrawn(address indexed staker, uint256 amount);
    event ValidatorRewarded(address indexed staker, uint256 amount);
    event ValidatorTokensPenalized(address indexed staker, uint256 amount);
    event RewardPaid(address indexed staker, uint256 reward);
    event AliasAdded(address indexed staker, address aliasAccount);
    event AliasRemoved(address indexed staker, address aliasAccount);
    event ValidatorNotRewardedBecauseAlias(
        address indexed staker,
        address aliasAccount
    );

    // onlyOwner events
    event TokenRewardPerTokenPerEpochSet(
        uint256 newTokenRewardPerTokenPerEpoch
    );
    event MinimumStakeSet(uint256 newMinimumStake);
    event MaximumStakeSet(uint256 newMaximumStake);
    event PermittedStakerAdded(address staker);
    event PermittedStakerRemoved(address staker);
    event PermittedStakersOnChanged(bool permittedStakersOn);
    event ResolverContractAddressSet(address newResolverAddress);
    event MaxAliasCountSet(uint newMaxAliasCount);
}
          

@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}
          

@openzeppelin/contracts/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

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

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}
          

@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/extensions/ERC721Burnable.sol)

pragma solidity ^0.8.0;

import "../ERC721.sol";
import "../../../utils/Context.sol";

/**
 * @title ERC721 Burnable Token
 * @dev ERC721 Token that can be burned (destroyed).
 */
abstract contract ERC721Burnable is Context, ERC721 {
    /**
     * @dev Burns `tokenId`. See {ERC721-_burn}.
     *
     * Requirements:
     *
     * - The caller must own `tokenId` or be an approved operator.
     */
    function burn(uint256 tokenId) public virtual {
        //solhint-disable-next-line max-line-length
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");
        _burn(tokenId);
    }
}
          

@openzeppelin/contracts/utils/introspection/ERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)

pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}
          

@openzeppelin/contracts/utils/structs/BitMaps.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/BitMaps.sol)
pragma solidity ^0.8.0;

/**
 * @dev Library for managing uint256 to bool mapping in a compact and efficient way, providing the keys are sequential.
 * Largely inspired by Uniswap's https://github.com/Uniswap/merkle-distributor/blob/master/contracts/MerkleDistributor.sol[merkle-distributor].
 */
library BitMaps {
    struct BitMap {
        mapping(uint256 => uint256) _data;
    }

    /**
     * @dev Returns whether the bit at `index` is set.
     */
    function get(BitMap storage bitmap, uint256 index) internal view returns (bool) {
        uint256 bucket = index >> 8;
        uint256 mask = 1 << (index & 0xff);
        return bitmap._data[bucket] & mask != 0;
    }

    /**
     * @dev Sets the bit at `index` to the boolean `value`.
     */
    function setTo(BitMap storage bitmap, uint256 index, bool value) internal {
        if (value) {
            set(bitmap, index);
        } else {
            unset(bitmap, index);
        }
    }

    /**
     * @dev Sets the bit at `index`.
     */
    function set(BitMap storage bitmap, uint256 index) internal {
        uint256 bucket = index >> 8;
        uint256 mask = 1 << (index & 0xff);
        bitmap._data[bucket] |= mask;
    }

    /**
     * @dev Unsets the bit at `index`.
     */
    function unset(BitMap storage bitmap, uint256 index) internal {
        uint256 bucket = index >> 8;
        uint256 mask = 1 << (index & 0xff);
        bitmap._data[bucket] &= ~mask;
    }
}
          

@openzeppelin/contracts/token/ERC20/IERC20.sol

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

@openzeppelin/contracts/access/IAccessControl.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)

pragma solidity ^0.8.0;

/**
 * @dev External interface of AccessControl declared to support ERC165 detection.
 */
interface IAccessControl {
    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     *
     * _Available since v3.1._
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call, an admin role
     * bearer except when using {AccessControl-_setupRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     */
    function renounceRole(bytes32 role, address account) external;
}
          

Contract ABI

[{"type":"constructor","stateMutability":"nonpayable","inputs":[{"type":"address","name":"_resolver","internalType":"address"},{"type":"uint8","name":"_env","internalType":"enum ContractResolver.Env"}]},{"type":"event","name":"ContractResolverAddressSet","inputs":[{"type":"address","name":"newResolverAddress","internalType":"address","indexed":false}],"anonymous":false},{"type":"event","name":"PubkeyRoutingDataSet","inputs":[{"type":"uint256","name":"tokenId","internalType":"uint256","indexed":true},{"type":"bytes","name":"pubkey","internalType":"bytes","indexed":false},{"type":"address","name":"stakingContract","internalType":"address","indexed":false},{"type":"uint256","name":"keyType","internalType":"uint256","indexed":false},{"type":"bytes32","name":"derivedKeyId","internalType":"bytes32","indexed":false}],"anonymous":false},{"type":"event","name":"RoleAdminChanged","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32","indexed":true},{"type":"bytes32","name":"previousAdminRole","internalType":"bytes32","indexed":true},{"type":"bytes32","name":"newAdminRole","internalType":"bytes32","indexed":true}],"anonymous":false},{"type":"event","name":"RoleGranted","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32","indexed":true},{"type":"address","name":"account","internalType":"address","indexed":true},{"type":"address","name":"sender","internalType":"address","indexed":true}],"anonymous":false},{"type":"event","name":"RoleRevoked","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32","indexed":true},{"type":"address","name":"account","internalType":"address","indexed":true},{"type":"address","name":"sender","internalType":"address","indexed":true}],"anonymous":false},{"type":"event","name":"RootKeySet","inputs":[{"type":"address","name":"stakingContract","internalType":"address","indexed":false},{"type":"tuple","name":"rootKey","internalType":"struct IPubkeyRouter.RootKey","indexed":false,"components":[{"type":"bytes","name":"pubkey","internalType":"bytes"},{"type":"uint256","name":"keyType","internalType":"uint256"}]}],"anonymous":false},{"type":"function","stateMutability":"view","outputs":[{"type":"bytes32","name":"","internalType":"bytes32"}],"name":"ADMIN_ROLE","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bytes32","name":"","internalType":"bytes32"}],"name":"DEFAULT_ADMIN_ROLE","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"checkNodeSignatures","inputs":[{"type":"tuple[]","name":"signatures","internalType":"struct IPubkeyRouter.Signature[]","components":[{"type":"bytes32","name":"r","internalType":"bytes32"},{"type":"bytes32","name":"s","internalType":"bytes32"},{"type":"uint8","name":"v","internalType":"uint8"}]},{"type":"bytes","name":"signedMessage","internalType":"bytes"},{"type":"address","name":"stakingContractAddress","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract ContractResolver"}],"name":"contractResolver","inputs":[]},{"type":"function","stateMutability":"pure","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"deriveEthAddressFromPubkey","inputs":[{"type":"bytes","name":"pubkey","internalType":"bytes"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint8","name":"","internalType":"enum ContractResolver.Env"}],"name":"env","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"ethAddressToPkpId","inputs":[{"type":"address","name":"","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bytes","name":"","internalType":"bytes"}],"name":"getDerivedPubkey","inputs":[{"type":"address","name":"stakingContract","internalType":"address"},{"type":"bytes32","name":"derivedKeyId","internalType":"bytes32"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"getEthAddress","inputs":[{"type":"uint256","name":"tokenId","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"getPkpNftAddress","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bytes","name":"","internalType":"bytes"}],"name":"getPubkey","inputs":[{"type":"uint256","name":"tokenId","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bytes32","name":"","internalType":"bytes32"}],"name":"getRoleAdmin","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"tuple[]","name":"","internalType":"struct IPubkeyRouter.RootKey[]","components":[{"type":"bytes","name":"pubkey","internalType":"bytes"},{"type":"uint256","name":"keyType","internalType":"uint256"}]}],"name":"getRootKeys","inputs":[{"type":"address","name":"stakingContract","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"tuple","name":"","internalType":"struct PubkeyRouter.PubkeyRoutingData","components":[{"type":"bytes","name":"pubkey","internalType":"bytes"},{"type":"uint256","name":"keyType","internalType":"uint256"},{"type":"bytes32","name":"derivedKeyId","internalType":"bytes32"}]}],"name":"getRoutingData","inputs":[{"type":"uint256","name":"tokenId","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"grantRole","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32"},{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"hasRole","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32"},{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"isRouted","inputs":[{"type":"uint256","name":"tokenId","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bytes","name":"pubkey","internalType":"bytes"},{"type":"uint256","name":"keyType","internalType":"uint256"},{"type":"bytes32","name":"derivedKeyId","internalType":"bytes32"}],"name":"pubkeys","inputs":[{"type":"uint256","name":"","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"renounceRole","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32"},{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"revokeRole","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32"},{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bytes","name":"pubkey","internalType":"bytes"},{"type":"uint256","name":"keyType","internalType":"uint256"}],"name":"rootKeys","inputs":[{"type":"address","name":"","internalType":"address"},{"type":"uint256","name":"","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setContractResolver","inputs":[{"type":"address","name":"newResolverAddress","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setRoutingData","inputs":[{"type":"uint256","name":"tokenId","internalType":"uint256"},{"type":"bytes","name":"pubkey","internalType":"bytes"},{"type":"address","name":"stakingContractAddress","internalType":"address"},{"type":"uint256","name":"keyType","internalType":"uint256"},{"type":"bytes32","name":"derivedKeyId","internalType":"bytes32"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setRoutingDataAsAdmin","inputs":[{"type":"uint256","name":"tokenId","internalType":"uint256"},{"type":"bytes","name":"pubkey","internalType":"bytes"},{"type":"address","name":"stakingContract","internalType":"address"},{"type":"uint256","name":"keyType","internalType":"uint256"},{"type":"bytes32","name":"derivedKeyId","internalType":"bytes32"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"supportsInterface","inputs":[{"type":"bytes4","name":"interfaceId","internalType":"bytes4"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"voteForRootKeys","inputs":[{"type":"address","name":"stakingContractAddress","internalType":"address"},{"type":"tuple[]","name":"newRootKeys","internalType":"struct IPubkeyRouter.RootKey[]","components":[{"type":"bytes","name":"pubkey","internalType":"bytes"},{"type":"uint256","name":"keyType","internalType":"uint256"}]}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"votes","internalType":"uint256"}],"name":"votesToRegisterRootKeys","inputs":[{"type":"address","name":"","internalType":"address"},{"type":"bytes","name":"","internalType":"bytes"}]}]
            

Contract Creation Code

Verify & Publish
0x60806040523480156200001157600080fd5b5060405162004d2c38038062004d2c833981810160405281019062000037919062000388565b81600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555080600160146101000a81548160ff02191690836002811115620000a0576200009f620003cf565b5b0217905550620000d77fdf8b4c520ffe197c5343c6f5aec59570151ef9a492f2c624fd45ddde6135ec42336200011160201b60201c565b620001097fdf8b4c520ffe197c5343c6f5aec59570151ef9a492f2c624fd45ddde6135ec42806200020260201b60201c565b5050620003fe565b6200012382826200026560201b60201c565b620001fe57600160008084815260200190815260200160002060000160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff021916908315150217905550620001a3620002cf60201b60201c565b73ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff16837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45b5050565b60006200021583620002d760201b60201c565b905081600080858152602001908152602001600020600101819055508181847fbd79b86ffe0ab8e8776151514217cd7cacd52c909f66475c3af44e129f0b00ff60405160405180910390a4505050565b600080600084815260200190815260200160002060000160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff16905092915050565b600033905090565b6000806000838152602001908152602001600020600101549050919050565b600080fd5b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b60006200032882620002fb565b9050919050565b6200033a816200031b565b81146200034657600080fd5b50565b6000815190506200035a816200032f565b92915050565b600381106200036e57600080fd5b50565b600081519050620003828162000360565b92915050565b60008060408385031215620003a257620003a1620002f6565b5b6000620003b28582860162000349565b9250506020620003c58582860162000371565b9150509250929050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602160045260246000fd5b61491e806200040e6000396000f3fe608060405234801561001057600080fd5b50600436106101a95760003560e01c80637bd3e3f6116100f9578063bd4986a011610097578063d547741f11610071578063d547741f14610543578063de18a5081461055f578063ef6fd8781461058f578063f95d71b1146105bf576101a9565b8063bd4986a0146104c5578063caead0c7146104f5578063cc609d2714610513576101a9565b80639dca0032116100d35780639dca0032146104295780639e45c02c14610447578063a217fddf14610477578063b4da9d7914610495576101a9565b80637bd3e3f6146103965780637cc3c6b7146103c857806391d14854146103f9576101a9565b80632f2ff15d116101665780634abc064d116101405780634abc064d1461032257806350d17b5e1461033e5780636e289d8e1461035c57806375b238fc14610378576101a9565b80632f2ff15d146102ba57806336568abe146102d657806343a2705f146102f2576101a9565b806301c6d035146101ae57806301ffc9a7146101de5780630fccbd621461020e578063191fe5331461022a578063248a9ca31461025a57806325c836f91461028a575b600080fd5b6101c860048036038101906101c391906128ab565b6105db565b6040516101d591906128f3565b60405180910390f35b6101f860048036038101906101f39190612966565b6106da565b60405161020591906128f3565b60405180910390f35b61022860048036038101906102239190612b6d565b610754565b005b610244600480360381019061023f9190612c04565b61094f565b6040516102519190612c6f565b60405180910390f35b610274600480360381019061026f9190612c8a565b610990565b6040516102819190612cc6565b60405180910390f35b6102a4600480360381019061029f91906128ab565b6109af565b6040516102b19190612dce565b60405180910390f35b6102d460048036038101906102cf9190612df0565b610a82565b005b6102f060048036038101906102eb9190612df0565b610aa3565b005b61030c60048036038101906103079190612e30565b610b26565b6040516103199190612eba565b60405180910390f35b61033c60048036038101906103379190613038565b610b50565b005b610346611099565b60405161035391906130f3565b60405180910390f35b61037660048036038101906103719190612b6d565b6110bf565b005b610380611219565b60405161038d9190612cc6565b60405180910390f35b6103b060048036038101906103ab91906128ab565b61123d565b6040516103bf9392919061310e565b60405180910390f35b6103e260048036038101906103dd919061314c565b6112ef565b6040516103f092919061318c565b60405180910390f35b610413600480360381019061040e9190612df0565b6113b8565b60405161042091906128f3565b60405180910390f35b610431611422565b60405161043e9190613233565b60405180910390f35b610461600480360381019061045c91906133ae565b611435565b60405161046e91906128f3565b60405180910390f35b61047f611616565b60405161048c9190612cc6565b60405180910390f35b6104af60048036038101906104aa9190613439565b61161d565b6040516104bc9190613565565b60405180910390f35b6104df60048036038101906104da91906128ab565b611757565b6040516104ec9190613596565b60405180910390f35b6104fd611807565b60405161050a9190613596565b60405180910390f35b61052d600480360381019061052891906135b1565b61194b565b60405161053a9190613596565b60405180910390f35b61055d60048036038101906105589190612df0565b61197a565b005b61057960048036038101906105749190613439565b61199b565b6040516105869190612c6f565b60405180910390f35b6105a960048036038101906105a491906128ab565b6119b3565b6040516105b69190612eba565b60405180910390f35b6105d960048036038101906105d49190613439565b611a5b565b005b6000806003600084815260200190815260200160002060405180606001604052908160008201805461060c90613629565b80601f016020809104026020016040519081016040528092919081815260200182805461063890613629565b80156106855780601f1061065a57610100808354040283529160200191610685565b820191906000526020600020905b81548152906001019060200180831161066857829003601f168201915b505050505081526020016001820154815260200160028201548152505090506000816000015151141580156106bf57506000816020015114155b80156106d257506000801b816040015114155b915050919050565b60007f7965db0b000000000000000000000000000000000000000000000000000000007bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916827bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916148061074d575061074c82611b01565b5b9050919050565b61075c611807565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16146107c9576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016107c0906136dd565b60405180910390fd5b838051906020012060001c8514610815576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161080c9061376f565b60405180910390fd5b61081e856105db565b1561085e576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161085590613801565b60405180910390fd5b8360036000878152602001908152602001600020600001908161088191906139c3565b5081600360008781526020019081526020016000206001018190555080600360008781526020019081526020016000206002018190555060006108c38561194b565b905085600460008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550857f0651cc1852188054ab1dc1f39e0a543b236620b2d303cdcf5ca15adc97c272be8686868660405161093f9493929190613a95565b60405180910390a2505050505050565b600260205281600052604060002081805160208101820180518482526020830160208501208183528095505050505050600091509150508060000154905081565b6000806000838152602001908152602001600020600101549050919050565b6109b761283d565b600360008381526020019081526020016000206040518060600160405290816000820180546109e590613629565b80601f0160208091040260200160405190810160405280929190818152602001828054610a1190613629565b8015610a5e5780601f10610a3357610100808354040283529160200191610a5e565b820191906000526020600020905b815481529060010190602001808311610a4157829003601f168201915b50505050508152602001600182015481526020016002820154815250509050919050565b610a8b82610990565b610a9481611b6b565b610a9e8383611b7f565b505050565b610aab611c5f565b73ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614610b18576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b0f90613b53565b60405180910390fd5b610b228282611c67565b5050565b60606000610b338461161d565b90506000610b4384836002611d48565b9050809250505092915050565b60008290508073ffffffffffffffffffffffffffffffffffffffff1663a25e49a4336040518263ffffffff1660e01b8152600401610b8e9190613596565b602060405180830381865afa158015610bab573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bcf9190613b9f565b610c0e576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610c0590613c3e565b60405180910390fd5b6000600560008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208054905014610c93576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610c8a90613cd0565b60405180910390fd5b60005b8251811015611093576000838281518110610cb457610cb3613cf0565b5b6020026020010151905060001515600260008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208260000151604051610d139190613d5b565b908152602001604051809103902060010160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff16151514610db1576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610da890613de4565b60405180910390fd5b6001600260008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208260000151604051610e049190613d5b565b90815260200160405180910390206000016000828254610e249190613e33565b925050819055506001600260008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208260000151604051610e7e9190613d5b565b908152602001604051809103902060010160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff0219169083151502179055508273ffffffffffffffffffffffffffffffffffffffff1663d4818fca6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610f2e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f529190613e7c565b600260008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208260000151604051610fa39190613d5b565b9081526020016040518091039020600001540361107f57600560008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819080600181540180825580915050600190039060005260206000209060020201600090919091909150600082015181600001908161103891906139c3565b506020820151816001015550507f960d418a88263b5c477aa3833dd1f4c69784abcbc0014ec8c21fb76b7a1f145c8582604051611076929190613ee6565b60405180910390a15b50808061108b90613f16565b915050610c96565b50505050565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6110e97fdf8b4c520ffe197c5343c6f5aec59570151ef9a492f2c624fd45ddde6135ec42336113b8565b611128576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161111f90613fd0565b60405180910390fd5b8360036000878152602001908152602001600020600001908161114b91906139c3565b50816003600087815260200190815260200160002060010181905550806003600087815260200190815260200160002060020181905550600061118d8561194b565b905085600460008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550857f0651cc1852188054ab1dc1f39e0a543b236620b2d303cdcf5ca15adc97c272be868686866040516112099493929190613a95565b60405180910390a2505050505050565b7fdf8b4c520ffe197c5343c6f5aec59570151ef9a492f2c624fd45ddde6135ec4281565b600360205280600052604060002060009150905080600001805461126090613629565b80601f016020809104026020016040519081016040528092919081815260200182805461128c90613629565b80156112d95780601f106112ae576101008083540402835291602001916112d9565b820191906000526020600020905b8154815290600101906020018083116112bc57829003601f168201915b5050505050908060010154908060020154905083565b6005602052816000526040600020818154811061130b57600080fd5b90600052602060002090600202016000915091505080600001805461132f90613629565b80601f016020809104026020016040519081016040528092919081815260200182805461135b90613629565b80156113a85780601f1061137d576101008083540402835291602001916113a8565b820191906000526020600020905b81548152906001019060200180831161138b57829003601f168201915b5050505050908060010154905082565b600080600084815260200190815260200160002060000160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff16905092915050565b600160149054906101000a900460ff1681565b6000808290508073ffffffffffffffffffffffffffffffffffffffff1663d4818fca6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611486573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114aa9190613e7c565b8551146114ec576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016114e390614062565b60405180910390fd5b60005b855181101561160957600086828151811061150d5761150c613cf0565b5b60200260200101519050600061153961152588611f62565b836040015184600001518560200151611f9d565b90508373ffffffffffffffffffffffffffffffffffffffff1663a25e49a4826040518263ffffffff1660e01b81526004016115749190613596565b602060405180830381865afa158015611591573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115b59190613b9f565b6115f4576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016115eb906140f4565b60405180910390fd5b5050808061160190613f16565b9150506114ef565b5060019150509392505050565b6000801b81565b6060600560008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020805480602002602001604051908101604052809291908181526020016000905b8282101561174c57838290600052602060002090600202016040518060400160405290816000820180546116b190613629565b80601f01602080910402602001604051908101604052809291908181526020018280546116dd90613629565b801561172a5780601f106116ff5761010080835404028352916020019161172a565b820191906000526020600020905b81548152906001019060200180831161170d57829003601f168201915b505050505081526020016001820154815250508152602001906001019061167e565b505050509050919050565b600061180060036000848152602001908152602001600020600001805461177d90613629565b80601f01602080910402602001604051908101604052809291908181526020018280546117a990613629565b80156117f65780601f106117cb576101008083540402835291602001916117f6565b820191906000526020600020905b8154815290600101906020018083116117d957829003601f168201915b505050505061194b565b9050919050565b6000600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16638e8dfd16600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16632c0b8bf76040518163ffffffff1660e01b8152600401602060405180830381865afa1580156118b4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118d89190614129565b600160149054906101000a900460ff166040518363ffffffff1660e01b8152600401611905929190614156565b602060405180830381865afa158015611922573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119469190614194565b905090565b6000806119656001604085611fc89092919063ffffffff16565b8051906020012090508060001c915050919050565b61198382610990565b61198c81611b6b565b6119968383611c67565b505050565b60046020528060005260406000206000915090505481565b60606003600083815260200190815260200160002060000180546119d690613629565b80601f0160208091040260200160405190810160405280929190818152602001828054611a0290613629565b8015611a4f5780601f10611a2457610100808354040283529160200191611a4f565b820191906000526020600020905b815481529060010190602001808311611a3257829003601f168201915b50505050509050919050565b7fdf8b4c520ffe197c5343c6f5aec59570151ef9a492f2c624fd45ddde6135ec42611a8581611b6b565b81600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055507f2760073c7cd8cac531d7f643becbfbb74d8b8156443eacf879622532dbbb3cd582604051611af59190613596565b60405180910390a15050565b60007f01ffc9a7000000000000000000000000000000000000000000000000000000007bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916827bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916149050919050565b611b7c81611b77611c5f565b6120e6565b50565b611b8982826113b8565b611c5b57600160008084815260200190815260200160002060000160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff021916908315150217905550611c00611c5f565b73ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff16837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45b5050565b600033905090565b611c7182826113b8565b15611d4457600080600084815260200190815260200160002060000160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff021916908315150217905550611ce9611c5f565b73ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff16837ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b60405160405180910390a45b5050565b60606000600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16638e8dfd16600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166385cb11916040518163ffffffff1660e01b8152600401602060405180830381865afa158015611df7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e1b9190614129565b600160149054906101000a900460ff166040518363ffffffff1660e01b8152600401611e48929190614156565b602060405180830381865afa158015611e65573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e899190614194565b90506000808273ffffffffffffffffffffffffffffffffffffffff1663a32c2b998888886040518463ffffffff1660e01b8152600401611ecb939291906141c1565b600060405180830381865afa158015611ee8573d6000803e3d6000fd5b505050506040513d6000823e3d601f19601f82011682018060405250810190611f11919061426f565b9150915081611f55576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611f4c9061433d565b60405180910390fd5b8093505050509392505050565b6000611f6e825161216b565b82604051602001611f809291906143f0565b604051602081830303815290604052805190602001209050919050565b6000806000611fae87878787612239565b91509150611fbb8161231b565b8192505050949350505050565b606081601f83611fd89190613e33565b1015612019576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016120109061446b565b60405180910390fd5b81836120259190613e33565b84511015612068576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161205f906144d7565b60405180910390fd5b606082156000811461208957604051915060008252602082016040526120da565b6040519150601f8416801560200281840101858101878315602002848b0101015b818310156120c757805183526020830192506020810190506120aa565b50868552601f19601f8301166040525050505b50809150509392505050565b6120f082826113b8565b612167576120fd81612481565b61210b8360001c60206124ae565b60405160200161211c92919061458f565b6040516020818303038152906040526040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161215e9190614602565b60405180910390fd5b5050565b60606000600161217a846126ea565b01905060008167ffffffffffffffff811115612199576121986129ae565b5b6040519080825280601f01601f1916602001820160405280156121cb5781602001600182028036833780820191505090505b509050600082602001820190505b60011561222e578080600190039150507f3031323334353637383961626364656600000000000000000000000000000000600a86061a8153600a858161222257612221614624565b5b049450600085036121d9575b819350505050919050565b6000807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08360001c1115612274576000600391509150612312565b6000600187878787604051600081526020016040526040516122999493929190614662565b6020604051602081039080840390855afa1580156122bb573d6000803e3d6000fd5b505050602060405103519050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff160361230957600060019250925050612312565b80600092509250505b94509492505050565b6000600481111561232f5761232e6131bc565b5b816004811115612342576123416131bc565b5b031561247e576001600481111561235c5761235b6131bc565b5b81600481111561236f5761236e6131bc565b5b036123af576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016123a6906146f3565b60405180910390fd5b600260048111156123c3576123c26131bc565b5b8160048111156123d6576123d56131bc565b5b03612416576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161240d9061475f565b60405180910390fd5b6003600481111561242a576124296131bc565b5b81600481111561243d5761243c6131bc565b5b0361247d576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401612474906147f1565b60405180910390fd5b5b50565b60606124a78273ffffffffffffffffffffffffffffffffffffffff16601460ff166124ae565b9050919050565b6060600060028360026124c19190614811565b6124cb9190613e33565b67ffffffffffffffff8111156124e4576124e36129ae565b5b6040519080825280601f01601f1916602001820160405280156125165781602001600182028036833780820191505090505b5090507f30000000000000000000000000000000000000000000000000000000000000008160008151811061254e5761254d613cf0565b5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a9053507f7800000000000000000000000000000000000000000000000000000000000000816001815181106125b2576125b1613cf0565b5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a905350600060018460026125f29190614811565b6125fc9190613e33565b90505b600181111561269c577f3031323334353637383961626364656600000000000000000000000000000000600f86166010811061263e5761263d613cf0565b5b1a60f81b82828151811061265557612654613cf0565b5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a905350600485901c94508061269590614853565b90506125ff565b50600084146126e0576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016126d7906148c8565b60405180910390fd5b8091505092915050565b600080600090507a184f03e93ff9f4daa797ed6e38ed64bf6a1f0100000000000000008310612748577a184f03e93ff9f4daa797ed6e38ed64bf6a1f010000000000000000838161273e5761273d614624565b5b0492506040810190505b6d04ee2d6d415b85acef81000000008310612785576d04ee2d6d415b85acef8100000000838161277b5761277a614624565b5b0492506020810190505b662386f26fc1000083106127b457662386f26fc1000083816127aa576127a9614624565b5b0492506010810190505b6305f5e10083106127dd576305f5e10083816127d3576127d2614624565b5b0492506008810190505b61271083106128025761271083816127f8576127f7614624565b5b0492506004810190505b60648310612825576064838161281b5761281a614624565b5b0492506002810190505b600a8310612834576001810190505b80915050919050565b60405180606001604052806060815260200160008152602001600080191681525090565b6000604051905090565b600080fd5b600080fd5b6000819050919050565b61288881612875565b811461289357600080fd5b50565b6000813590506128a58161287f565b92915050565b6000602082840312156128c1576128c061286b565b5b60006128cf84828501612896565b91505092915050565b60008115159050919050565b6128ed816128d8565b82525050565b600060208201905061290860008301846128e4565b92915050565b60007fffffffff0000000000000000000000000000000000000000000000000000000082169050919050565b6129438161290e565b811461294e57600080fd5b50565b6000813590506129608161293a565b92915050565b60006020828403121561297c5761297b61286b565b5b600061298a84828501612951565b91505092915050565b600080fd5b600080fd5b6000601f19601f8301169050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b6129e68261299d565b810181811067ffffffffffffffff82111715612a0557612a046129ae565b5b80604052505050565b6000612a18612861565b9050612a2482826129dd565b919050565b600067ffffffffffffffff821115612a4457612a436129ae565b5b612a4d8261299d565b9050602081019050919050565b82818337600083830152505050565b6000612a7c612a7784612a29565b612a0e565b905082815260208101848484011115612a9857612a97612998565b5b612aa3848285612a5a565b509392505050565b600082601f830112612ac057612abf612993565b5b8135612ad0848260208601612a69565b91505092915050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b6000612b0482612ad9565b9050919050565b612b1481612af9565b8114612b1f57600080fd5b50565b600081359050612b3181612b0b565b92915050565b6000819050919050565b612b4a81612b37565b8114612b5557600080fd5b50565b600081359050612b6781612b41565b92915050565b600080600080600060a08688031215612b8957612b8861286b565b5b6000612b9788828901612896565b955050602086013567ffffffffffffffff811115612bb857612bb7612870565b5b612bc488828901612aab565b9450506040612bd588828901612b22565b9350506060612be688828901612896565b9250506080612bf788828901612b58565b9150509295509295909350565b60008060408385031215612c1b57612c1a61286b565b5b6000612c2985828601612b22565b925050602083013567ffffffffffffffff811115612c4a57612c49612870565b5b612c5685828601612aab565b9150509250929050565b612c6981612875565b82525050565b6000602082019050612c846000830184612c60565b92915050565b600060208284031215612ca057612c9f61286b565b5b6000612cae84828501612b58565b91505092915050565b612cc081612b37565b82525050565b6000602082019050612cdb6000830184612cb7565b92915050565b600081519050919050565b600082825260208201905092915050565b60005b83811015612d1b578082015181840152602081019050612d00565b60008484015250505050565b6000612d3282612ce1565b612d3c8185612cec565b9350612d4c818560208601612cfd565b612d558161299d565b840191505092915050565b612d6981612875565b82525050565b612d7881612b37565b82525050565b60006060830160008301518482036000860152612d9b8282612d27565b9150506020830151612db06020860182612d60565b506040830151612dc36040860182612d6f565b508091505092915050565b60006020820190508181036000830152612de88184612d7e565b905092915050565b60008060408385031215612e0757612e0661286b565b5b6000612e1585828601612b58565b9250506020612e2685828601612b22565b9150509250929050565b60008060408385031215612e4757612e4661286b565b5b6000612e5585828601612b22565b9250506020612e6685828601612b58565b9150509250929050565b600082825260208201905092915050565b6000612e8c82612ce1565b612e968185612e70565b9350612ea6818560208601612cfd565b612eaf8161299d565b840191505092915050565b60006020820190508181036000830152612ed48184612e81565b905092915050565b600067ffffffffffffffff821115612ef757612ef66129ae565b5b602082029050602081019050919050565b600080fd5b600080fd5b600080fd5b600060408284031215612f2d57612f2c612f0d565b5b612f376040612a0e565b9050600082013567ffffffffffffffff811115612f5757612f56612f12565b5b612f6384828501612aab565b6000830152506020612f7784828501612896565b60208301525092915050565b6000612f96612f9184612edc565b612a0e565b90508083825260208201905060208402830185811115612fb957612fb8612f08565b5b835b8181101561300057803567ffffffffffffffff811115612fde57612fdd612993565b5b808601612feb8982612f17565b85526020850194505050602081019050612fbb565b5050509392505050565b600082601f83011261301f5761301e612993565b5b813561302f848260208601612f83565b91505092915050565b6000806040838503121561304f5761304e61286b565b5b600061305d85828601612b22565b925050602083013567ffffffffffffffff81111561307e5761307d612870565b5b61308a8582860161300a565b9150509250929050565b6000819050919050565b60006130b96130b46130af84612ad9565b613094565b612ad9565b9050919050565b60006130cb8261309e565b9050919050565b60006130dd826130c0565b9050919050565b6130ed816130d2565b82525050565b600060208201905061310860008301846130e4565b92915050565b600060608201905081810360008301526131288186612e81565b90506131376020830185612c60565b6131446040830184612cb7565b949350505050565b600080604083850312156131635761316261286b565b5b600061317185828601612b22565b925050602061318285828601612896565b9150509250929050565b600060408201905081810360008301526131a68185612e81565b90506131b56020830184612c60565b9392505050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602160045260246000fd5b600381106131fc576131fb6131bc565b5b50565b600081905061320d826131eb565b919050565b600061321d826131ff565b9050919050565b61322d81613212565b82525050565b60006020820190506132486000830184613224565b92915050565b600067ffffffffffffffff821115613269576132686129ae565b5b602082029050602081019050919050565b600060ff82169050919050565b6132908161327a565b811461329b57600080fd5b50565b6000813590506132ad81613287565b92915050565b6000606082840312156132c9576132c8612f0d565b5b6132d36060612a0e565b905060006132e384828501612b58565b60008301525060206132f784828501612b58565b602083015250604061330b8482850161329e565b60408301525092915050565b600061332a6133258461324e565b612a0e565b9050808382526020820190506060840283018581111561334d5761334c612f08565b5b835b81811015613376578061336288826132b3565b84526020840193505060608101905061334f565b5050509392505050565b600082601f83011261339557613394612993565b5b81356133a5848260208601613317565b91505092915050565b6000806000606084860312156133c7576133c661286b565b5b600084013567ffffffffffffffff8111156133e5576133e4612870565b5b6133f186828701613380565b935050602084013567ffffffffffffffff81111561341257613411612870565b5b61341e86828701612aab565b925050604061342f86828701612b22565b9150509250925092565b60006020828403121561344f5761344e61286b565b5b600061345d84828501612b22565b91505092915050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b600060408301600083015184820360008601526134af8282612d27565b91505060208301516134c46020860182612d60565b508091505092915050565b60006134db8383613492565b905092915050565b6000602082019050919050565b60006134fb82613466565b6135058185613471565b93508360208202850161351785613482565b8060005b85811015613553578484038952815161353485826134cf565b945061353f836134e3565b925060208a0199505060018101905061351b565b50829750879550505050505092915050565b6000602082019050818103600083015261357f81846134f0565b905092915050565b61359081612af9565b82525050565b60006020820190506135ab6000830184613587565b92915050565b6000602082840312156135c7576135c661286b565b5b600082013567ffffffffffffffff8111156135e5576135e4612870565b5b6135f184828501612aab565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b6000600282049050600182168061364157607f821691505b602082108103613654576136536135fa565b5b50919050565b600082825260208201905092915050565b7f736574526f7574696e6744617461206d7573742062652063616c6c656420627960008201527f20504b504e465420636f6e747261637400000000000000000000000000000000602082015250565b60006136c760308361365a565b91506136d28261366b565b604082019050919050565b600060208201905081810360008301526136f6816136ba565b9050919050565b7f746f6b656e496420646f6573206e6f74206d617463682068617368656420707560008201527f626b657900000000000000000000000000000000000000000000000000000000602082015250565b600061375960248361365a565b9150613764826136fd565b604082019050919050565b600060208201905081810360008301526137888161374c565b9050919050565b7f5075626b6579526f757465723a207075626b657920616c72656164792068617360008201527f20726f7574696e67206461746100000000000000000000000000000000000000602082015250565b60006137eb602d8361365a565b91506137f68261378f565b604082019050919050565b6000602082019050818103600083015261381a816137de565b9050919050565b60008190508160005260206000209050919050565b60006020601f8301049050919050565b600082821b905092915050565b6000600883026138837fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff82613846565b61388d8683613846565b95508019841693508086168417925050509392505050565b60006138c06138bb6138b684612875565b613094565b612875565b9050919050565b6000819050919050565b6138da836138a5565b6138ee6138e6826138c7565b848454613853565b825550505050565b600090565b6139036138f6565b61390e8184846138d1565b505050565b5b81811015613932576139276000826138fb565b600181019050613914565b5050565b601f8211156139775761394881613821565b61395184613836565b81016020851015613960578190505b61397461396c85613836565b830182613913565b50505b505050565b600082821c905092915050565b600061399a6000198460080261397c565b1980831691505092915050565b60006139b38383613989565b9150826002028217905092915050565b6139cc82612ce1565b67ffffffffffffffff8111156139e5576139e46129ae565b5b6139ef8254613629565b6139fa828285613936565b600060209050601f831160018114613a2d5760008415613a1b578287015190505b613a2585826139a7565b865550613a8d565b601f198416613a3b86613821565b60005b82811015613a6357848901518255600182019150602085019450602081019050613a3e565b86831015613a805784890151613a7c601f891682613989565b8355505b6001600288020188555050505b505050505050565b60006080820190508181036000830152613aaf8187612e81565b9050613abe6020830186613587565b613acb6040830185612c60565b613ad86060830184612cb7565b95945050505050565b7f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560008201527f20726f6c657320666f722073656c660000000000000000000000000000000000602082015250565b6000613b3d602f8361365a565b9150613b4882613ae1565b604082019050919050565b60006020820190508181036000830152613b6c81613b30565b9050919050565b613b7c816128d8565b8114613b8757600080fd5b50565b600081519050613b9981613b73565b92915050565b600060208284031215613bb557613bb461286b565b5b6000613bc384828501613b8a565b91505092915050565b7f5075626b6579526f757465723a2074786e2073656e646572206973206e6f742060008201527f6163746976652076616c696461746f7200000000000000000000000000000000602082015250565b6000613c2860308361365a565b9150613c3382613bcc565b604082019050919050565b60006020820190508181036000830152613c5781613c1b565b9050919050565b7f5075626b6579526f757465723a20726f6f74206b65797320616c72656164792060008201527f73657420666f722074686973207374616b696e6720636f6e7472616374000000602082015250565b6000613cba603d8361365a565b9150613cc582613c5e565b604082019050919050565b60006020820190508181036000830152613ce981613cad565b9050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600081905092915050565b6000613d3582612ce1565b613d3f8185613d1f565b9350613d4f818560208601612cfd565b80840191505092915050565b6000613d678284613d2a565b915081905092915050565b7f5075626b6579526f757465723a2076616c696461746f722068617320616c726560008201527f61647920766f74656420666f72207468697320726f6f74206b65790000000000602082015250565b6000613dce603b8361365a565b9150613dd982613d72565b604082019050919050565b60006020820190508181036000830152613dfd81613dc1565b9050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b6000613e3e82612875565b9150613e4983612875565b9250828201905080821115613e6157613e60613e04565b5b92915050565b600081519050613e768161287f565b92915050565b600060208284031215613e9257613e9161286b565b5b6000613ea084828501613e67565b91505092915050565b60006040830160008301518482036000860152613ec68282612d27565b9150506020830151613edb6020860182612d60565b508091505092915050565b6000604082019050613efb6000830185613587565b8181036020830152613f0d8184613ea9565b90509392505050565b6000613f2182612875565b91507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8203613f5357613f52613e04565b5b600182019050919050565b7f5075626b6579526f757465723a206d75737420686176652061646d696e20726f60008201527f6c65000000000000000000000000000000000000000000000000000000000000602082015250565b6000613fba60228361365a565b9150613fc582613f5e565b604082019050919050565b60006020820190508181036000830152613fe981613fad565b9050919050565b7f5075626b6579526f757465723a20696e636f7272656374206e756d626572206f60008201527f66207369676e617475726573206f6e206120676976656e20726f6f74206b6579602082015250565b600061404c60408361365a565b915061405782613ff0565b604082019050919050565b6000602082019050818103600083015261407b8161403f565b9050919050565b7f5075626b6579526f757465723a207369676e6572206973206e6f74206163746960008201527f76652076616c696461746f720000000000000000000000000000000000000000602082015250565b60006140de602c8361365a565b91506140e982614082565b604082019050919050565b6000602082019050818103600083015261410d816140d1565b9050919050565b60008151905061412381612b41565b92915050565b60006020828403121561413f5761413e61286b565b5b600061414d84828501614114565b91505092915050565b600060408201905061416b6000830185612cb7565b6141786020830184613224565b9392505050565b60008151905061418e81612b0b565b92915050565b6000602082840312156141aa576141a961286b565b5b60006141b88482850161417f565b91505092915050565b60006060820190506141d66000830186612cb7565b81810360208301526141e881856134f0565b90506141f76040830184612c60565b949350505050565b600061421261420d84612a29565b612a0e565b90508281526020810184848401111561422e5761422d612998565b5b614239848285612cfd565b509392505050565b600082601f83011261425657614255612993565b5b81516142668482602086016141ff565b91505092915050565b600080604083850312156142865761428561286b565b5b600061429485828601613b8a565b925050602083015167ffffffffffffffff8111156142b5576142b4612870565b5b6142c185828601614241565b9150509250929050565b7f5075626b6579526f757465723a204661696c6564207075626c6963206b65792060008201527f63616c63756c6174696f6e000000000000000000000000000000000000000000602082015250565b6000614327602b8361365a565b9150614332826142cb565b604082019050919050565b600060208201905081810360008301526143568161431a565b9050919050565b600081905092915050565b7f19457468657265756d205369676e6564204d6573736167653a0a000000000000600082015250565b600061439e601a8361435d565b91506143a982614368565b601a82019050919050565b600081519050919050565b60006143ca826143b4565b6143d4818561435d565b93506143e4818560208601612cfd565b80840191505092915050565b60006143fb82614391565b915061440782856143bf565b91506144138284613d2a565b91508190509392505050565b7f736c6963655f6f766572666c6f77000000000000000000000000000000000000600082015250565b6000614455600e8361365a565b91506144608261441f565b602082019050919050565b6000602082019050818103600083015261448481614448565b9050919050565b7f736c6963655f6f75744f66426f756e6473000000000000000000000000000000600082015250565b60006144c160118361365a565b91506144cc8261448b565b602082019050919050565b600060208201905081810360008301526144f0816144b4565b9050919050565b7f416363657373436f6e74726f6c3a206163636f756e7420000000000000000000600082015250565b600061452d60178361435d565b9150614538826144f7565b601782019050919050565b7f206973206d697373696e6720726f6c6520000000000000000000000000000000600082015250565b600061457960118361435d565b915061458482614543565b601182019050919050565b600061459a82614520565b91506145a682856143bf565b91506145b18261456c565b91506145bd82846143bf565b91508190509392505050565b60006145d4826143b4565b6145de818561365a565b93506145ee818560208601612cfd565b6145f78161299d565b840191505092915050565b6000602082019050818103600083015261461c81846145c9565b905092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b61465c8161327a565b82525050565b60006080820190506146776000830187612cb7565b6146846020830186614653565b6146916040830185612cb7565b61469e6060830184612cb7565b95945050505050565b7f45434453413a20696e76616c6964207369676e61747572650000000000000000600082015250565b60006146dd60188361365a565b91506146e8826146a7565b602082019050919050565b6000602082019050818103600083015261470c816146d0565b9050919050565b7f45434453413a20696e76616c6964207369676e6174757265206c656e67746800600082015250565b6000614749601f8361365a565b915061475482614713565b602082019050919050565b600060208201905081810360008301526147788161473c565b9050919050565b7f45434453413a20696e76616c6964207369676e6174757265202773272076616c60008201527f7565000000000000000000000000000000000000000000000000000000000000602082015250565b60006147db60228361365a565b91506147e68261477f565b604082019050919050565b6000602082019050818103600083015261480a816147ce565b9050919050565b600061481c82612875565b915061482783612875565b925082820261483581612875565b9150828204841483151761484c5761484b613e04565b5b5092915050565b600061485e82612875565b91506000820361487157614870613e04565b5b600182039050919050565b7f537472696e67733a20686578206c656e67746820696e73756666696369656e74600082015250565b60006148b260208361365a565b91506148bd8261487c565b602082019050919050565b600060208201905081810360008301526148e1816148a5565b905091905056fea2646970667358221220d1021b8a42e5b231ff40dfab015d0419b12e8e59c84f0919fa4dc03eb12186a464736f6c634300081100330000000000000000000000000bca885cf322d0e478dc48fb84b4f522144db9d70000000000000000000000000000000000000000000000000000000000000000

Deployed ByteCode

0x608060405234801561001057600080fd5b50600436106101a95760003560e01c80637bd3e3f6116100f9578063bd4986a011610097578063d547741f11610071578063d547741f14610543578063de18a5081461055f578063ef6fd8781461058f578063f95d71b1146105bf576101a9565b8063bd4986a0146104c5578063caead0c7146104f5578063cc609d2714610513576101a9565b80639dca0032116100d35780639dca0032146104295780639e45c02c14610447578063a217fddf14610477578063b4da9d7914610495576101a9565b80637bd3e3f6146103965780637cc3c6b7146103c857806391d14854146103f9576101a9565b80632f2ff15d116101665780634abc064d116101405780634abc064d1461032257806350d17b5e1461033e5780636e289d8e1461035c57806375b238fc14610378576101a9565b80632f2ff15d146102ba57806336568abe146102d657806343a2705f146102f2576101a9565b806301c6d035146101ae57806301ffc9a7146101de5780630fccbd621461020e578063191fe5331461022a578063248a9ca31461025a57806325c836f91461028a575b600080fd5b6101c860048036038101906101c391906128ab565b6105db565b6040516101d591906128f3565b60405180910390f35b6101f860048036038101906101f39190612966565b6106da565b60405161020591906128f3565b60405180910390f35b61022860048036038101906102239190612b6d565b610754565b005b610244600480360381019061023f9190612c04565b61094f565b6040516102519190612c6f565b60405180910390f35b610274600480360381019061026f9190612c8a565b610990565b6040516102819190612cc6565b60405180910390f35b6102a4600480360381019061029f91906128ab565b6109af565b6040516102b19190612dce565b60405180910390f35b6102d460048036038101906102cf9190612df0565b610a82565b005b6102f060048036038101906102eb9190612df0565b610aa3565b005b61030c60048036038101906103079190612e30565b610b26565b6040516103199190612eba565b60405180910390f35b61033c60048036038101906103379190613038565b610b50565b005b610346611099565b60405161035391906130f3565b60405180910390f35b61037660048036038101906103719190612b6d565b6110bf565b005b610380611219565b60405161038d9190612cc6565b60405180910390f35b6103b060048036038101906103ab91906128ab565b61123d565b6040516103bf9392919061310e565b60405180910390f35b6103e260048036038101906103dd919061314c565b6112ef565b6040516103f092919061318c565b60405180910390f35b610413600480360381019061040e9190612df0565b6113b8565b60405161042091906128f3565b60405180910390f35b610431611422565b60405161043e9190613233565b60405180910390f35b610461600480360381019061045c91906133ae565b611435565b60405161046e91906128f3565b60405180910390f35b61047f611616565b60405161048c9190612cc6565b60405180910390f35b6104af60048036038101906104aa9190613439565b61161d565b6040516104bc9190613565565b60405180910390f35b6104df60048036038101906104da91906128ab565b611757565b6040516104ec9190613596565b60405180910390f35b6104fd611807565b60405161050a9190613596565b60405180910390f35b61052d600480360381019061052891906135b1565b61194b565b60405161053a9190613596565b60405180910390f35b61055d60048036038101906105589190612df0565b61197a565b005b61057960048036038101906105749190613439565b61199b565b6040516105869190612c6f565b60405180910390f35b6105a960048036038101906105a491906128ab565b6119b3565b6040516105b69190612eba565b60405180910390f35b6105d960048036038101906105d49190613439565b611a5b565b005b6000806003600084815260200190815260200160002060405180606001604052908160008201805461060c90613629565b80601f016020809104026020016040519081016040528092919081815260200182805461063890613629565b80156106855780601f1061065a57610100808354040283529160200191610685565b820191906000526020600020905b81548152906001019060200180831161066857829003601f168201915b505050505081526020016001820154815260200160028201548152505090506000816000015151141580156106bf57506000816020015114155b80156106d257506000801b816040015114155b915050919050565b60007f7965db0b000000000000000000000000000000000000000000000000000000007bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916827bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916148061074d575061074c82611b01565b5b9050919050565b61075c611807565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16146107c9576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016107c0906136dd565b60405180910390fd5b838051906020012060001c8514610815576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161080c9061376f565b60405180910390fd5b61081e856105db565b1561085e576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161085590613801565b60405180910390fd5b8360036000878152602001908152602001600020600001908161088191906139c3565b5081600360008781526020019081526020016000206001018190555080600360008781526020019081526020016000206002018190555060006108c38561194b565b905085600460008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550857f0651cc1852188054ab1dc1f39e0a543b236620b2d303cdcf5ca15adc97c272be8686868660405161093f9493929190613a95565b60405180910390a2505050505050565b600260205281600052604060002081805160208101820180518482526020830160208501208183528095505050505050600091509150508060000154905081565b6000806000838152602001908152602001600020600101549050919050565b6109b761283d565b600360008381526020019081526020016000206040518060600160405290816000820180546109e590613629565b80601f0160208091040260200160405190810160405280929190818152602001828054610a1190613629565b8015610a5e5780601f10610a3357610100808354040283529160200191610a5e565b820191906000526020600020905b815481529060010190602001808311610a4157829003601f168201915b50505050508152602001600182015481526020016002820154815250509050919050565b610a8b82610990565b610a9481611b6b565b610a9e8383611b7f565b505050565b610aab611c5f565b73ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614610b18576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b0f90613b53565b60405180910390fd5b610b228282611c67565b5050565b60606000610b338461161d565b90506000610b4384836002611d48565b9050809250505092915050565b60008290508073ffffffffffffffffffffffffffffffffffffffff1663a25e49a4336040518263ffffffff1660e01b8152600401610b8e9190613596565b602060405180830381865afa158015610bab573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bcf9190613b9f565b610c0e576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610c0590613c3e565b60405180910390fd5b6000600560008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208054905014610c93576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610c8a90613cd0565b60405180910390fd5b60005b8251811015611093576000838281518110610cb457610cb3613cf0565b5b6020026020010151905060001515600260008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208260000151604051610d139190613d5b565b908152602001604051809103902060010160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff16151514610db1576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610da890613de4565b60405180910390fd5b6001600260008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208260000151604051610e049190613d5b565b90815260200160405180910390206000016000828254610e249190613e33565b925050819055506001600260008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208260000151604051610e7e9190613d5b565b908152602001604051809103902060010160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff0219169083151502179055508273ffffffffffffffffffffffffffffffffffffffff1663d4818fca6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610f2e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f529190613e7c565b600260008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208260000151604051610fa39190613d5b565b9081526020016040518091039020600001540361107f57600560008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819080600181540180825580915050600190039060005260206000209060020201600090919091909150600082015181600001908161103891906139c3565b506020820151816001015550507f960d418a88263b5c477aa3833dd1f4c69784abcbc0014ec8c21fb76b7a1f145c8582604051611076929190613ee6565b60405180910390a15b50808061108b90613f16565b915050610c96565b50505050565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6110e97fdf8b4c520ffe197c5343c6f5aec59570151ef9a492f2c624fd45ddde6135ec42336113b8565b611128576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161111f90613fd0565b60405180910390fd5b8360036000878152602001908152602001600020600001908161114b91906139c3565b50816003600087815260200190815260200160002060010181905550806003600087815260200190815260200160002060020181905550600061118d8561194b565b905085600460008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550857f0651cc1852188054ab1dc1f39e0a543b236620b2d303cdcf5ca15adc97c272be868686866040516112099493929190613a95565b60405180910390a2505050505050565b7fdf8b4c520ffe197c5343c6f5aec59570151ef9a492f2c624fd45ddde6135ec4281565b600360205280600052604060002060009150905080600001805461126090613629565b80601f016020809104026020016040519081016040528092919081815260200182805461128c90613629565b80156112d95780601f106112ae576101008083540402835291602001916112d9565b820191906000526020600020905b8154815290600101906020018083116112bc57829003601f168201915b5050505050908060010154908060020154905083565b6005602052816000526040600020818154811061130b57600080fd5b90600052602060002090600202016000915091505080600001805461132f90613629565b80601f016020809104026020016040519081016040528092919081815260200182805461135b90613629565b80156113a85780601f1061137d576101008083540402835291602001916113a8565b820191906000526020600020905b81548152906001019060200180831161138b57829003601f168201915b5050505050908060010154905082565b600080600084815260200190815260200160002060000160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff16905092915050565b600160149054906101000a900460ff1681565b6000808290508073ffffffffffffffffffffffffffffffffffffffff1663d4818fca6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611486573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114aa9190613e7c565b8551146114ec576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016114e390614062565b60405180910390fd5b60005b855181101561160957600086828151811061150d5761150c613cf0565b5b60200260200101519050600061153961152588611f62565b836040015184600001518560200151611f9d565b90508373ffffffffffffffffffffffffffffffffffffffff1663a25e49a4826040518263ffffffff1660e01b81526004016115749190613596565b602060405180830381865afa158015611591573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115b59190613b9f565b6115f4576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016115eb906140f4565b60405180910390fd5b5050808061160190613f16565b9150506114ef565b5060019150509392505050565b6000801b81565b6060600560008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020805480602002602001604051908101604052809291908181526020016000905b8282101561174c57838290600052602060002090600202016040518060400160405290816000820180546116b190613629565b80601f01602080910402602001604051908101604052809291908181526020018280546116dd90613629565b801561172a5780601f106116ff5761010080835404028352916020019161172a565b820191906000526020600020905b81548152906001019060200180831161170d57829003601f168201915b505050505081526020016001820154815250508152602001906001019061167e565b505050509050919050565b600061180060036000848152602001908152602001600020600001805461177d90613629565b80601f01602080910402602001604051908101604052809291908181526020018280546117a990613629565b80156117f65780601f106117cb576101008083540402835291602001916117f6565b820191906000526020600020905b8154815290600101906020018083116117d957829003601f168201915b505050505061194b565b9050919050565b6000600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16638e8dfd16600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16632c0b8bf76040518163ffffffff1660e01b8152600401602060405180830381865afa1580156118b4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118d89190614129565b600160149054906101000a900460ff166040518363ffffffff1660e01b8152600401611905929190614156565b602060405180830381865afa158015611922573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119469190614194565b905090565b6000806119656001604085611fc89092919063ffffffff16565b8051906020012090508060001c915050919050565b61198382610990565b61198c81611b6b565b6119968383611c67565b505050565b60046020528060005260406000206000915090505481565b60606003600083815260200190815260200160002060000180546119d690613629565b80601f0160208091040260200160405190810160405280929190818152602001828054611a0290613629565b8015611a4f5780601f10611a2457610100808354040283529160200191611a4f565b820191906000526020600020905b815481529060010190602001808311611a3257829003601f168201915b50505050509050919050565b7fdf8b4c520ffe197c5343c6f5aec59570151ef9a492f2c624fd45ddde6135ec42611a8581611b6b565b81600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055507f2760073c7cd8cac531d7f643becbfbb74d8b8156443eacf879622532dbbb3cd582604051611af59190613596565b60405180910390a15050565b60007f01ffc9a7000000000000000000000000000000000000000000000000000000007bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916827bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916149050919050565b611b7c81611b77611c5f565b6120e6565b50565b611b8982826113b8565b611c5b57600160008084815260200190815260200160002060000160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff021916908315150217905550611c00611c5f565b73ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff16837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45b5050565b600033905090565b611c7182826113b8565b15611d4457600080600084815260200190815260200160002060000160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff021916908315150217905550611ce9611c5f565b73ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff16837ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b60405160405180910390a45b5050565b60606000600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16638e8dfd16600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166385cb11916040518163ffffffff1660e01b8152600401602060405180830381865afa158015611df7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e1b9190614129565b600160149054906101000a900460ff166040518363ffffffff1660e01b8152600401611e48929190614156565b602060405180830381865afa158015611e65573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e899190614194565b90506000808273ffffffffffffffffffffffffffffffffffffffff1663a32c2b998888886040518463ffffffff1660e01b8152600401611ecb939291906141c1565b600060405180830381865afa158015611ee8573d6000803e3d6000fd5b505050506040513d6000823e3d601f19601f82011682018060405250810190611f11919061426f565b9150915081611f55576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611f4c9061433d565b60405180910390fd5b8093505050509392505050565b6000611f6e825161216b565b82604051602001611f809291906143f0565b604051602081830303815290604052805190602001209050919050565b6000806000611fae87878787612239565b91509150611fbb8161231b565b8192505050949350505050565b606081601f83611fd89190613e33565b1015612019576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016120109061446b565b60405180910390fd5b81836120259190613e33565b84511015612068576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161205f906144d7565b60405180910390fd5b606082156000811461208957604051915060008252602082016040526120da565b6040519150601f8416801560200281840101858101878315602002848b0101015b818310156120c757805183526020830192506020810190506120aa565b50868552601f19601f8301166040525050505b50809150509392505050565b6120f082826113b8565b612167576120fd81612481565b61210b8360001c60206124ae565b60405160200161211c92919061458f565b6040516020818303038152906040526040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161215e9190614602565b60405180910390fd5b5050565b60606000600161217a846126ea565b01905060008167ffffffffffffffff811115612199576121986129ae565b5b6040519080825280601f01601f1916602001820160405280156121cb5781602001600182028036833780820191505090505b509050600082602001820190505b60011561222e578080600190039150507f3031323334353637383961626364656600000000000000000000000000000000600a86061a8153600a858161222257612221614624565b5b049450600085036121d9575b819350505050919050565b6000807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08360001c1115612274576000600391509150612312565b6000600187878787604051600081526020016040526040516122999493929190614662565b6020604051602081039080840390855afa1580156122bb573d6000803e3d6000fd5b505050602060405103519050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff160361230957600060019250925050612312565b80600092509250505b94509492505050565b6000600481111561232f5761232e6131bc565b5b816004811115612342576123416131bc565b5b031561247e576001600481111561235c5761235b6131bc565b5b81600481111561236f5761236e6131bc565b5b036123af576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016123a6906146f3565b60405180910390fd5b600260048111156123c3576123c26131bc565b5b8160048111156123d6576123d56131bc565b5b03612416576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161240d9061475f565b60405180910390fd5b6003600481111561242a576124296131bc565b5b81600481111561243d5761243c6131bc565b5b0361247d576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401612474906147f1565b60405180910390fd5b5b50565b60606124a78273ffffffffffffffffffffffffffffffffffffffff16601460ff166124ae565b9050919050565b6060600060028360026124c19190614811565b6124cb9190613e33565b67ffffffffffffffff8111156124e4576124e36129ae565b5b6040519080825280601f01601f1916602001820160405280156125165781602001600182028036833780820191505090505b5090507f30000000000000000000000000000000000000000000000000000000000000008160008151811061254e5761254d613cf0565b5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a9053507f7800000000000000000000000000000000000000000000000000000000000000816001815181106125b2576125b1613cf0565b5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a905350600060018460026125f29190614811565b6125fc9190613e33565b90505b600181111561269c577f3031323334353637383961626364656600000000000000000000000000000000600f86166010811061263e5761263d613cf0565b5b1a60f81b82828151811061265557612654613cf0565b5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a905350600485901c94508061269590614853565b90506125ff565b50600084146126e0576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016126d7906148c8565b60405180910390fd5b8091505092915050565b600080600090507a184f03e93ff9f4daa797ed6e38ed64bf6a1f0100000000000000008310612748577a184f03e93ff9f4daa797ed6e38ed64bf6a1f010000000000000000838161273e5761273d614624565b5b0492506040810190505b6d04ee2d6d415b85acef81000000008310612785576d04ee2d6d415b85acef8100000000838161277b5761277a614624565b5b0492506020810190505b662386f26fc1000083106127b457662386f26fc1000083816127aa576127a9614624565b5b0492506010810190505b6305f5e10083106127dd576305f5e10083816127d3576127d2614624565b5b0492506008810190505b61271083106128025761271083816127f8576127f7614624565b5b0492506004810190505b60648310612825576064838161281b5761281a614624565b5b0492506002810190505b600a8310612834576001810190505b80915050919050565b60405180606001604052806060815260200160008152602001600080191681525090565b6000604051905090565b600080fd5b600080fd5b6000819050919050565b61288881612875565b811461289357600080fd5b50565b6000813590506128a58161287f565b92915050565b6000602082840312156128c1576128c061286b565b5b60006128cf84828501612896565b91505092915050565b60008115159050919050565b6128ed816128d8565b82525050565b600060208201905061290860008301846128e4565b92915050565b60007fffffffff0000000000000000000000000000000000000000000000000000000082169050919050565b6129438161290e565b811461294e57600080fd5b50565b6000813590506129608161293a565b92915050565b60006020828403121561297c5761297b61286b565b5b600061298a84828501612951565b91505092915050565b600080fd5b600080fd5b6000601f19601f8301169050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b6129e68261299d565b810181811067ffffffffffffffff82111715612a0557612a046129ae565b5b80604052505050565b6000612a18612861565b9050612a2482826129dd565b919050565b600067ffffffffffffffff821115612a4457612a436129ae565b5b612a4d8261299d565b9050602081019050919050565b82818337600083830152505050565b6000612a7c612a7784612a29565b612a0e565b905082815260208101848484011115612a9857612a97612998565b5b612aa3848285612a5a565b509392505050565b600082601f830112612ac057612abf612993565b5b8135612ad0848260208601612a69565b91505092915050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b6000612b0482612ad9565b9050919050565b612b1481612af9565b8114612b1f57600080fd5b50565b600081359050612b3181612b0b565b92915050565b6000819050919050565b612b4a81612b37565b8114612b5557600080fd5b50565b600081359050612b6781612b41565b92915050565b600080600080600060a08688031215612b8957612b8861286b565b5b6000612b9788828901612896565b955050602086013567ffffffffffffffff811115612bb857612bb7612870565b5b612bc488828901612aab565b9450506040612bd588828901612b22565b9350506060612be688828901612896565b9250506080612bf788828901612b58565b9150509295509295909350565b60008060408385031215612c1b57612c1a61286b565b5b6000612c2985828601612b22565b925050602083013567ffffffffffffffff811115612c4a57612c49612870565b5b612c5685828601612aab565b9150509250929050565b612c6981612875565b82525050565b6000602082019050612c846000830184612c60565b92915050565b600060208284031215612ca057612c9f61286b565b5b6000612cae84828501612b58565b91505092915050565b612cc081612b37565b82525050565b6000602082019050612cdb6000830184612cb7565b92915050565b600081519050919050565b600082825260208201905092915050565b60005b83811015612d1b578082015181840152602081019050612d00565b60008484015250505050565b6000612d3282612ce1565b612d3c8185612cec565b9350612d4c818560208601612cfd565b612d558161299d565b840191505092915050565b612d6981612875565b82525050565b612d7881612b37565b82525050565b60006060830160008301518482036000860152612d9b8282612d27565b9150506020830151612db06020860182612d60565b506040830151612dc36040860182612d6f565b508091505092915050565b60006020820190508181036000830152612de88184612d7e565b905092915050565b60008060408385031215612e0757612e0661286b565b5b6000612e1585828601612b58565b9250506020612e2685828601612b22565b9150509250929050565b60008060408385031215612e4757612e4661286b565b5b6000612e5585828601612b22565b9250506020612e6685828601612b58565b9150509250929050565b600082825260208201905092915050565b6000612e8c82612ce1565b612e968185612e70565b9350612ea6818560208601612cfd565b612eaf8161299d565b840191505092915050565b60006020820190508181036000830152612ed48184612e81565b905092915050565b600067ffffffffffffffff821115612ef757612ef66129ae565b5b602082029050602081019050919050565b600080fd5b600080fd5b600080fd5b600060408284031215612f2d57612f2c612f0d565b5b612f376040612a0e565b9050600082013567ffffffffffffffff811115612f5757612f56612f12565b5b612f6384828501612aab565b6000830152506020612f7784828501612896565b60208301525092915050565b6000612f96612f9184612edc565b612a0e565b90508083825260208201905060208402830185811115612fb957612fb8612f08565b5b835b8181101561300057803567ffffffffffffffff811115612fde57612fdd612993565b5b808601612feb8982612f17565b85526020850194505050602081019050612fbb565b5050509392505050565b600082601f83011261301f5761301e612993565b5b813561302f848260208601612f83565b91505092915050565b6000806040838503121561304f5761304e61286b565b5b600061305d85828601612b22565b925050602083013567ffffffffffffffff81111561307e5761307d612870565b5b61308a8582860161300a565b9150509250929050565b6000819050919050565b60006130b96130b46130af84612ad9565b613094565b612ad9565b9050919050565b60006130cb8261309e565b9050919050565b60006130dd826130c0565b9050919050565b6130ed816130d2565b82525050565b600060208201905061310860008301846130e4565b92915050565b600060608201905081810360008301526131288186612e81565b90506131376020830185612c60565b6131446040830184612cb7565b949350505050565b600080604083850312156131635761316261286b565b5b600061317185828601612b22565b925050602061318285828601612896565b9150509250929050565b600060408201905081810360008301526131a68185612e81565b90506131b56020830184612c60565b9392505050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602160045260246000fd5b600381106131fc576131fb6131bc565b5b50565b600081905061320d826131eb565b919050565b600061321d826131ff565b9050919050565b61322d81613212565b82525050565b60006020820190506132486000830184613224565b92915050565b600067ffffffffffffffff821115613269576132686129ae565b5b602082029050602081019050919050565b600060ff82169050919050565b6132908161327a565b811461329b57600080fd5b50565b6000813590506132ad81613287565b92915050565b6000606082840312156132c9576132c8612f0d565b5b6132d36060612a0e565b905060006132e384828501612b58565b60008301525060206132f784828501612b58565b602083015250604061330b8482850161329e565b60408301525092915050565b600061332a6133258461324e565b612a0e565b9050808382526020820190506060840283018581111561334d5761334c612f08565b5b835b81811015613376578061336288826132b3565b84526020840193505060608101905061334f565b5050509392505050565b600082601f83011261339557613394612993565b5b81356133a5848260208601613317565b91505092915050565b6000806000606084860312156133c7576133c661286b565b5b600084013567ffffffffffffffff8111156133e5576133e4612870565b5b6133f186828701613380565b935050602084013567ffffffffffffffff81111561341257613411612870565b5b61341e86828701612aab565b925050604061342f86828701612b22565b9150509250925092565b60006020828403121561344f5761344e61286b565b5b600061345d84828501612b22565b91505092915050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b600060408301600083015184820360008601526134af8282612d27565b91505060208301516134c46020860182612d60565b508091505092915050565b60006134db8383613492565b905092915050565b6000602082019050919050565b60006134fb82613466565b6135058185613471565b93508360208202850161351785613482565b8060005b85811015613553578484038952815161353485826134cf565b945061353f836134e3565b925060208a0199505060018101905061351b565b50829750879550505050505092915050565b6000602082019050818103600083015261357f81846134f0565b905092915050565b61359081612af9565b82525050565b60006020820190506135ab6000830184613587565b92915050565b6000602082840312156135c7576135c661286b565b5b600082013567ffffffffffffffff8111156135e5576135e4612870565b5b6135f184828501612aab565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b6000600282049050600182168061364157607f821691505b602082108103613654576136536135fa565b5b50919050565b600082825260208201905092915050565b7f736574526f7574696e6744617461206d7573742062652063616c6c656420627960008201527f20504b504e465420636f6e747261637400000000000000000000000000000000602082015250565b60006136c760308361365a565b91506136d28261366b565b604082019050919050565b600060208201905081810360008301526136f6816136ba565b9050919050565b7f746f6b656e496420646f6573206e6f74206d617463682068617368656420707560008201527f626b657900000000000000000000000000000000000000000000000000000000602082015250565b600061375960248361365a565b9150613764826136fd565b604082019050919050565b600060208201905081810360008301526137888161374c565b9050919050565b7f5075626b6579526f757465723a207075626b657920616c72656164792068617360008201527f20726f7574696e67206461746100000000000000000000000000000000000000602082015250565b60006137eb602d8361365a565b91506137f68261378f565b604082019050919050565b6000602082019050818103600083015261381a816137de565b9050919050565b60008190508160005260206000209050919050565b60006020601f8301049050919050565b600082821b905092915050565b6000600883026138837fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff82613846565b61388d8683613846565b95508019841693508086168417925050509392505050565b60006138c06138bb6138b684612875565b613094565b612875565b9050919050565b6000819050919050565b6138da836138a5565b6138ee6138e6826138c7565b848454613853565b825550505050565b600090565b6139036138f6565b61390e8184846138d1565b505050565b5b81811015613932576139276000826138fb565b600181019050613914565b5050565b601f8211156139775761394881613821565b61395184613836565b81016020851015613960578190505b61397461396c85613836565b830182613913565b50505b505050565b600082821c905092915050565b600061399a6000198460080261397c565b1980831691505092915050565b60006139b38383613989565b9150826002028217905092915050565b6139cc82612ce1565b67ffffffffffffffff8111156139e5576139e46129ae565b5b6139ef8254613629565b6139fa828285613936565b600060209050601f831160018114613a2d5760008415613a1b578287015190505b613a2585826139a7565b865550613a8d565b601f198416613a3b86613821565b60005b82811015613a6357848901518255600182019150602085019450602081019050613a3e565b86831015613a805784890151613a7c601f891682613989565b8355505b6001600288020188555050505b505050505050565b60006080820190508181036000830152613aaf8187612e81565b9050613abe6020830186613587565b613acb6040830185612c60565b613ad86060830184612cb7565b95945050505050565b7f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560008201527f20726f6c657320666f722073656c660000000000000000000000000000000000602082015250565b6000613b3d602f8361365a565b9150613b4882613ae1565b604082019050919050565b60006020820190508181036000830152613b6c81613b30565b9050919050565b613b7c816128d8565b8114613b8757600080fd5b50565b600081519050613b9981613b73565b92915050565b600060208284031215613bb557613bb461286b565b5b6000613bc384828501613b8a565b91505092915050565b7f5075626b6579526f757465723a2074786e2073656e646572206973206e6f742060008201527f6163746976652076616c696461746f7200000000000000000000000000000000602082015250565b6000613c2860308361365a565b9150613c3382613bcc565b604082019050919050565b60006020820190508181036000830152613c5781613c1b565b9050919050565b7f5075626b6579526f757465723a20726f6f74206b65797320616c72656164792060008201527f73657420666f722074686973207374616b696e6720636f6e7472616374000000602082015250565b6000613cba603d8361365a565b9150613cc582613c5e565b604082019050919050565b60006020820190508181036000830152613ce981613cad565b9050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600081905092915050565b6000613d3582612ce1565b613d3f8185613d1f565b9350613d4f818560208601612cfd565b80840191505092915050565b6000613d678284613d2a565b915081905092915050565b7f5075626b6579526f757465723a2076616c696461746f722068617320616c726560008201527f61647920766f74656420666f72207468697320726f6f74206b65790000000000602082015250565b6000613dce603b8361365a565b9150613dd982613d72565b604082019050919050565b60006020820190508181036000830152613dfd81613dc1565b9050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b6000613e3e82612875565b9150613e4983612875565b9250828201905080821115613e6157613e60613e04565b5b92915050565b600081519050613e768161287f565b92915050565b600060208284031215613e9257613e9161286b565b5b6000613ea084828501613e67565b91505092915050565b60006040830160008301518482036000860152613ec68282612d27565b9150506020830151613edb6020860182612d60565b508091505092915050565b6000604082019050613efb6000830185613587565b8181036020830152613f0d8184613ea9565b90509392505050565b6000613f2182612875565b91507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8203613f5357613f52613e04565b5b600182019050919050565b7f5075626b6579526f757465723a206d75737420686176652061646d696e20726f60008201527f6c65000000000000000000000000000000000000000000000000000000000000602082015250565b6000613fba60228361365a565b9150613fc582613f5e565b604082019050919050565b60006020820190508181036000830152613fe981613fad565b9050919050565b7f5075626b6579526f757465723a20696e636f7272656374206e756d626572206f60008201527f66207369676e617475726573206f6e206120676976656e20726f6f74206b6579602082015250565b600061404c60408361365a565b915061405782613ff0565b604082019050919050565b6000602082019050818103600083015261407b8161403f565b9050919050565b7f5075626b6579526f757465723a207369676e6572206973206e6f74206163746960008201527f76652076616c696461746f720000000000000000000000000000000000000000602082015250565b60006140de602c8361365a565b91506140e982614082565b604082019050919050565b6000602082019050818103600083015261410d816140d1565b9050919050565b60008151905061412381612b41565b92915050565b60006020828403121561413f5761413e61286b565b5b600061414d84828501614114565b91505092915050565b600060408201905061416b6000830185612cb7565b6141786020830184613224565b9392505050565b60008151905061418e81612b0b565b92915050565b6000602082840312156141aa576141a961286b565b5b60006141b88482850161417f565b91505092915050565b60006060820190506141d66000830186612cb7565b81810360208301526141e881856134f0565b90506141f76040830184612c60565b949350505050565b600061421261420d84612a29565b612a0e565b90508281526020810184848401111561422e5761422d612998565b5b614239848285612cfd565b509392505050565b600082601f83011261425657614255612993565b5b81516142668482602086016141ff565b91505092915050565b600080604083850312156142865761428561286b565b5b600061429485828601613b8a565b925050602083015167ffffffffffffffff8111156142b5576142b4612870565b5b6142c185828601614241565b9150509250929050565b7f5075626b6579526f757465723a204661696c6564207075626c6963206b65792060008201527f63616c63756c6174696f6e000000000000000000000000000000000000000000602082015250565b6000614327602b8361365a565b9150614332826142cb565b604082019050919050565b600060208201905081810360008301526143568161431a565b9050919050565b600081905092915050565b7f19457468657265756d205369676e6564204d6573736167653a0a000000000000600082015250565b600061439e601a8361435d565b91506143a982614368565b601a82019050919050565b600081519050919050565b60006143ca826143b4565b6143d4818561435d565b93506143e4818560208601612cfd565b80840191505092915050565b60006143fb82614391565b915061440782856143bf565b91506144138284613d2a565b91508190509392505050565b7f736c6963655f6f766572666c6f77000000000000000000000000000000000000600082015250565b6000614455600e8361365a565b91506144608261441f565b602082019050919050565b6000602082019050818103600083015261448481614448565b9050919050565b7f736c6963655f6f75744f66426f756e6473000000000000000000000000000000600082015250565b60006144c160118361365a565b91506144cc8261448b565b602082019050919050565b600060208201905081810360008301526144f0816144b4565b9050919050565b7f416363657373436f6e74726f6c3a206163636f756e7420000000000000000000600082015250565b600061452d60178361435d565b9150614538826144f7565b601782019050919050565b7f206973206d697373696e6720726f6c6520000000000000000000000000000000600082015250565b600061457960118361435d565b915061458482614543565b601182019050919050565b600061459a82614520565b91506145a682856143bf565b91506145b18261456c565b91506145bd82846143bf565b91508190509392505050565b60006145d4826143b4565b6145de818561365a565b93506145ee818560208601612cfd565b6145f78161299d565b840191505092915050565b6000602082019050818103600083015261461c81846145c9565b905092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b61465c8161327a565b82525050565b60006080820190506146776000830187612cb7565b6146846020830186614653565b6146916040830185612cb7565b61469e6060830184612cb7565b95945050505050565b7f45434453413a20696e76616c6964207369676e61747572650000000000000000600082015250565b60006146dd60188361365a565b91506146e8826146a7565b602082019050919050565b6000602082019050818103600083015261470c816146d0565b9050919050565b7f45434453413a20696e76616c6964207369676e6174757265206c656e67746800600082015250565b6000614749601f8361365a565b915061475482614713565b602082019050919050565b600060208201905081810360008301526147788161473c565b9050919050565b7f45434453413a20696e76616c6964207369676e6174757265202773272076616c60008201527f7565000000000000000000000000000000000000000000000000000000000000602082015250565b60006147db60228361365a565b91506147e68261477f565b604082019050919050565b6000602082019050818103600083015261480a816147ce565b9050919050565b600061481c82612875565b915061482783612875565b925082820261483581612875565b9150828204841483151761484c5761484b613e04565b5b5092915050565b600061485e82612875565b91506000820361487157614870613e04565b5b600182039050919050565b7f537472696e67733a20686578206c656e67746820696e73756666696369656e74600082015250565b60006148b260208361365a565b91506148bd8261487c565b602082019050919050565b600060208201905081810360008301526148e1816148a5565b905091905056fea2646970667358221220d1021b8a42e5b231ff40dfab015d0419b12e8e59c84f0919fa4dc03eb12186a464736f6c63430008110033