Sonic Blaze Testnet

Contract

0x4fB8b44149750e247A5Cde33DBc0aDC0FF38720a

Overview

S Balance

Sonic Blaze LogoSonic Blaze LogoSonic Blaze Logo0 S

Token Holdings

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To
Add Pve Deck164084062025-01-29 13:18:409 days ago1738156720IN
0x4fB8b441...0FF38720a
0 S0.000184141.1
Remove Pve Deck164083252025-01-29 13:18:129 days ago1738156692IN
0x4fB8b441...0FF38720a
0 S0.000068051.1
Add Pve Deck164077562025-01-29 13:14:549 days ago1738156494IN
0x4fB8b441...0FF38720a
0 S0.000254921.1
Add Admin164075022025-01-29 13:13:209 days ago1738156400IN
0x4fB8b441...0FF38720a
0 S0.000052671.1
Add Admin164074722025-01-29 13:13:099 days ago1738156389IN
0x4fB8b441...0FF38720a
0 S0.000052661.1
Add Admin159702492025-01-27 18:21:2410 days ago1738002084IN
0x4fB8b441...0FF38720a
0 S0.000052671.1

Latest 9 internal transactions

Parent Transaction Hash Block From To
164084062025-01-29 13:18:409 days ago1738156720
0x4fB8b441...0FF38720a
0 S
164084062025-01-29 13:18:409 days ago1738156720
0x4fB8b441...0FF38720a
0 S
164083252025-01-29 13:18:129 days ago1738156692
0x4fB8b441...0FF38720a
0 S
164077562025-01-29 13:14:549 days ago1738156494
0x4fB8b441...0FF38720a
0 S
164077562025-01-29 13:14:549 days ago1738156494
0x4fB8b441...0FF38720a
0 S
159702632025-01-27 18:21:2910 days ago1738002089
0x4fB8b441...0FF38720a
0 S
159702632025-01-27 18:21:2910 days ago1738002089
0x4fB8b441...0FF38720a
0 S
159702632025-01-27 18:21:2910 days ago1738002089
0x4fB8b441...0FF38720a
0 S
159702632025-01-27 18:21:2910 days ago1738002089
0x4fB8b441...0FF38720a
0 S
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
PepemonMatchmakerPve

Compiler Version
v0.8.6+commit.11564f7e

Optimization Enabled:
Yes with 200 runs

Other Settings:
default evmVersion

Contract Source Code (Solidity Standard Json-Input format)

File 1 of 34 : PepemonMatchmakerPve.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "./PepemonMatchmaker.sol";

contract PepemonMatchmakerPve is PepemonMatchmaker {
    constructor(uint256 defaultRanking, address _configAddress) PepemonMatchmaker(defaultRanking, _configAddress) {
        setPveMode(true);
    }
}

File 2 of 34 : LinkTokenInterface.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface LinkTokenInterface {

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

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

  function balanceOf(
    address owner
  )
    external
    view
    returns (
      uint256 balance
    );

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

  function decreaseApproval(
    address spender,
    uint256 addedValue
  )
    external
    returns (
      bool success
    );

  function increaseApproval(
    address spender,
    uint256 subtractedValue
  ) external;

  function name()
    external
    view
    returns (
      string memory tokenName
    );

  function symbol()
    external
    view
    returns (
      string memory tokenSymbol
    );

  function totalSupply()
    external
    view
    returns (
      uint256 totalTokensIssued
    );

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

  function transferAndCall(
    address to,
    uint256 value,
    bytes calldata data
  )
    external
    returns (
      bool success
    );

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

}

File 3 of 34 : VRFConsumerBase.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "./interfaces/LinkTokenInterface.sol";

import "./VRFRequestIDBase.sol";

/** ****************************************************************************
 * @notice Interface for contracts using VRF randomness
 * *****************************************************************************
 * @dev PURPOSE
 *
 * @dev Reggie the Random Oracle (not his real job) wants to provide randomness
 * @dev to Vera the verifier in such a way that Vera can be sure he's not
 * @dev making his output up to suit himself. Reggie provides Vera a public key
 * @dev to which he knows the secret key. Each time Vera provides a seed to
 * @dev Reggie, he gives back a value which is computed completely
 * @dev deterministically from the seed and the secret key.
 *
 * @dev Reggie provides a proof by which Vera can verify that the output was
 * @dev correctly computed once Reggie tells it to her, but without that proof,
 * @dev the output is indistinguishable to her from a uniform random sample
 * @dev from the output space.
 *
 * @dev The purpose of this contract is to make it easy for unrelated contracts
 * @dev to talk to Vera the verifier about the work Reggie is doing, to provide
 * @dev simple access to a verifiable source of randomness.
 * *****************************************************************************
 * @dev USAGE
 *
 * @dev Calling contracts must inherit from VRFConsumerBase, and can
 * @dev initialize VRFConsumerBase's attributes in their constructor as
 * @dev shown:
 *
 * @dev   contract VRFConsumer {
 * @dev     constuctor(<other arguments>, address _vrfCoordinator, address _link)
 * @dev       VRFConsumerBase(_vrfCoordinator, _link) public {
 * @dev         <initialization with other arguments goes here>
 * @dev       }
 * @dev   }
 *
 * @dev The oracle will have given you an ID for the VRF keypair they have
 * @dev committed to (let's call it keyHash), and have told you the minimum LINK
 * @dev price for VRF service. Make sure your contract has sufficient LINK, and
 * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you
 * @dev want to generate randomness from.
 *
 * @dev Once the VRFCoordinator has received and validated the oracle's response
 * @dev to your request, it will call your contract's fulfillRandomness method.
 *
 * @dev The randomness argument to fulfillRandomness is the actual random value
 * @dev generated from your seed.
 *
 * @dev The requestId argument is generated from the keyHash and the seed by
 * @dev makeRequestId(keyHash, seed). If your contract could have concurrent
 * @dev requests open, you can use the requestId to track which seed is
 * @dev associated with which randomness. See VRFRequestIDBase.sol for more
 * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind,
 * @dev if your contract could have multiple requests in flight simultaneously.)
 *
 * @dev Colliding `requestId`s are cryptographically impossible as long as seeds
 * @dev differ. (Which is critical to making unpredictable randomness! See the
 * @dev next section.)
 *
 * *****************************************************************************
 * @dev SECURITY CONSIDERATIONS
 *
 * @dev A method with the ability to call your fulfillRandomness method directly
 * @dev could spoof a VRF response with any random value, so it's critical that
 * @dev it cannot be directly called by anything other than this base contract
 * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
 *
 * @dev For your users to trust that your contract's random behavior is free
 * @dev from malicious interference, it's best if you can write it so that all
 * @dev behaviors implied by a VRF response are executed *during* your
 * @dev fulfillRandomness method. If your contract must store the response (or
 * @dev anything derived from it) and use it later, you must ensure that any
 * @dev user-significant behavior which depends on that stored value cannot be
 * @dev manipulated by a subsequent VRF request.
 *
 * @dev Similarly, both miners and the VRF oracle itself have some influence
 * @dev over the order in which VRF responses appear on the blockchain, so if
 * @dev your contract could have multiple VRF requests in flight simultaneously,
 * @dev you must ensure that the order in which the VRF responses arrive cannot
 * @dev be used to manipulate your contract's user-significant behavior.
 *
 * @dev Since the ultimate input to the VRF is mixed with the block hash of the
 * @dev block in which the request is made, user-provided seeds have no impact
 * @dev on its economic security properties. They are only included for API
 * @dev compatability with previous versions of this contract.
 *
 * @dev Since the block hash of the block which contains the requestRandomness
 * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
 * @dev miner could, in principle, fork the blockchain to evict the block
 * @dev containing the request, forcing the request to be included in a
 * @dev different block with a different hash, and therefore a different input
 * @dev to the VRF. However, such an attack would incur a substantial economic
 * @dev cost. This cost scales with the number of blocks the VRF oracle waits
 * @dev until it calls responds to a request.
 */
abstract contract VRFConsumerBase is VRFRequestIDBase {

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

  /**
   * @dev In order to keep backwards compatibility we have kept the user
   * seed field around. We remove the use of it because given that the blockhash
   * enters later, it overrides whatever randomness the used seed provides.
   * Given that it adds no security, and can easily lead to misunderstandings,
   * we have removed it from usage and can now provide a simpler API.
   */
  uint256 constant private USER_SEED_PLACEHOLDER = 0;

  /**
   * @notice requestRandomness initiates a request for VRF output given _seed
   *
   * @dev The fulfillRandomness method receives the output, once it's provided
   * @dev by the Oracle, and verified by the vrfCoordinator.
   *
   * @dev The _keyHash must already be registered with the VRFCoordinator, and
   * @dev the _fee must exceed the fee specified during registration of the
   * @dev _keyHash.
   *
   * @dev The _seed parameter is vestigial, and is kept only for API
   * @dev compatibility with older versions. It can't *hurt* to mix in some of
   * @dev your own randomness, here, but it's not necessary because the VRF
   * @dev oracle will mix the hash of the block containing your request into the
   * @dev VRF seed it ultimately uses.
   *
   * @param _keyHash ID of public key against which randomness is generated
   * @param _fee The amount of LINK to send with the request
   *
   * @return requestId unique ID for this request
   *
   * @dev The returned requestId can be used to distinguish responses to
   * @dev concurrent requests. It is passed as the first argument to
   * @dev fulfillRandomness.
   */
  function requestRandomness(
    bytes32 _keyHash,
    uint256 _fee
  )
    internal
    returns (
      bytes32 requestId
    )
  {
    LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER));
    // This is the seed passed to VRFCoordinator. The oracle will mix this with
    // the hash of the block containing this request to obtain the seed/input
    // which is finally passed to the VRF cryptographic machinery.
    uint256 vRFSeed  = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]);
    // nonces[_keyHash] must stay in sync with
    // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above
    // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest).
    // This provides protection against the user repeating their input seed,
    // which would result in a predictable/duplicate output, if multiple such
    // requests appeared in the same block.
    nonces[_keyHash] = nonces[_keyHash] + 1;
    return makeRequestId(_keyHash, vRFSeed);
  }

  LinkTokenInterface immutable internal LINK;
  address immutable private vrfCoordinator;

  // Nonces for each VRF key from which randomness has been requested.
  //
  // Must stay in sync with VRFCoordinator[_keyHash][this]
  mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces;

  /**
   * @param _vrfCoordinator address of VRFCoordinator contract
   * @param _link address of LINK token contract
   *
   * @dev https://docs.chain.link/docs/link-token-contracts
   */
  constructor(
    address _vrfCoordinator,
    address _link
  ) {
    vrfCoordinator = _vrfCoordinator;
    LINK = LinkTokenInterface(_link);
  }

  // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
  // proof. rawFulfillRandomness then calls fulfillRandomness, after validating
  // the origin of the call
  function rawFulfillRandomness(
    bytes32 requestId,
    uint256 randomness
  )
    external
  {
    require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill");
    fulfillRandomness(requestId, randomness);
  }
}

File 4 of 34 : VRFRequestIDBase.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract VRFRequestIDBase {

  /**
   * @notice returns the seed which is actually input to the VRF coordinator
   *
   * @dev To prevent repetition of VRF output due to repetition of the
   * @dev user-supplied seed, that seed is combined in a hash with the
   * @dev user-specific nonce, and the address of the consuming contract. The
   * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in
   * @dev the final seed, but the nonce does protect against repetition in
   * @dev requests which are included in a single block.
   *
   * @param _userSeed VRF seed input provided by user
   * @param _requester Address of the requesting contract
   * @param _nonce User-specific nonce at the time of the request
   */
  function makeVRFInputSeed(
    bytes32 _keyHash,
    uint256 _userSeed,
    address _requester,
    uint256 _nonce
  )
    internal
    pure
    returns (
      uint256
    )
  {
    return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce)));
  }

  /**
   * @notice Returns the id for this request
   * @param _keyHash The serviceAgreement ID to be used for this request
   * @param _vRFInputSeed The seed to be passed directly to the VRF
   * @return The id for this request
   *
   * @dev Note that _vRFInputSeed is not the seed passed by the consuming
   * @dev contract, but the one generated by makeVRFInputSeed
   */
  function makeRequestId(
    bytes32 _keyHash,
    uint256 _vRFInputSeed
  )
    internal
    pure
    returns (
      bytes32
    )
  {
    return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed));
  }
}

File 5 of 34 : IERC1155Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)

pragma solidity ^0.8.0;

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

/**
 * @dev _Available since v3.1._
 */
interface IERC1155Receiver is IERC165 {
    /**
     * @dev Handles the receipt of a single ERC1155 token type. This function is
     * called at the end of a `safeTransferFrom` after the balance has been updated.
     *
     * NOTE: To accept the transfer, this must return
     * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
     * (i.e. 0xf23a6e61, or its own function selector).
     *
     * @param operator The address which initiated the transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param id The ID of the token being transferred
     * @param value The amount of tokens being transferred
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
     */
    function onERC1155Received(
        address operator,
        address from,
        uint256 id,
        uint256 value,
        bytes calldata data
    ) external returns (bytes4);

    /**
     * @dev Handles the receipt of a multiple ERC1155 token types. This function
     * is called at the end of a `safeBatchTransferFrom` after the balances have
     * been updated.
     *
     * NOTE: To accept the transfer(s), this must return
     * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
     * (i.e. 0xbc197c81, or its own function selector).
     *
     * @param operator The address which initiated the batch transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param ids An array containing ids of each token being transferred (order and length must match values array)
     * @param values An array containing amounts of each token being transferred (order and length must match ids array)
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
     */
    function onERC1155BatchReceived(
        address operator,
        address from,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata data
    ) external returns (bytes4);
}

File 6 of 34 : ERC1155Holder.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/utils/ERC1155Holder.sol)

pragma solidity ^0.8.0;

import "./ERC1155Receiver.sol";

/**
 * Simple implementation of `ERC1155Receiver` that will allow a contract to hold ERC1155 tokens.
 *
 * IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be
 * stuck.
 *
 * @dev _Available since v3.1._
 */
contract ERC1155Holder is ERC1155Receiver {
    function onERC1155Received(
        address,
        address,
        uint256,
        uint256,
        bytes memory
    ) public virtual override returns (bytes4) {
        return this.onERC1155Received.selector;
    }

    function onERC1155BatchReceived(
        address,
        address,
        uint256[] memory,
        uint256[] memory,
        bytes memory
    ) public virtual override returns (bytes4) {
        return this.onERC1155BatchReceived.selector;
    }
}

File 7 of 34 : ERC1155Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/utils/ERC1155Receiver.sol)

pragma solidity ^0.8.0;

import "../IERC1155Receiver.sol";
import "../../../utils/introspection/ERC165.sol";

/**
 * @dev _Available since v3.1._
 */
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
        return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
    }
}

File 8 of 34 : 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;
    }
}

File 9 of 34 : 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);
}

File 10 of 34 : 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);
}

File 11 of 34 : 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);
}

File 12 of 34 : ERC721Holder.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/utils/ERC721Holder.sol)

pragma solidity ^0.8.0;

import "../IERC721Receiver.sol";

/**
 * @dev Implementation of the {IERC721Receiver} interface.
 *
 * Accepts all token transfers.
 * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
 */
contract ERC721Holder is IERC721Receiver {
    /**
     * @dev See {IERC721Receiver-onERC721Received}.
     *
     * Always returns `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) {
        return this.onERC721Received.selector;
    }
}

File 13 of 34 : 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);
        }
    }
}

File 14 of 34 : Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (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;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

File 15 of 34 : 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;
    }
}

File 16 of 34 : 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);
}

File 17 of 34 : 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);
        }
    }
}

File 18 of 34 : SafeMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/SafeMath.sol)

pragma solidity ^0.8.0;

// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.

/**
 * @dev Wrappers over Solidity's arithmetic operations.
 *
 * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
 * now has built in overflow checking.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        return a + b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return a - b;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        return a * b;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator.
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        return a % b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {trySub}.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        unchecked {
            require(b <= a, errorMessage);
            return a - b;
        }
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a / b;
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting with custom message when dividing by zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryMod}.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a % b;
        }
    }
}

File 19 of 34 : 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);
        }
    }
}

File 20 of 34 : 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));
    }
}

File 21 of 34 : IConfigurable.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IConfigurable {
    function syncConfig() external;
}

File 22 of 34 : IPepemonCardOracle.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;

/**
This contract acts as the oracle, it contains battling information for both the Pepemon Battle and Support cards
**/
interface IPepemonCardOracle {

    enum SupportCardType {
        OFFENSE,
        STRONG_OFFENSE,
        DEFENSE,
        STRONG_DEFENSE
    }

    enum EffectTo {
        ATTACK,
        STRONG_ATTACK,
        DEFENSE,
        STRONG_DEFENSE,
        SPEED,
        INTELLIGENCE
    }

    enum EffectFor {
        ME,
        ENEMY
    }

    enum BattleCardTypes{
        FIRE,
        GRASS,
        WATER,
        LIGHTNING,
        WIND,
        POISON,
        GHOST,
        FAIRY,
        EARTH,
        UNKNOWN,
        NONE
    }

    struct BattleCardStats {
        uint256 battleCardId;
        BattleCardTypes element;
        uint16 hp; // hitpoints
        uint16 spd; // speed
        uint16 inte; // intelligence
        uint16 def; // defense
        uint16 atk; // attack
        uint16 sAtk; // special attack
        uint16 sDef; // special defense
    }

    struct SupportCardStats {
        uint256 supportCardId;
        SupportCardType supportCardType;
        EffectOne effectOne;
        EffectMany effectMany;
        // If true, duplicate copies of the card in the same turn will have no extra effect.
        bool unstackable;
        // This property is for EffectMany now.
        // If true, assume the card is already in effect
        // then the same card drawn and used within a number of turns does not extend or reset duration of the effect.
        bool unresettable;
    }

    struct EffectOne {
        // If power is 0, it is equal to the total of all normal offense/defense cards in the current turn.
        
        //basePower = power if req not met
        int16 basePower;

        //triggeredPower = power if req met
        int16 triggeredPower;
        EffectTo effectTo;
        EffectFor effectFor;
        uint16 reqCode; //requirement code
    }

    struct EffectMany {
        int16 power;
        uint16 numTurns;
        EffectTo effectTo;
        EffectFor effectFor;
        uint16 reqCode; //requirement code
    }

    //Struct for keeping track of weakness / resistance
    struct elementWR{
        BattleCardTypes weakness;
        BattleCardTypes resistance;
    }

    // mappings
    function battleCardStats(uint256 x) view external returns (BattleCardStats memory);
    
    function supportCardStats(uint256 x) view external returns (SupportCardStats memory);
    
    function elementDecode(BattleCardTypes x) view external returns (string memory);
    
    function weakResist(BattleCardTypes x) view external returns (elementWR memory);

    // other functions
    function addBattleCard(BattleCardStats memory cardData) external;

    function updateBattleCard(BattleCardStats memory cardData) external;

    function getBattleCardById(uint256 _id) view external returns (BattleCardStats memory);

    function addSupportCard(SupportCardStats memory cardData) external;

    function updateSupportCard(SupportCardStats memory cardData) external;

    function getSupportCardById(uint256 _id) view  external returns (SupportCardStats memory);

    function getWeakResist(BattleCardTypes element) view  external returns (elementWR memory);

    function getSupportCardTypeById(uint256 _id) view external returns (SupportCardType);
}

File 23 of 34 : IPepemonFactory.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IPepemonFactory {
    function safeTransferFrom(
        address _from,
        address _to,
        uint256 _id,
        uint256 _amount,
        bytes calldata _data
    ) external;

    function setApprovalForAll(
        address _operator,
        bool _approved
    ) external;

    function balanceOf(
        address _owner, 
        uint256 _id
    ) external view returns (uint256);

    function airdrop(
        uint256 _id,
        address[] memory _addresses
    ) external;

    function batchMint(
        uint start, 
        uint end, 
        address to) 
    external;

    function batchMintList(
        uint256[] calldata ids,
        address to) 
    external;

    function addMinter(
        address account
    ) external;
}

File 24 of 34 : AdminRole.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./Roles.sol";

contract AdminRole {
  using Roles for Roles.Role;

  event AdminAdded(address indexed account);
  event AdminRemoved(address indexed account);

  Roles.Role private admins;

  constructor() {
    _addAdmin(msg.sender);
  }

  modifier onlyAdmin() {
    require(isAdmin(msg.sender));
    _;
  }

  function isAdmin(address account) public view returns (bool) {
    return admins.has(account);
  }

  function addAdmin(address account) public onlyAdmin {
    _addAdmin(account);
  }

  function renounceAdmin() public {
    _removeAdmin(msg.sender);
  }

  function _addAdmin(address account) internal {
    admins.add(account);
    emit AdminAdded(account);
  }

  function _removeAdmin(address account) internal {
    admins.remove(account);
    emit AdminRemoved(account);
  }
}

File 25 of 34 : Arrays.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

library Arrays {
    //Shuffles an array of uints with random seed
    function shuffle(uint256[] memory _elements, uint256 _seed) internal pure returns (uint256[] memory) {
        for (uint256 i = 0; i < _elements.length; i++) {
            //Pick random index to swap current element with
            uint256 n = i + _seed % (_elements.length - i);

            //swap elements
            uint256 temp = _elements[n];
            _elements[n] = _elements[i];
            _elements[i] = temp;

            //Create new pseudorandom number using seed.
            _seed = uint(keccak256(abi.encodePacked(_seed)));
        }
        return _elements;
    }

    // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/0a3f880753112b425160086c97623b1ab38bfec6/contracts/utils/Arrays.sol

    /**
     * @dev Searches an `array` sorted in ascending order and returns the first
     * index that contains a value greater or equal than `element`. If no such index
     * exists (i.e. all values in the array are strictly less than `element`), the array
     * length is returned. Time complexity O(log n).
     *
     * See C++'s https://en.cppreference.com/w/cpp/algorithm/lower_bound[lower_bound].
     */
    function lowerBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeMemoryAccess(array, mid) < element) {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            } else {
                high = mid;
            }
        }

        return low;
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(uint256[] memory arr, uint256 pos) internal pure returns (uint256 res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/0a3f880753112b425160086c97623b1ab38bfec6/contracts/utils/math/Math.sol
    
    /**
     * @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;
    }


    function isSortedAscending(uint256[] memory arr) internal pure returns (bool) {
        uint256 length = arr.length - 1;
        for (uint256 i = 0; i < length; i++) {
            uint256 current = unsafeMemoryAccess(arr, i);
            uint256 next = unsafeMemoryAccess(arr, i + 1);
            if (current > next) {
                return false;
            }
        }
        return true;
    }

    function contains(uint256[] memory arr, uint256 value) internal pure returns (bool) {
        uint256 index = lowerBoundMemory(arr, value);
        if (index == arr.length || unsafeMemoryAccess(arr, index) != value) {
            return false;
        }
        return true;
    }
}

File 26 of 34 : ChainLinkRngOracle.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
import "./AdminRole.sol";

abstract contract ChainLinkRngOracle is VRFConsumerBase, AdminRole {
    bytes32 immutable keyHash;
    bytes32 public lastRequestId;
    uint256 internal fee;

    address constant maticLink = 0xb0897686c545045aFc77CF20eC7A532E3120E0F1;
    address constant maticVrfCoordinator = 0x3d2341ADb2D31f1c5530cDC622016af293177AE0;
    bytes32 constant maticKeyHash = 0xf86195cf7690c55907b2b611ebb7343a6f649bff128701cc542f0569e2c549da;

    address constant mumbaiLink = 0x326C977E6efc84E512bB9C30f76E30c160eD06FB;
    address constant mumbaiVrfCoordinator = 0x8C7382F9D8f56b33781fE506E897a4F1e2d17255;
    bytes32 constant mumbaiKeyHash = 0x6e75b569a01ef56d18cab6a8e71e6600d6ce853834d4a5748b720d06f878b3a4;

    address constant fantomTestnetLink = 0xfaFedb041c0DD4fA2Dc0d87a6B0979Ee6FA7af5F;
    address constant fantomTestnetVrfCoordinator = 0xbd13f08b8352A3635218ab9418E340c60d6Eb418;
    bytes32 constant fantomTestnetKeyHash = 0x121a143066e0f2f08b620784af77cccb35c6242460b4a8ee251b4b416abaebd4;

    address constant fantomLink = 0x6F43FF82CCA38001B6699a8AC47A2d0E66939407;
    address constant fantomVrfCoordinator = 0xd5D517aBE5cF79B7e95eC98dB0f0277788aFF634;
    bytes32 constant fantomKeyHash = 0x5881eea62f9876043df723cf89f0c2bb6f950da25e9dfe66995c24f919c8f8ab;



    mapping(bytes32 => uint256) internal results;

    constructor() VRFConsumerBase(fantomTestnetVrfCoordinator, fantomTestnetLink) {
        keyHash = fantomTestnetKeyHash;
        fee = 1 ether / 1000;
    }

    //Get a new random number (paying link for it)
    //Only callable by admin
    function getNewRandomNumber() public onlyAdmin returns (bytes32 requestId) {
        require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
        lastRequestId = requestRandomness(keyHash, fee);
        return lastRequestId;
    }

    /**
     * Callback function used by VRF Coordinator
     */
    function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
        results[requestId] = randomness;
    }

    function fetchNumberByRequestId(bytes32 _requestId) public view returns (uint256) {
        return results[_requestId];
    }

    //Get most recent random number and use that as randomness source    
    function getRandomNumber() public view returns (uint256){
        return fetchNumberByRequestId(lastRequestId);        
    }
}

File 27 of 34 : Elo.sol
// SPDX-License-Identifier: MIT
// https://github.com/saucepoint/elo-lib/blob/main/src/Elo.sol
pragma solidity ^0.8.0;

import {FixedPointMathLib as fp} from "solmate/src/utils/FixedPointMathLib.sol";

library Elo {
    /// @notice Get the 16th root of a number, used in ELO calculations
    /// @dev Elo calculations require the 400th root (10 ^ (x / 400)), however this can be simplified to the 16th root (10 ^ ((x / 25) / 16))
    function sixteenthRoot(uint256 x) internal pure returns (uint256) {
        return fp.sqrt(fp.sqrt(fp.sqrt(fp.sqrt(x))));
    }

    /// @notice Calculates the change in ELO rating, after a given outcome.
    /// @param ratingA the ELO rating of the player A
    /// @param ratingB the ELO rating of the player B
    /// @param score the score of the player A, scaled by 100. 100 = win, 50 = draw, 0 = loss
    /// @param kFactor the k-factor or development multiplier used to calculate the change in ELO rating. 20 is the typical value
    /// @return change the change in ELO rating of player A, with 2 decimals of precision. 1501 = 15.01 ELO change
    /// @return negative the directional change of player A's ELO. Opposite sign for player B
    function ratingChange(uint256 ratingA, uint256 ratingB, uint256 score, uint256 kFactor)
        internal
        pure
        returns (uint256 change, bool negative)
    {
        uint256 _kFactor; // scaled up `kFactor` by 100
        bool _negative = ratingB < ratingA;
        uint256 ratingDiff; // absolute value difference between `ratingA` and `ratingB`

        unchecked {
            // scale up the inputs by a factor of 100
            // since our elo math is scaled up by 100 (to avoid low precision integer division)
            _kFactor = kFactor * 10_000;
            ratingDiff = _negative ? ratingA - ratingB : ratingB - ratingA;
        }

        // checks against overflow/underflow, discovered via fuzzing
        // large rating diffs leads to 10^ratingDiff being too large to fit in a uint256
        require(ratingDiff < 1126, "Rating difference too large");
        // large rating diffs when applying the scale factor leads to underflow (800 - ratingDiff)
        if (_negative) require(ratingDiff < 800, "Rating difference too large");

        // ----------------------------------------------------------------------
        // Below, we'll be running simplified versions of the following formulas:
        // expected score = 1 / (1 + 10 ^ (ratingDiff / 400))
        // elo change = kFactor * (score - expectedScore)

        uint256 n; // numerator of the power, with scaling, (numerator of `ratingDiff / 400`)
        uint256 _powered; // the value of 10 ^ numerator
        uint256 powered; // the value of 16th root of 10 ^ numerator (fully resolved 10 ^ (ratingDiff / 400))
        uint256 kExpectedScore; // the expected score with K factor distributed
        uint256 kScore; // the actual score with K factor distributed

        unchecked {
            // apply offset of 800 to scale the result by 100
            n = _negative ? 800 - ratingDiff : 800 + ratingDiff;

            // (x / 400) is the same as ((x / 25) / 16))
            _powered = fp.rpow(10, n / 25, 1); // divide by 25 to avoid reach uint256 max
            powered = sixteenthRoot(_powered); // x ^ (1 / 16) is the same as 16th root of x

            // given `change = kFactor * (score - expectedScore)` we can distribute kFactor to both terms
            kExpectedScore = _kFactor / (100 + powered); // both numerator and denominator scaled up by 100
            kScore = kFactor * score; // input score is already scaled up by 100

            // determines the sign of the ELO change
            negative = kScore < kExpectedScore;
            change = negative ? kExpectedScore - kScore : kScore - kExpectedScore;
        }
    }
}

File 28 of 34 : PepemonConfig.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "./AdminRole.sol";
import "../iface/IConfigurable.sol";

/**
 * @notice This contract stores the addresses of all and any other contracts used by Pepemon
 * @dev This contract must be added as an Admin on contracts before "syncContractConfig" can be called.
 */
contract PepemonConfig is AdminRole {
    struct ContractDisplayData {
        address contractAddress;
        string contractName;
    }

    string[] private contactsNames;
    mapping(string => address) public contractAddresses;

    /**
     * @dev Actual implementation for both setContractAddress and batchSetContractAddress, making a call to
     * a common 'internal' function uses less gas than calling a 'public' one
     */
    function setContractAddressInternal(string calldata contractName, address contractAddress, bool callSync) internal {
        require(contractAddress != address(0));

        // If its the first time adding the contract, store its name in the array
        if (contractAddresses[contractName] == address(0)) {
            contactsNames.push(contractName);
        }
        contractAddresses[contractName] = contractAddress;
        if (callSync) {
            IConfigurable(contractAddress).syncConfig();
        }
    }

    /**
     * @notice Adds or updates contracts addresses associated by contract names
     * @param contractName Name of the contract that will be stored
     * @param contractAddress Address of the contract that will be stored
     * @param callSync When true, the function "syncConfig" of the contract being stored will be invoked
     */
    function setContractAddress(
        string calldata contractName,
        address contractAddress,
        bool callSync
    ) external onlyAdmin {
        setContractAddressInternal(contractName, contractAddress, callSync);
    }

    /**
     * @notice Batch version of `setContractAddress`
     * @param contractNameList Names of the contracts that will be stored
     * @param contractAddressesList Addresses of the contracts that will be stored
     * @param callSyncList When true, the function "syncConfig" of the contracts being stored will be invoked
     */
    function batchSetContractAddress(
        string[] calldata contractNameList,
        address[] calldata contractAddressesList,
        bool[] calldata callSyncList
    ) external onlyAdmin {
        uint256 len = contractNameList.length;
        require(len == contractAddressesList.length && len == callSyncList.length, "Mismatching batch length");
        for (uint256 i = 0; i < len; ++i) {
            setContractAddressInternal(contractNameList[i], contractAddressesList[i], callSyncList[i]);
        }
    }

    /**
     * @dev Tries to call "syncConfig" from the address of the contract in `contractName`, this might fail if
     * the target contract does not have this contract (PepemonConfig) added as an Admin, or if `contractName` is not
     * associated with any contract
     */
    function syncContractConfig(string calldata contractName) external onlyAdmin {
        require(contractAddresses[contractName] != address(0));
        IConfigurable(contractAddresses[contractName]).syncConfig();
    }

    /**
     * @dev Batch version of syncContractConfig
     */
    function batchSyncContractConfig(string[] calldata contractNames) external onlyAdmin {
        uint256 len = contractNames.length;
        for (uint256 i = 0; i < len; ++i) {
            require(contractAddresses[contractNames[i]] != address(0));
            IConfigurable(contractAddresses[contractNames[i]]).syncConfig();
        }
    }

    /**
     * @dev Displays contracts names and addresses.
     */
    function getContracts() external view returns (ContractDisplayData[] memory data) {
        uint256 len = contactsNames.length;

        data = new ContractDisplayData[](len);

        for (uint256 i = 0; i < len; ++i) {
            string memory contractName = contactsNames[i];
            data[i].contractName = contractName;
            data[i].contractAddress = contractAddresses[contractName];
        }
        return data;
    }
}

File 29 of 34 : RewardPool.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface RewardPool {
    /**
     * @dev Adds a single reward into the pool.
     * @param tokenAddress Reward address
     * @param tokenId Reward id
     */
    function addReward(address tokenAddress, uint256 tokenId) external; //onlyAdmin

    /**
     * @dev Transfer an amount of a given token from the sender into the rewardPool
     * @param tokenAddress Reward address
     * @param tokenId Reward id
     * @param amount The number of items to be added to the pool.
     */
    function addRewards(address tokenAddress, uint256 tokenId, uint256 amount) external; //onlyAdmin

    /**
     * @dev Takes a random reward from rewardPool and sends it to someone.
     * @param rngSeed RNG seed of a Battle
     * @param account Address of who will receive the reward
     */
    function sendReward(uint256 rngSeed, address account) external; //onlyAdmin
}

File 30 of 34 : Roles.sol
// SPDX-License-Identifier: MIT


pragma solidity ^0.8.0;

/**
 * @title Roles
 * @dev Library for managing addresses assigned to a Role.
 */
library Roles {
  struct Role {
    mapping (address => bool) bearer;
  }

  /**
   * @dev give an account access to this role
   */
  function add(Role storage role, address account) internal {
    require(account != address(0));
    require(!has(role, account));

    role.bearer[account] = true;
  }

  /**
   * @dev remove an account's access to this role
   */
  function remove(Role storage role, address account) internal {
    require(account != address(0));
    require(has(role, account));

    role.bearer[account] = false;
  }

  /**
   * @dev check if an account has this role
   * @return bool
   */
  function has(Role storage role, address account)
    internal
    view
    returns (bool)
  {
    require(account != address(0));
    return role.bearer[account];
  }
}

File 31 of 34 : PepemonBattle.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;
import "./lib/AdminRole.sol";
import "./PepemonCardDeck.sol";
import "./iface/IPepemonCardOracle.sol";
import "./iface/IConfigurable.sol";
import "./lib/ChainLinkRngOracle.sol";

contract PepemonBattle is AdminRole, IConfigurable {

    event BattleCreated(
        address indexed player1Addr,
        address indexed player2Addr,
        uint256 battleId,
        uint256 p1DeckId,
        uint256 p2DeckId
    );

    mapping (uint => uint) public battleIdRNGSeed;

    uint constant _max_inte = 8;
    uint constant _max_cards_on_table = 5;
    uint constant _refreshTurn = 5;

    //Attacker can either be PLAYER_ONE or PLAYER_TWO
    enum Attacker {
        PLAYER_ONE,
        PLAYER_TWO
    }

    //Game can either be in FIRST_HALF or SECOND_HALF
    enum TurnHalves {
        FIRST_HALF,
        SECOND_HALF
    }

    //Battle contains:
    //battleId = ID of this battle
    //player1, player2 = players
    //currentTurn
    //attacker
    //turnHalves => first half or second half?
    struct Battle {
        uint256 battleId;
        Player player1;
        Player player2;
        uint256 currentTurn;
        Attacker attacker;
        TurnHalves turnHalves;
    }

    // Used to keep a local copy of players battle/support cards instead of reloading
    // from the oracle
    struct PlayersCards {
        uint256 player1SupportCardsCount;
        uint256 player2SupportCardsCount;
        IPepemonCardOracle.BattleCardStats player1Battlecard;
        IPepemonCardOracle.BattleCardStats player2Battlecard;
        uint256[] player1SupportCards;
        uint256[] player2SupportCards;
    }

    //playerAddr
    //deckId = Id of deck
    //hand = keeps track of current player's stats (such as health)
    //totalSupportCardIds = all IDs of support cards
    //playedCardCount = number of cards played already
    struct Player {
        address playerAddr;
        uint256 deckId;
        Hand hand;
        uint256[60] totalSupportCardIds;
        uint256 playedCardCount;
    }

    //health - health of player's battle card
    // battleCardId = card id of player
    // currentBCstats = all stats of the player's battle cards currently
    // supportCardInHandIds = IDs of the support cards in your current hand
    //                  the amount of support cards a player can play is determined by intelligence
    // tableSupportCardStats = Number of support cards that are currently played on the table
    // currentSuportCards = cards on the table, based on which turn ago they were played
    //                      Notice that the number of turns is limited by _refreshTurn
    struct Hand {
        int256 health;
        uint256 battleCardId;
        CurrentBattleCardStats currentBCstats;
        uint256[_max_inte] supportCardInHandIds;
        uint256 tableSupportCardStats;
        TableSupportCardStats[_max_cards_on_table] tableSupportCards;
    }
    //spd, inte, def, atk, sAtk, sDef - Current stats of battle card (with powerups included)
    //Each param can go into the negatives
    struct CurrentBattleCardStats {
        int256 spd;
        uint256 inte;
        int256 def;
        int256 atk;
        int256 sAtk;
        int256 sDef;
    }

    //links supportCardID with effectMany
    struct TableSupportCardStats {
        uint256 supportCardId;
        IPepemonCardOracle.EffectMany effectMany;
    }

    uint256 private _nextBattleId;

    bool private _allowBattleAgainstOneself;

    IPepemonCardOracle private _cardContract;
    PepemonCardDeck private _deckContract;
    ChainLinkRngOracle private _randNrGenContract;

    address public configAddress;

    constructor(address _configAddress) {
        configAddress = _configAddress;
        _nextBattleId = 1;
        _allowBattleAgainstOneself = false;
    }

    function setConfigAddress(address _configAddress) external onlyAdmin {
        configAddress = _configAddress;
    }

    function syncConfig() external override onlyAdmin {
        _cardContract = IPepemonCardOracle(PepemonConfig(configAddress).contractAddresses("PepemonCardOracle"));
        _deckContract = PepemonCardDeck(PepemonConfig(configAddress).contractAddresses("PepemonCardDeck"));
        _randNrGenContract = ChainLinkRngOracle(PepemonConfig(configAddress).contractAddresses("SampleChainLinkRngOracle"));
    }

    function setAllowBattleAgainstOneself(bool allow) public onlyAdmin {
        _allowBattleAgainstOneself = allow;
    }

    /**
     * @dev Create battle
     * @param p1Addr address player1
     * @param p1DeckId uint256
     * @param p2Addr address player2
     * @param p2DeckId uint256
     */
    function createBattle(
        address p1Addr,
        uint256 p1DeckId,
        address p2Addr,
        uint256 p2DeckId
    ) public onlyAdmin returns (Battle memory, uint256 battleId)  {
        require(_allowBattleAgainstOneself || p1Addr != p2Addr, "PepemonBattle: Cannot battle yourself");

        (uint256 p1BattleCardId, ) = _deckContract.decks(p1DeckId);
        (uint256 p2BattleCardId, ) = _deckContract.decks(p2DeckId);

        IPepemonCardOracle.BattleCardStats memory p1BattleCard = _cardContract.getBattleCardById(p1BattleCardId);
        IPepemonCardOracle.BattleCardStats memory p2BattleCard = _cardContract.getBattleCardById(p2BattleCardId);

        Battle memory newBattle;
        // Initiate battle ID
        newBattle.battleId = _nextBattleId;
        // Initiate player1
        newBattle.player1.hand.health = int256(uint256(p1BattleCard.hp));
        newBattle.player1.hand.battleCardId = p1BattleCardId;
        newBattle.player1.playerAddr = p1Addr;
        newBattle.player1.deckId = p1DeckId;
        // Initiate player2
        newBattle.player2.hand.health = int256(uint256(p2BattleCard.hp));
        newBattle.player2.hand.battleCardId = p2BattleCardId;
        newBattle.player2.playerAddr = p2Addr;
        newBattle.player2.deckId = p2DeckId;
        // Set the RNG seed
        battleIdRNGSeed[_nextBattleId] = _randSeed(newBattle);

        //Emit event
        emit BattleCreated(p1Addr, p2Addr, _nextBattleId, p1DeckId, p2DeckId);
        return (newBattle, _nextBattleId++);
    }

    function getPlayersCards(
        uint256 player1BattleCardId,
        uint256 player2BattleCardId,
        uint256 player1DeckId,
        uint256 player2DeckId
    ) internal view returns (PlayersCards memory) {
        // Get Battle Cards for Player 1 and Player 2
        IPepemonCardOracle.BattleCardStats memory player1Battlecard = _cardContract.getBattleCardById(player1BattleCardId);
        IPepemonCardOracle.BattleCardStats memory player2Battlecard = _cardContract.getBattleCardById(player2BattleCardId);

        // Get Support Cards for Player 1 and Player 2
        uint256[] memory player1SupportCards = _deckContract.getAllSupportCardsInDeck(player1DeckId);
        uint256[] memory player2SupportCards = _deckContract.getAllSupportCardsInDeck(player2DeckId);

        // Get Support Card count for Player 1 and Player 2
        uint256 player1SupportCardsCount = _deckContract.getSupportCardCountInDeck(player1DeckId);
        uint256 player2SupportCardsCount = _deckContract.getSupportCardCountInDeck(player2DeckId);

        // Create and return the PlayersCards struct instance
        return PlayersCards({
            player1Battlecard: player1Battlecard,
            player1SupportCards: player1SupportCards,
            player1SupportCardsCount: player1SupportCardsCount,
            player2Battlecard: player2Battlecard,
            player2SupportCards: player2SupportCards,
            player2SupportCardsCount: player2SupportCardsCount
        });
    }

    function goForBattle(Battle memory battle) public view returns (Battle memory, address winner) {
        // local cache for cards and decks info to reduce gas usage
        PlayersCards memory cards = getPlayersCards(
            battle.player1.hand.battleCardId,
            battle.player2.hand.battleCardId,
            battle.player1.deckId,
            battle.player2.deckId
        );

        //Initialize battle by starting the first turn
        battle = goForNewTurn(battle, cards);
        address winnerAddr;
        // Battle goes!
        while (true) {
            // Resolve attacker in the current turn
            battle = resolveAttacker(battle);
            // Fight
            battle = fight(battle);

            // Check if battle ended
            (bool isEnded, address win) = checkIfBattleEnded(battle);
            if (isEnded) {
                winnerAddr = win;
                break;
            }

            // Resolve turn halves
            battle = updateTurnInfo(battle, cards);
        }
        return (battle, winnerAddr);
    }

    //If currently in first half -> go to second half
    //If currently in second half -> make a new turn
    function updateTurnInfo(Battle memory battle, PlayersCards memory cards) internal view returns (Battle memory) {
        // If the current half is first, go over second half
        // or go over next turn
        if (battle.turnHalves == TurnHalves.FIRST_HALF) {
            battle.turnHalves = TurnHalves.SECOND_HALF;
        } else {
            battle = goForNewTurn(battle, cards);
        }

        return battle;
    }

    //Things this function does:
    //Reset both players hand infos back to base stats (stats with no support card powerups)
    //Check if support cards need to be scrambled and redealt
    //Redeal support cards if necessary
    //Calculate support card's power
    //Finally, draw Pepemon's intelligence number of cards.
    function goForNewTurn(Battle memory battle, PlayersCards memory cards) internal view returns (Battle memory) {
        Player memory player1 = battle.player1;
        Player memory player2 = battle.player2;

        // Load base battle card stats (stats without any powerups)
        // and reset both players' hand infos to base stats
        player1.hand.currentBCstats = getCardStats(cards.player1Battlecard);
        player2.hand.currentBCstats = getCardStats(cards.player2Battlecard);

        uint256 p1SupportCardIdsLength = cards.player1SupportCardsCount;
        uint256 p2SupportCardIdsLength = cards.player2SupportCardsCount;

        //Refresh cards every 5 turns
        bool isRefreshTurn = (battle.currentTurn % _refreshTurn == 0);

        if (isRefreshTurn) {
            //Need to refresh decks

            // Shuffle player1 support cards
            uint[] memory scrambled = Arrays.shuffle(cards.player1SupportCards, _randMod(69, battle));

            //Copy back scrambled cards to original list
            for (uint i = 0 ; i < p1SupportCardIdsLength; i++){
                player1.totalSupportCardIds[i]=scrambled[i];
            }
            
            //Reset played card count
            player1.playedCardCount = 0;

            //Shuffling player 2 support cards
            //Create a pseudorandom seed and shuffle the cards
            uint[] memory scrambled2 = Arrays.shuffle(cards.player2SupportCards, _randMod(420, battle));

            //Copy the support cards back into the list
            for (uint256 i = 0; i < p2SupportCardIdsLength; i++) {
                player2.totalSupportCardIds[i]=scrambled2[i];
            }
            
            //Reset player2 played card counts
            player2.playedCardCount = 0;
        }
        else 
        {
            //Don't need to refresh cards now

            // Get temp support info of previous turn's hands and calculate their effect for the new turn
            player1.hand = calSupportCardsOnTable(player1.hand, player2.hand);
            player2.hand = calSupportCardsOnTable(player2.hand, player1.hand);
        }

        // Draw player1 support cards for the new turn
        uint256 remainingCards = p1SupportCardIdsLength - player1.playedCardCount;
        // limit number of cards to be taken to prevent taking invalid cards
        player1.hand.currentBCstats.inte = remainingCards < player1.hand.currentBCstats.inte ? remainingCards : player1.hand.currentBCstats.inte;
        for (uint256 i = 0; i < player1.hand.currentBCstats.inte; i++) {
            // "totalSupportCardIds" array has 60 elements, max intelligence is 8 (_max_inte), each 5 rounds playedCardCount is reset, 
            // so in total, 40 (5*8) cards could end up being used, no out of bounds errors
            player1.hand.supportCardInHandIds[i] = player1.totalSupportCardIds[i + player1.playedCardCount];
        }
        player1.playedCardCount += player1.hand.currentBCstats.inte;

        // Draw player2 support cards for the new turn
        remainingCards = p2SupportCardIdsLength - player2.playedCardCount;
        // limit number of cards to be taken to prevent taking invalid cards
        player2.hand.currentBCstats.inte = remainingCards < player2.hand.currentBCstats.inte ? remainingCards : player2.hand.currentBCstats.inte;
        for (uint256 i = 0; i < player2.hand.currentBCstats.inte; i++) {
            player2.hand.supportCardInHandIds[i] = player2.totalSupportCardIds[i + player2.playedCardCount];
        }
        player2.playedCardCount += player2.hand.currentBCstats.inte;

        //Update current battle info
        battle.player1 = player1;
        battle.player2 = player2;

        // Increment current turn number of battle
        battle.currentTurn++;

        // Go for first half in turn
        battle.turnHalves = TurnHalves.FIRST_HALF;

        return battle;
    }

    //This method calculates the battle card's stats after taking into consideration all the support cards currently being played
    function calSupportCardsOnTable(Hand memory hand, Hand memory oppHand) internal pure returns (Hand memory) {
        for (uint256 i = 0; i < hand.tableSupportCardStats; i++) {
            //Loop through every support card currently played

            //Get the support card being considered now
            TableSupportCardStats memory tableSupportCardStat = hand.tableSupportCards[i];
            
            //Get the effect of that support card
            IPepemonCardOracle.EffectMany memory effect = tableSupportCardStat.effectMany;
            
            //If there is at least 1 turn left
            if (effect.numTurns >= 1) {

                //If the effect is for me
                if (effect.effectFor == IPepemonCardOracle.EffectFor.ME) {
                    // Change my card's stats using that support card
                    // Currently effectTo of EffectMany can be ATTACK, DEFENSE, SPEED and INTELLIGENCE
                    //Get the statistic changed and update it 
                    //Intelligence can't go into the negatives nor above _max_inte
                    if (effect.effectTo == IPepemonCardOracle.EffectTo.ATTACK) {
                        hand.currentBCstats.atk += effect.power;
                    } else if (effect.effectTo == IPepemonCardOracle.EffectTo.DEFENSE) {
                        hand.currentBCstats.def += effect.power;
                    } else if (effect.effectTo == IPepemonCardOracle.EffectTo.SPEED) {
                        hand.currentBCstats.spd += effect.power;
                    } else if (effect.effectTo == IPepemonCardOracle.EffectTo.INTELLIGENCE) {
                        int temp;
                        temp = int256(hand.currentBCstats.inte) + effect.power;
                        temp = temp > int(_max_inte) ? int(_max_inte) : temp;
                        hand.currentBCstats.inte = (temp > 0 ? uint(temp) : 0);
                    }
                } else {
                    //The card affects the opp's pepemon
                    //Update card stats of the opp's pepemon
                    //Make sure INT stat can't go below zero nor above _max_inte
                    if (effect.effectTo == IPepemonCardOracle.EffectTo.ATTACK) {
                        oppHand.currentBCstats.atk += effect.power;
                    } else if (effect.effectTo == IPepemonCardOracle.EffectTo.DEFENSE) {
                        oppHand.currentBCstats.def += effect.power;
                    } else if (effect.effectTo == IPepemonCardOracle.EffectTo.SPEED) {
                        oppHand.currentBCstats.spd += effect.power;
                    } else if (effect.effectTo == IPepemonCardOracle.EffectTo.INTELLIGENCE) {
                        int temp;
                        temp = int256(oppHand.currentBCstats.inte) + effect.power;
                        temp = temp > int(_max_inte) ? int(_max_inte) : temp;
                        oppHand.currentBCstats.inte = (temp > 0 ? uint(temp) : 0);
                    }
                }
                // Decrease effect numTurns by 1 since 1 turn has already passed
                effect.numTurns--;
                // Delete this one from tableSupportCardStat if all turns of the card have been exhausted
                if (effect.numTurns == 0) {
                    if (i < hand.tableSupportCardStats - 1) {
                        hand.tableSupportCards[i] = hand.tableSupportCards[hand.tableSupportCardStats - 1];
                    }
                    delete hand.tableSupportCards[hand.tableSupportCardStats - 1];
                    hand.tableSupportCardStats--;
                }
            }
        }

        return hand;
    }

    //This method gets the current attacker
    function resolveAttacker(Battle memory battle) internal view returns (Battle memory) {
        CurrentBattleCardStats memory p1CurrentBattleCardStats = battle.player1.hand.currentBCstats;
        CurrentBattleCardStats memory p2CurrentBattleCardStats = battle.player2.hand.currentBCstats;

        if (battle.turnHalves == TurnHalves.FIRST_HALF) {
            //Player with highest speed card goes first
            if (p1CurrentBattleCardStats.spd > p2CurrentBattleCardStats.spd) {
                battle.attacker = Attacker.PLAYER_ONE;
            } else if (p1CurrentBattleCardStats.spd < p2CurrentBattleCardStats.spd) {
                battle.attacker = Attacker.PLAYER_TWO;
            } else {
                //Tiebreak: intelligence
                if (p1CurrentBattleCardStats.inte > p2CurrentBattleCardStats.inte) {
                    battle.attacker = Attacker.PLAYER_ONE;
                } else if (p1CurrentBattleCardStats.inte < p2CurrentBattleCardStats.inte) {
                    battle.attacker = Attacker.PLAYER_TWO;
                } else {
                    //Second tiebreak: use RNG
                    uint256 rand = _randMod(69420, battle) % 2;
                    battle.attacker = (rand == 0 ? Attacker.PLAYER_ONE : Attacker.PLAYER_TWO);
                }
            }
        } else {
            //For second half, switch players
            battle.attacker = (battle.attacker == Attacker.PLAYER_ONE ? Attacker.PLAYER_TWO : Attacker.PLAYER_ONE);
        }

        return battle;
    }

    //Create a random seed, using the chainlink number and the addresses of the combatants as entropy
    function _randSeed(Battle memory battle) private view returns (uint256) {
        //Get the chainlink random number
        uint chainlinkNumber = _randNrGenContract.getRandomNumber();
        //Create a new pseudorandom number using the seed and battle info as entropy
        //This makes sure the RNG returns a different number every time
        uint256 randomNumber = uint(keccak256(abi.encodePacked(block.number, chainlinkNumber, battle.player1.playerAddr, battle.player2.playerAddr)));
        return randomNumber;
    }

    function _randMod(uint256 seed, Battle memory battle) private view returns (uint256) {
        uint256 randomNumber = uint(keccak256(abi.encodePacked(seed, battle.currentTurn, battleIdRNGSeed[battle.battleId])));
        return randomNumber;
    }

    //Check if battle ended by looking at player's health
    function checkIfBattleEnded(Battle memory battle) public pure returns (bool, address) {
        if (battle.player1.hand.health <= 0) {
            return (true, battle.player1.playerAddr);
        } else if (battle.player2.hand.health <= 0) {
            return (true, battle.player2.playerAddr);
        } else {
            return (false, address(0));
        }
    }

    function fight(Battle memory battle) public view returns (Battle memory) {
        Hand memory atkHand;
        Hand memory defHand;

        //Get attacker and defender for current turn
        if (battle.attacker == Attacker.PLAYER_ONE) {
            atkHand = battle.player1.hand;
            defHand = battle.player2.hand;
        } else {
            atkHand = battle.player2.hand;
            defHand = battle.player1.hand;
        }

        (atkHand, defHand) = calSupportCardsInHand(atkHand, defHand);

        //Give 2 point advantage if weakness, 2 point disadvantage if resistance
        atkHand.currentBCstats.atk += resistanceWeaknessCal(atkHand, defHand);

        // Fight

        //Calculate HP loss for defending player
        if (atkHand.currentBCstats.atk > defHand.currentBCstats.def) {
            //If attacker's attack > defender's defense, find difference. That is the defending player's HP loss
            defHand.health -= (atkHand.currentBCstats.atk - defHand.currentBCstats.def);
        } else {
            //Otherwise, defender loses 1 HP
            defHand.health -= 1;
        }

        //Write updated info back into battle
        if (battle.attacker == Attacker.PLAYER_ONE) {
            battle.player1.hand = atkHand;
            battle.player2.hand = defHand;
        } else {
            battle.player1.hand = defHand;
            battle.player2.hand = atkHand;
        }

        return battle;
    }

    
    //We calculate the effect of every card in the player's hand
    function calSupportCardsInHand(Hand memory atkHand, Hand memory defHand) public view returns (Hand memory, Hand memory) {
        // If this card is included in player's hand, adds an additional power equal to the total of
        // all normal offense/defense cards
        bool isPower0CardIncluded = false;
        // Total sum of normal support cards
        int256 totalNormalPower = 0;
        // Cal attacker hand
        for (uint256 i = 0; i < atkHand.currentBCstats.inte; i++) {
            //Loop through every card the attacker has in his hand
            uint256 id = atkHand.supportCardInHandIds[i];

            //Get the support cardStats
            IPepemonCardOracle.SupportCardStats memory cardStats = _cardContract.getSupportCardById(id);
            if (cardStats.supportCardType == IPepemonCardOracle.SupportCardType.OFFENSE) {
                // Card type is OFFENSE.
                // Calc effects of EffectOne array

                IPepemonCardOracle.EffectOne memory effectOne = cardStats.effectOne;
                
                //Checks if that support card is triggered and by how much it is triggered by
                (bool isTriggered, uint256 multiplier) = checkReqCode(atkHand, defHand, effectOne.reqCode, true);
                if (isTriggered) {
                    //use triggeredPower if triggered
                    atkHand.currentBCstats.atk += effectOne.triggeredPower * int256(multiplier);
                    totalNormalPower += effectOne.triggeredPower * int256(multiplier);
                }
                else{
                    //use basePower if not
                    atkHand.currentBCstats.atk += effectOne.basePower;
                    totalNormalPower += effectOne.basePower;
                }

            } else if (cardStats.supportCardType == IPepemonCardOracle.SupportCardType.STRONG_OFFENSE) {
                // Card type is STRONG OFFENSE.

                //Make sure unstackable cards can't be stacked
                if (cardStats.unstackable) {
                    bool isNew = true;
                    // Check if card is new to previous cards
                    for (uint256 j = 0; j < i; j++) {
                        if (id == atkHand.supportCardInHandIds[j]) {
                            isNew = false;
                            break;
                        }
                    }
                    if (!isNew) {
                        //If it isn't - skip card
                        continue;
                    }
                    // Check if card is new to temp support info cards
                    for (uint256 j = 0; j < atkHand.tableSupportCardStats; j++) {
                        if (id == atkHand.tableSupportCards[j].supportCardId) {
                            isNew = false;
                            break;
                        }
                    }
                    if (!isNew) {
                        //If it isn't - skip card
                        continue;
                    }
                }

                // Calc effects of EffectOne array

                IPepemonCardOracle.EffectOne memory effectOne = cardStats.effectOne;
                (bool isTriggered, uint256 multiplier) = checkReqCode(atkHand, defHand, effectOne.reqCode, true);
                if (isTriggered) {
                    //If triggered: use triggered power
                    if (multiplier > 1) {
                        atkHand.currentBCstats.atk += effectOne.triggeredPower * int256(multiplier);
                    } else {
                        if (effectOne.effectTo == IPepemonCardOracle.EffectTo.STRONG_ATTACK) {
                            // If it's a use Special Attack instead of Attack card
                            atkHand.currentBCstats.atk = atkHand.currentBCstats.sAtk;
                            continue;
                        } else if (effectOne.triggeredPower == 0) {
                            // We have a card that says ATK is increased by amount
                            // Equal to the total of all offense cards in the current turn
                            isPower0CardIncluded = true;
                            continue;
                        }
                        atkHand.currentBCstats.atk += effectOne.triggeredPower;
                    }
                }
                else{
                    //If not triggered: use base power instead
                    atkHand.currentBCstats.atk += effectOne.basePower;
                    totalNormalPower += effectOne.basePower;
                }
                // If card lasts for >1 turns
                if (cardStats.effectMany.power != 0) {
                    // Add card  to table if <5 on table currently
                    if (atkHand.tableSupportCardStats < _max_cards_on_table) {
                        atkHand.tableSupportCards[atkHand.tableSupportCardStats++] = TableSupportCardStats({
                            supportCardId: id,
                            effectMany: cardStats.effectMany
                        });
                    }
                }
            } else {
                // Other card type is ignored.
                continue;
            }
        }
        if (isPower0CardIncluded) {
            //If we have a card that says ATK is increased by amount equal to total of all offense cards
            atkHand.currentBCstats.atk += totalNormalPower;
        }
        // Cal defense hand
        isPower0CardIncluded = false;
        totalNormalPower = 0;

        for (uint256 i = 0; i < defHand.currentBCstats.inte; i++) {
            uint256 id = defHand.supportCardInHandIds[i];
            IPepemonCardOracle.SupportCardStats memory card = _cardContract.getSupportCardById(id);
            if (card.supportCardType == IPepemonCardOracle.SupportCardType.DEFENSE) {
                // Card type is DEFENSE
                // Calc effects of EffectOne array

                    IPepemonCardOracle.EffectOne memory effectOne = card.effectOne;
                    (bool isTriggered, uint256 multiplier) = checkReqCode(atkHand, defHand, effectOne.reqCode, false);
                    if (isTriggered) {
                        defHand.currentBCstats.def += effectOne.triggeredPower * int256(multiplier);
                        totalNormalPower += effectOne.triggeredPower * int256(multiplier);
                    }
                    else{
                        //If not triggered, use base power instead
                        defHand.currentBCstats.def += effectOne.basePower;
                        totalNormalPower += effectOne.basePower;
                    }

            } else if (card.supportCardType == IPepemonCardOracle.SupportCardType.STRONG_DEFENSE) {
                // Card type is STRONG DEFENSE
                if (card.unstackable) {
                    bool isNew = true;
                    // Check if card is new to previous cards
                    for (uint256 j = 0; j < i; j++) {
                        if (id == defHand.supportCardInHandIds[j]) {
                            isNew = false;
                            break;
                        }
                    }
                    // Check if card is new to temp support info cards
                    for (uint256 j = 0; j < defHand.tableSupportCardStats; j++) {
                        if (id == defHand.tableSupportCards[j].supportCardId) {
                            isNew = false;
                            break;
                        }
                    }
                    if (!isNew) {
                        continue;
                    }
                }
                // Calc effects of EffectOne array
                IPepemonCardOracle.EffectOne memory effectOne = card.effectOne;
                (bool isTriggered, uint256 num) = checkReqCode(atkHand, defHand, effectOne.reqCode, false);
                if (isTriggered) {
                    if (num > 0) {
                        defHand.currentBCstats.def += effectOne.triggeredPower * int256(num);
                    } else {
                        if (effectOne.effectTo == IPepemonCardOracle.EffectTo.STRONG_DEFENSE) {
                            defHand.currentBCstats.def = defHand.currentBCstats.sDef;
                            continue;
                        } else if (effectOne.triggeredPower == 0) {
                            // Equal to the total of all defense cards in the current turn
                            isPower0CardIncluded = true;
                            continue;
                        }
                        defHand.currentBCstats.def += effectOne.triggeredPower;
                    }
                }
                else{
                    //If not triggered, use base stats instead
                    defHand.currentBCstats.def += effectOne.basePower;
                    totalNormalPower += effectOne.basePower;
                }
            
                // If card effect lasts >1 turn
                if (card.effectMany.power != 0) {
                    // Add card to table if there are <5 cards on table right now
                    if (defHand.tableSupportCardStats < _max_cards_on_table) {
                        defHand.tableSupportCards[defHand.tableSupportCardStats++] = TableSupportCardStats({
                            supportCardId: id,
                            effectMany: card.effectMany
                        });
                    }
                }
            } else {
                // Other card type is ignored.
                continue;
            }
        }
        if (isPower0CardIncluded) {
            //If a "add total of defense" card is included
            defHand.currentBCstats.def += totalNormalPower;
        }

        return (atkHand, defHand);
    }

    //Strip important game information (like speed, intelligence, etc.) from battle card
    function getCardStats(IPepemonCardOracle.BattleCardStats memory x) internal pure returns (CurrentBattleCardStats memory){
        CurrentBattleCardStats memory ret;

        ret.spd = int(uint(x.spd));
        ret.inte = x.inte;
        ret.def = int(uint(x.def));
        ret.atk = int(uint(x.atk));
        ret.sAtk = int(uint(x.sAtk));
        ret.sDef = int(uint(x.sDef));

        return ret;
    }

//Checks if the requirements are satisfied for a certain code
//returns bool - is satisfied?
// uint - the multiplier for the card's attack power
// for most cases multiplier is 1
function checkReqCode(
        Hand memory atkHand,
        Hand memory defHand,
        uint256 reqCode,
        bool isAttacker
    ) internal view returns (bool, uint256) {
        bool isTriggered = false;
        uint256 multiplier = 1;
        if (reqCode == 0) {
            // No requirement
            isTriggered = true;
        } else if (reqCode == 1) {
            // Intelligence of offense pepemon <= 5.
            isTriggered = (atkHand.currentBCstats.inte <= 5 );
        } else if (reqCode == 2) {
            // Number of defense cards of defense pepemon is 0.
            isTriggered = true;
            for (uint256 i = 0; i < defHand.currentBCstats.inte; i++) {
                IPepemonCardOracle.SupportCardType supportCardType = _cardContract.getSupportCardTypeById(
                    defHand.supportCardInHandIds[i]
                );
                if (supportCardType == IPepemonCardOracle.SupportCardType.DEFENSE) {
                    isTriggered = false;
                    break;
                }
            }
        } else if (reqCode == 3) {
            // Each +2 offense cards of offense pepemon.
            return countCards(atkHand, IPepemonCardOracle.SupportCardType.OFFENSE, 2);
        } else if (reqCode == 4) {
            // Each +3 offense cards of offense pepemon.
            return countCards(atkHand, IPepemonCardOracle.SupportCardType.OFFENSE, 3);
        } else if (reqCode == 5) {
            // Each offense card of offense pepemon.
            return countCards(atkHand, IPepemonCardOracle.SupportCardType.OFFENSE, 0);

        } else if (reqCode == 6) {
            // Each +3 defense card of defense pepemon.
            return countCards(defHand, IPepemonCardOracle.SupportCardType.DEFENSE, 3);
        } else if (reqCode == 7) {
            // Each +4 defense card of defense pepemon.
            return countCards(defHand, IPepemonCardOracle.SupportCardType.DEFENSE, 4);
        } else if (reqCode == 8) {
            // Intelligence of defense pepemon <= 5.
            isTriggered = (defHand.currentBCstats.inte <= 5 );
        } else if (reqCode == 9) {
            // Intelligence of defense pepemon >= 7.
            isTriggered = (defHand.currentBCstats.inte >= 7 );
        } else if (reqCode == 10) {
            // Offense pepemon is using strong attack
            for (uint256 i = 0; i < atkHand.currentBCstats.inte; i++) {
                IPepemonCardOracle.SupportCardStats memory card = _cardContract.getSupportCardById(
                    atkHand.supportCardInHandIds[i]
                );
                if (card.supportCardType == IPepemonCardOracle.SupportCardType.STRONG_OFFENSE) {
                    isTriggered = true;
                    break;
                }
            }
            multiplier = 1;
        } else if (reqCode == 11) {
            // The current HP is less than 50% of max HP.
            isTriggered = lessThanHalfHP(isAttacker ? atkHand : defHand);
        }
        return (isTriggered, multiplier);
    }

    function lessThanHalfHP(Hand memory hand) internal view returns (bool){
        return hand.health * 2 <= int256(uint256(_cardContract.getBattleCardById(hand.battleCardId).hp));
    }
    
    function countCards(Hand memory hand, IPepemonCardOracle.SupportCardType cardType, int basePower) internal view returns (bool, uint){
        uint multiplier = 0;
        for (uint256 i = 0; i < hand.currentBCstats.inte; i++) {
            IPepemonCardOracle.SupportCardStats memory card = _cardContract.getSupportCardById(
                hand.supportCardInHandIds[i]
            );
            if (card.supportCardType != cardType) {
                continue;
            }
            IPepemonCardOracle.EffectOne memory effectOne = card.effectOne;
            if (effectOne.basePower == basePower || basePower == 0) {
                multiplier++;
            }
        }
        return (multiplier>0, multiplier);
    }

    function resistanceWeaknessCal(Hand memory atkHand, Hand memory defHand) internal view returns (int){
        int adjustment = 0;
        uint battleIdAtk = atkHand.battleCardId;
        uint battleIdDef = defHand.battleCardId;
        IPepemonCardOracle.BattleCardTypes atkType = _cardContract.getBattleCardById(battleIdAtk).element;
        IPepemonCardOracle.BattleCardTypes defType = _cardContract.getBattleCardById(battleIdDef).element;
        IPepemonCardOracle.BattleCardTypes weakness = _cardContract.getWeakResist(defType).weakness;
        IPepemonCardOracle.BattleCardTypes resistance = _cardContract.getWeakResist(defType).resistance;
        if (atkType == weakness) adjustment = 2;
        if (atkType == resistance) adjustment = -2;
        return adjustment;
    }
}

File 32 of 34 : PepemonCardDeck.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;
//pragma experimental ABIEncoderV2;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "./iface/IPepemonFactory.sol";
import "./iface/IPepemonCardOracle.sol";
import "./lib/AdminRole.sol";
import "./lib/Arrays.sol";
import "./lib/PepemonConfig.sol";
import "./lib/AdminRole.sol";
import "./lib/ChainLinkRngOracle.sol";

contract PepemonCardDeck is ERC721, ERC1155Holder, AdminRole, IConfigurable {
    using SafeMath for uint256;

    struct Deck {
        uint256 battleCardId;
        uint256 supportCardCount;
        mapping(uint256 => SupportCardType) supportCardTypes;
        uint256[] supportCardTypeList;
    }

    struct SupportCardType {
        uint256 supportCardId;
        uint256 count;
        uint256 pointer;
        bool isEntity;
    }

    struct SupportCardRequest {
        uint256 supportCardId;
        uint256 amount;
    }

    uint256 public MAX_SUPPORT_CARDS;
    uint256 public MIN_SUPPORT_CARDS;

    // cards allowed to be picked on when creating the Starter Deck
    uint256[] public allowedInitialDeckBattleCards;
    uint256[] allowedInitialDeckSupportCards;
    uint256 initialDeckSupportCardAmount;

    // set this to 0 to disable minting test cards.
    uint256 maxMintTestCardId;
    uint256 minMintTestCardId;

    uint256 nextDeckId;
    address public configAddress;
    address public factoryAddress;
    address public randNrGenContract;

    mapping(uint256 => Deck) public decks;
    mapping(address => uint256[]) public playerToDecks;

    constructor(address _configAddress) ERC721("Pepedeck", "Pepedeck") {
        nextDeckId = 1;
        MAX_SUPPORT_CARDS = 60;
        MIN_SUPPORT_CARDS = 40;

        minMintTestCardId = 1;
        configAddress = _configAddress;
    }

    /**
     * @dev Override supportInterface .
     */
    function supportsInterface(
        bytes4 interfaceId
    ) public view virtual override(ERC721, ERC1155Receiver) returns (bool) {
        return super.supportsInterface(interfaceId);
    }

    // MODIFIERS
    modifier sendersDeck(uint256 _deckId) {
        require(msg.sender == ownerOf(_deckId), "PepemonCardDeck: Not your deck");
        _;
    }

    // PUBLIC METHODS
    function setConfigAddress(address _configAddress) external onlyAdmin {
        configAddress = _configAddress;
    }

    function syncConfig() external override onlyAdmin {
        factoryAddress = PepemonConfig(configAddress).contractAddresses("PepemonFactory");
    }

    function setMaxSupportCards(uint256 _maxSupportCards) public onlyAdmin {
        MAX_SUPPORT_CARDS = _maxSupportCards;
    }

    function setMinSupportCards(uint256 _minSupportCards) public onlyAdmin {
        MIN_SUPPORT_CARDS = _minSupportCards;
    }

    function setRandNrGenContractAddress(address randOracleAddress) public onlyAdmin {
        randNrGenContract = randOracleAddress;
    }

    function setInitialDeckOptions(
        uint256[] calldata battleCardIds,
        uint256[] calldata supportCards,
        uint256 maxInitialSupportCards
    ) public onlyAdmin {
        require(Arrays.isSortedAscending(battleCardIds));
        require(maxInitialSupportCards <= MAX_SUPPORT_CARDS);

        initialDeckSupportCardAmount = maxInitialSupportCards;
        allowedInitialDeckBattleCards = battleCardIds;
        allowedInitialDeckSupportCards = supportCards;
    }

    // ALLOW TEST MINTING
    function setMintingCards(uint256 minCardId, uint256 maxCardId) public onlyAdmin {
        maxMintTestCardId = maxCardId;
        minMintTestCardId = minCardId;
    }

    /**
     * @dev right now there are 40 different cards that can be minted, but the maximum is configurable with maxMintTestCard.
     * setting maxMintTestCard to 0 disables this card minting.
     */
    function mintCards() public {
        require(maxMintTestCardId > 0, "Minting test cards is disabled");
        IPepemonFactory(factoryAddress).batchMint(minMintTestCardId, maxMintTestCardId, msg.sender);
    }

    function mintInitialDeck(uint256 battleCardId) public {
        require(Arrays.contains(allowedInitialDeckBattleCards, battleCardId), "Invalid battlecard");
        require(playerToDecks[msg.sender].length == 0, "Not your first deck");
        // battlecard + support cards
        uint amount = initialDeckSupportCardAmount + 1;
        uint256[] memory cards = new uint256[](amount);

        // First step: Mint cards

        uint256 allowedCardsCount = allowedInitialDeckSupportCards.length;
        uint256 randomNumber = randSeed();
        cards[0] = battleCardId;
        // begin from index 1 instead of 0 because battlecard was already added
        for (uint256 i = 1; i < amount; ++i) {
            randomNumber = uint256(keccak256(abi.encodePacked(i, randomNumber)));
            cards[i] = allowedInitialDeckSupportCards[randomNumber % allowedCardsCount];
        }
        // mint cards directly for this contract instead of msg.sender, so that we dont have to
        // transfer it back and forth
        IPepemonFactory(factoryAddress).batchMintList(cards, address(this));

        // Second step: Add cards into new the deck

        uint256 newDeckId = createDeckInternal();

        // no need to call addBattleCardToDeck since the new deck never had a battlecard before, plus
        // the battlecard is already owned by this contract
        decks[newDeckId].battleCardId = battleCardId;

        // begin from index 1 again because battlecard is in index 0
        for (uint256 i = 1; i < amount; ++i) {
            addSupportCardToDeckDirectly(newDeckId, cards[i], 1);
        }
    }

    function createDeck() public {
        createDeckInternal();
    }

    function addBattleCardToDeck(uint256 deckId, uint256 battleCardId) public sendersDeck(deckId) {
        require(
            IPepemonFactory(factoryAddress).balanceOf(msg.sender, battleCardId) >= 1,
            "PepemonCardDeck: Don't own battle card"
        );

        require(battleCardId != decks[deckId].battleCardId, "PepemonCardDeck: Card already in deck");

        uint256 oldBattleCardId = decks[deckId].battleCardId;
        decks[deckId].battleCardId = battleCardId;

        IPepemonFactory(factoryAddress).safeTransferFrom(msg.sender, address(this), battleCardId, 1, "");

        returnBattleCardFromDeck(oldBattleCardId);
    }

    function removeBattleCardFromDeck(uint256 _deckId) public sendersDeck(_deckId) {
        uint256 oldBattleCardId = decks[_deckId].battleCardId;

        decks[_deckId].battleCardId = 0;

        returnBattleCardFromDeck(oldBattleCardId);
    }

    function addSupportCardsToDeck(
        uint256 deckId,
        SupportCardRequest[] memory supportCards
    ) public sendersDeck(deckId) {
        for (uint256 i = 0; i < supportCards.length; i++) {
            addSupportCardToDeck(deckId, supportCards[i].supportCardId, supportCards[i].amount);
        }
    }

    function removeSupportCardsFromDeck(
        uint256 _deckId,
        SupportCardRequest[] memory _supportCards
    ) public sendersDeck(_deckId) {
        for (uint256 i = 0; i < _supportCards.length; i++) {
            removeSupportCardFromDeck(_deckId, _supportCards[i].supportCardId, _supportCards[i].amount);
        }
    }

    // INTERNALS
    function createDeckInternal() internal returns (uint256) {
        _safeMint(msg.sender, nextDeckId);
        playerToDecks[msg.sender].push(nextDeckId);
        uint256 playerDeck = nextDeckId;
        nextDeckId = nextDeckId.add(1);
        return playerDeck;
    }

    function addSupportCardToDeck(uint256 _deckId, uint256 _supportCardId, uint256 _amount) internal {
        require(MAX_SUPPORT_CARDS >= decks[_deckId].supportCardCount.add(_amount), "PepemonCardDeck: Deck overflow");
        require(
            IPepemonFactory(factoryAddress).balanceOf(msg.sender, _supportCardId) >= _amount,
            "PepemonCardDeck: You don't have enough of this card"
        );

        addSupportCardToDeckDirectly(_deckId, _supportCardId, _amount);

        IPepemonFactory(factoryAddress).safeTransferFrom(msg.sender, address(this), _supportCardId, _amount, "");
    }

    function addSupportCardToDeckDirectly(uint256 _deckId, uint256 _supportCardId, uint256 _amount) internal {
        if (!decks[_deckId].supportCardTypes[_supportCardId].isEntity) {
            decks[_deckId].supportCardTypes[_supportCardId] = SupportCardType({
                supportCardId: _supportCardId,
                count: _amount,
                pointer: decks[_deckId].supportCardTypeList.length,
                isEntity: true
            });

            // Prepend the ID to the list
            decks[_deckId].supportCardTypeList.push(_supportCardId);
        } else {
            SupportCardType storage supportCard = decks[_deckId].supportCardTypes[_supportCardId];
            supportCard.count = supportCard.count.add(_amount);
        }

        decks[_deckId].supportCardCount = decks[_deckId].supportCardCount.add(_amount);
    }

    function removeSupportCardFromDeck(uint256 _deckId, uint256 _supportCardId, uint256 _amount) internal {
        SupportCardType storage supportCardList = decks[_deckId].supportCardTypes[_supportCardId];
        supportCardList.count = supportCardList.count.sub(_amount);

        decks[_deckId].supportCardCount = decks[_deckId].supportCardCount.sub(_amount);

        if (supportCardList.count == 0) {
            uint256 lastItemIndex = decks[_deckId].supportCardTypeList.length - 1;

            // update the pointer of the item to be swapped
            uint256 lastSupportCardId = decks[_deckId].supportCardTypeList[lastItemIndex];
            decks[_deckId].supportCardTypes[lastSupportCardId].pointer = supportCardList.pointer;

            // swap the last item of the list with the one to be deleted
            decks[_deckId].supportCardTypeList[supportCardList.pointer] = decks[_deckId].supportCardTypeList[
                lastItemIndex
            ];
            decks[_deckId].supportCardTypeList.pop();

            delete decks[_deckId].supportCardTypes[_supportCardId];
        }

        IPepemonFactory(factoryAddress).safeTransferFrom(address(this), msg.sender, _supportCardId, _amount, "");
    }

    function returnBattleCardFromDeck(uint256 _battleCardId) internal {
        if (_battleCardId != 0) {
            IPepemonFactory(factoryAddress).safeTransferFrom(address(this), msg.sender, _battleCardId, 1, "");
        }
    }

    // VIEWS
    function getDeckCount(address player) public view returns (uint256) {
        return playerToDecks[player].length;
    }

    function getBattleCardInDeck(uint256 _deckId) public view returns (uint256) {
        return decks[_deckId].battleCardId;
    }

    function getCardTypesInDeck(uint256 _deckId) public view returns (uint256[] memory) {
        Deck storage deck = decks[_deckId];

        uint256[] memory supportCardTypes = new uint256[](deck.supportCardTypeList.length);

        for (uint256 i = 0; i < deck.supportCardTypeList.length; i++) {
            supportCardTypes[i] = deck.supportCardTypeList[i];
        }

        return supportCardTypes;
    }

    function getCountOfCardTypeInDeck(uint256 _deckId, uint256 _cardTypeId) public view returns (uint256) {
        return decks[_deckId].supportCardTypes[_cardTypeId].count;
    }

    function getSupportCardCountInDeck(uint256 deckId) public view returns (uint256) {
        return decks[deckId].supportCardCount;
    }

    /**
     * @dev Returns array of support cards for a deck
     * @param _deckId uint256 ID of the deck
     */
    function getAllSupportCardsInDeck(uint256 _deckId) public view returns (uint256[] memory) {
        Deck storage deck = decks[_deckId];
        uint256[] memory supportCards = new uint256[](deck.supportCardCount);
        uint256 idx = 0;
        for (uint256 i = 0; i < deck.supportCardTypeList.length; i++) {
            uint256 supportCardId = deck.supportCardTypeList[i];
            uint256 count = deck.supportCardTypes[supportCardId].count;
            for (uint256 j = 0; j < count; j++) {
                supportCards[idx++] = supportCardId;
            }
        }
        return supportCards;
    }

    /**
     * @dev Shuffles deck
     * @param _deckId uint256 ID of the deck
     */
    function shuffleDeck(uint256 _deckId, uint256 _seed) public view returns (uint256[] memory) {
        uint256[] memory totalSupportCards = getAllSupportCardsInDeck(_deckId);
        return Arrays.shuffle(totalSupportCards, _seed);
    }

    //Create a random seed
    function randSeed() private view returns (uint256) {
        //Get the chainlink random number
        uint chainlinkNumber = ChainLinkRngOracle(randNrGenContract).getRandomNumber();
        //Create a new pseudorandom number using the seed and block info as entropy
        //This makes sure the RNG returns a different number every time
        uint256 randomNumber = uint(keccak256(abi.encodePacked(block.number, block.timestamp, chainlinkNumber)));
        return randomNumber;
    }
}

File 33 of 34 : PepemonMatchmaker.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import "./lib/AdminRole.sol";
import "./PepemonCardDeck.sol";
import "./lib/RewardPool.sol";
import "./lib/Elo.sol";
import "./iface/IPepemonCardOracle.sol";
import "./PepemonBattle.sol";
import "./lib/PepemonConfig.sol";

contract PepemonMatchmaker is ERC1155Holder, ERC721Holder, AdminRole, IConfigurable {
    event BattleFinished(address indexed winner, address indexed loser, uint256 battleId);

    struct waitingDeckData {
        uint256 deckId;
        uint256 enterTimestamp;
    }

    address private _battleAddress;
    address private _deckAddress;
    address private _rewardPoolAddress;
    bool private _allowBattleAgainstOneself;
    bool private _pveMode;

    uint256 private immutable _defaultRanking;
    uint256 private _matchRange = 300;
    uint256 private _matchRangePerMinute = 1;
    uint256 private _kFactor = 16;

    address public configAddress;
    mapping(uint256 => uint256) internal _waitingDecksIndex; // _waitingDecksIndex[deckId] -> index of waitingDecks
    mapping(uint256 => address) public deckOwner;
    waitingDeckData[] public waitingDecks;

    mapping(address => uint256) public playerRanking;
    address[] public leaderboardPlayers;

    constructor (uint256 defaultRanking, address _configAddress) {
        _defaultRanking = defaultRanking; // suggested: 2000
        configAddress = _configAddress;
        _allowBattleAgainstOneself = false;
    }

    function setPveMode(bool enable) public onlyAdmin {
        _pveMode = enable;
    }

    function addPveDeck(uint256 deckId) public onlyAdmin {
        require(_pveMode == true);

        // must be set, unless PvE requires no ranking (to be confirmed)
        if (playerRanking[msg.sender] == 0) {
            playerRanking[msg.sender] = _defaultRanking;
            leaderboardPlayers.push(msg.sender);
        }

        addWaitingDeck(deckId);
    }

    function removePveDeck(uint256 deckId) public onlyAdmin {
        require(_pveMode == true);
        removeWaitingDeck(deckId);
    }

    function setAllowBattleAgainstOneself(bool allow) public onlyAdmin {
        _allowBattleAgainstOneself = allow;
    }

    function setConfigAddress(address _configAddress) public onlyAdmin {
        configAddress = _configAddress;
    }

    function syncConfig() external override onlyAdmin {
        _battleAddress = PepemonConfig(configAddress).contractAddresses("PepemonBattle");
        _deckAddress = PepemonConfig(configAddress).contractAddresses("PepemonCardDeck");
        _rewardPoolAddress = PepemonConfig(configAddress).contractAddresses("PepemonRewardPool");
    }

    function setMatchRange(uint256 matchRange, uint256 matchRangePerMinute) public onlyAdmin {
        _matchRange = matchRange;
        _matchRangePerMinute = matchRangePerMinute;
    }

    function forceExit(uint256 deckId) public onlyAdmin {
        removeWaitingDeck(deckId);
    }

    /**
     * @dev Dictates the rate of change, has a direct influence on how much a player wins/loses in the ranking
     * @param kFactor Value used to calculate the rate of change in getEloRatingChange
     */
    function setKFactor(uint256 kFactor) public onlyAdmin {
        _kFactor = kFactor;
    }

    /**
     * @notice Tells whether or not this contract is operating in PvE mode. When in PvE mode, players cannot fight against
     * each other (because PvE is the opposite of PvP).
     */
    function isPveMode() public view returns(bool) {
        return _pveMode;
    }

    /**
     * @dev Returns the number of players currently on the leaderboard.
     * @return The number of players currently on the leaderboard.
     */
    function leaderboardPlayersCount() public view returns(uint256) {
        return leaderboardPlayers.length;
    }

    /**
     * @dev Returns the rankings and addresses of players on the leaderboard, within a given range of indices.
     * @param count The number of rankings to return.
     * @param offset The index of the first ranking to return.
     * @return addresses An array of player addresses corresponding to the returned rankings.
     * @return rankings An array of ranking values for the returned players.
     * @dev Requires that `count` is less than or equal to the number of players on the leaderboard minus `offset`, and that `offset` is less than the number of players on the leaderboard.
     */
    function getPlayersRankings(
        uint256 count,
        uint256 offset
    ) public view returns (address[] memory addresses, uint256[] memory rankings) {
        uint leaderboardLength = leaderboardPlayers.length;
        require(offset < leaderboardLength, "Invalid offset");
        
        if(count - offset > leaderboardLength) {
            count = leaderboardLength;
        }

        addresses = new address[](count);
        rankings = new uint256[](count);

        for (uint256 i = offset; i < offset + count; ++i) {
            if (i >= leaderboardLength) {
                break;
            }
            address playerAddress = leaderboardPlayers[i];
            addresses[i - offset] = playerAddress;
            rankings[i - offset] = playerRanking[playerAddress];
        }
        return (addresses, rankings);
    }

    /**
     * @notice Tries to initiate a battle using a specified deck.
     * @dev This function tries to initiate a battle either in PvE or PvP depending on how the contract is operating. 
     * @param deckId The Deck of who called this function
     */
    function enter(uint256 deckId) public {
        PepemonCardDeck deckContract = PepemonCardDeck(_deckAddress);
        require(msg.sender == deckContract.ownerOf(deckId), "PepemonMatchmaker: Not your deck");
        require(deckContract.getBattleCardInDeck(deckId) != 0, "PepemonMatchmaker: Invalid battlecard");

        // Make sure the player has the minimum amount of support cards required
        (,uint256 supportCardCount) = deckContract.decks(deckId);
        require(supportCardCount >= deckContract.MIN_SUPPORT_CARDS(), "PepemonMatchmaker: Not enough support cards");

        // If playerRanking is empty, set default ranking
        if (playerRanking[msg.sender] == 0) {
            playerRanking[msg.sender] = _defaultRanking;
            leaderboardPlayers.push(msg.sender);
        }

        if (_pveMode == false) {
            enterPvp(deckId);
        } else {
            enterPve(deckId);
        }
    }

    /**
     * @notice Tries to initiate a battle using a specified deck. Opponents are not other players but a set of decks added by admins.
     * @dev This function cannot be used if _pveMode is set to false.
     * @param deckId The Deck of the player
     */
    function enterPve(uint256 deckId) internal {
        // Get a matchmaking opponent
        uint256 opponentDeckId = getPveMatchmakingOpponent(deckId);

        // If one is found then start the battle, otherwise revert the transaction because someone forgot to add the opponents
        if (opponentDeckId > 0) {
            // start battle
            processMatch(deckId, opponentDeckId);
        } else {
            // should only happen if an admin forgot to add decks to this contract
            revert("PepemonMatchmaker: No PvE opponents available");
        }
    }

    /**
     * @notice Tries to initiate a battle using a specified deck. If no opponents are found, the deck
     * is placed in a wait list.
     * @dev This function cannot be used if _pveMode is set to true.
     * @param deckId The Deck of the player
     */
    function enterPvp(uint256 deckId) internal {
        // Try find matchmaking partner
        uint256 opponentDeckId = findMatchmakingOpponent(deckId);

        // If one is found then start the battle, otherwise put in a wait list
        if (opponentDeckId > 0) {
            // start battle
            processMatch(deckId, opponentDeckId);
            // prevent other matches from starting immediately after this one finishes
            removeWaitingDeck(opponentDeckId);
        } else {
            addWaitingDeck(deckId);
        }
    }

    /**
     * @notice Transfers a deck back to its owner and removes from the wait list
     * @param deckId The Deck of the owner
     */
    function exit(uint256 deckId) public {
        require(waitingDecks.length > 0 && waitingDecks[_waitingDecksIndex[deckId]].deckId != 0, "PepemonMatchmaker: Deck is not in the wait list");
        require(msg.sender == deckOwner[deckId], "PepemonMatchmaker: Not your deck");
        removeWaitingDeck(deckId);
    }

    /**
     * @notice Calculates the Elo change based on the winner's and loser's ratings.
     * @dev The returned number has 2 decimals of precision, so 1501 = 15.01 Elo change
     */
    function getEloRatingChange(uint256 winnerRating, uint256 loserRating) public view returns (uint256) {
        (uint256 change,) = Elo.ratingChange(winnerRating, loserRating, 100, _kFactor);
        return change;
    }

    /**
     * @notice Retrieves the number of waiting decks
     */
    function getWaitingCount() public view returns (uint256) {
        return waitingDecks.length;
    }

    /**
     * @notice Transfers a deck from its owner onto this contract, then adds the deck to the wait list
     * @param deckId The Deck of the owner
     */
    function addWaitingDeck(uint256 deckId) internal {
        deckOwner[deckId] = msg.sender;
        PepemonCardDeck(_deckAddress).safeTransferFrom(msg.sender, address(this), deckId, "");

        _waitingDecksIndex[deckId] = waitingDecks.length;
        waitingDecks.push(waitingDeckData(deckId, block.timestamp));
    }

    /**
     * @notice Removes a deck from the wait list
     * @dev Works by replacing the current element by the last element of the array. See https://stackoverflow.com/a/74668959
     * @param deckId The Deck of the owner
     */
    function removeWaitingDeck(uint256 deckId) internal {
        // Transfer deck back to owner
        PepemonCardDeck(_deckAddress).safeTransferFrom(address(this), deckOwner[deckId], deckId, "");
        delete deckOwner[deckId];

        uint256 lastItemIndex = waitingDecks.length - 1;

        uint256 lastDeckId = waitingDecks[lastItemIndex].deckId;

        // update the index of the item to be swapped 
        _waitingDecksIndex[lastDeckId] = _waitingDecksIndex[deckId];

        // swap the last item of the list with the one to be deleted
        waitingDecks[_waitingDecksIndex[deckId]] = waitingDecks[lastItemIndex];
        waitingDecks.pop();
        delete _waitingDecksIndex[deckId];
    }

    /**
     * @notice Performs the battle between player 1's and player 2's deck, sends a reward for the winner,
     * and ajust their ranking
     * @param player1deckId Deck of the first player
     * @param player2deckId Deck of the second player
     */
    function processMatch(uint256 player1deckId, uint256 player2deckId) internal {
        // Evaluate the battle winner
        (address winner, address loser, uint256 battleId) = doBattle(player1deckId, player2deckId);
        // Declare loser and winner
        emit BattleFinished(winner, loser, battleId);

        // Send a reward to the winner
        RewardPool(_rewardPoolAddress).sendReward(battleId, winner);

        // Adjust ranking accordingly. Change is adjusted to remove the extra precision from getEloRatingChange
        uint256 change = getEloRatingChange(playerRanking[winner], playerRanking[loser]) / 100;
        playerRanking[winner] += change;
        // Prevent underflow or rank reset if it gets below or equal to zero. Unlikely, but possible.
        if(int256(playerRanking[loser]) - int256(change) > 0) {
            playerRanking[loser] = playerRanking[loser] - change;
        } else {
            playerRanking[loser] = 1;
        }
    }

    /**
     * @dev Takes one random deckId from the waiting list, which in pve mode contains decks set by admins instead of other player's decks
     * @param deckId Deck of the current player trying to start a match, only used for added entropy
     * @return opponentDeckId Deck of the opponent, if any. 0 when none are available
     */
    function getPveMatchmakingOpponent(uint256 deckId) internal view returns (uint256) {
        if (waitingDecks.length == 0) {
            return 0;
        }
        // Take one of the random pve decks
        uint256 index = uint256(keccak256(abi.encodePacked(uint256(63), deckId, block.timestamp))) % waitingDecks.length;
        return waitingDecks[index].deckId;
    }

    /**
     * @dev Tries to find an opponent's deck based off all waiting player's ratings. The acceptable
     * difference between players ratings is increased over time by an amount defined by _matchRangePerMinute
     * @param deckId Deck of the current player trying to start a match
     * @return opponentDeckId Deck of the opponent, if found. 0 when not found
     */
    function findMatchmakingOpponent(uint256 deckId) internal view returns (uint256) {
        // Find a waiting deck with a ranking that is within matchRange
        for (uint256 i = 0; i < waitingDecks.length; ++i) {
            uint256 currentIterDeck = waitingDecks[i].deckId;

            // Skip own deck, as well as other decks of the same owner IF _allowBattleAgainstOneself is false
            if (i == deckId || (!_allowBattleAgainstOneself && msg.sender == deckOwner[currentIterDeck])) {
                continue;
            }

            // increase precision to allow increasing playerMatchRange every second
            uint256 mins = (120 * (block.timestamp - waitingDecks[i].enterTimestamp)) / 60;
            uint256 playerMatchRange = _matchRange + (mins * _matchRangePerMinute) / 120;
            // Assume deckOwner[deckId] is msg.sender, because we are not storing msg.sender in deckOwner[deckId], saving gas
            if (
                // instead of doing the following:
                // playerRanking[msg.sender] > (playerRanking[deckOwner[currentIterDeck]] - playerMatchRange) &&
                // we invert the math operation to avoid casting everything to int256, thus saving some gas
                (playerRanking[msg.sender] + playerMatchRange) > playerRanking[deckOwner[currentIterDeck]] &&
                playerRanking[msg.sender] < (playerRanking[deckOwner[currentIterDeck]] + playerMatchRange)
            ) {
                return waitingDecks[i].deckId;
            }
        }
        return 0;
    }

    /**
     * @dev Creates a new battle in the PepemonBattle contract and executes the battle logic
     * @param player1deckId Deck of the first player
     * @param player2deckId Deck of the second player
     * @return winner Address of the winner
     * @return loser Address of the loser
     * @return battleId Random seed generated for the battle
     */
    function doBattle(uint256 player1deckId, uint256 player2deckId) internal returns (address, address, uint256) {
        // Assume deckOwner[player1deckId] is msg.sender, because we are not storing msg.sender in deckOwner[player1deckId], saving gas
        (PepemonBattle.Battle memory battle, uint256 battleId) = PepemonBattle(_battleAddress).createBattle(
            msg.sender,
            player1deckId,
            deckOwner[player2deckId],
            player2deckId
        );
        (, address winner) = PepemonBattle(_battleAddress).goForBattle(battle);
        address loser = (winner == msg.sender ? deckOwner[player2deckId] : msg.sender);
        return (winner, loser, battleId);
    }
}

File 34 of 34 : FixedPointMathLib.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)
library FixedPointMathLib {
    /*//////////////////////////////////////////////////////////////
                    SIMPLIFIED FIXED POINT OPERATIONS
    //////////////////////////////////////////////////////////////*/

    uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.

    function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.
    }

    function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.
    }

    function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.
    }

    function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.
    }

    /*//////////////////////////////////////////////////////////////
                    LOW LEVEL FIXED POINT OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function mulDivDown(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 z) {
        assembly {
            // Store x * y in z for now.
            z := mul(x, y)

            // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))
            if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {
                revert(0, 0)
            }

            // Divide z by the denominator.
            z := div(z, denominator)
        }
    }

    function mulDivUp(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 z) {
        assembly {
            // Store x * y in z for now.
            z := mul(x, y)

            // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))
            if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {
                revert(0, 0)
            }

            // First, divide z - 1 by the denominator and add 1.
            // We allow z - 1 to underflow if z is 0, because we multiply the
            // end result by 0 if z is zero, ensuring we return 0 if z is zero.
            z := mul(iszero(iszero(z)), add(div(sub(z, 1), denominator), 1))
        }
    }

    function rpow(
        uint256 x,
        uint256 n,
        uint256 scalar
    ) internal pure returns (uint256 z) {
        assembly {
            switch x
            case 0 {
                switch n
                case 0 {
                    // 0 ** 0 = 1
                    z := scalar
                }
                default {
                    // 0 ** n = 0
                    z := 0
                }
            }
            default {
                switch mod(n, 2)
                case 0 {
                    // If n is even, store scalar in z for now.
                    z := scalar
                }
                default {
                    // If n is odd, store x in z for now.
                    z := x
                }

                // Shifting right by 1 is like dividing by 2.
                let half := shr(1, scalar)

                for {
                    // Shift n right by 1 before looping to halve it.
                    n := shr(1, n)
                } n {
                    // Shift n right by 1 each iteration to halve it.
                    n := shr(1, n)
                } {
                    // Revert immediately if x ** 2 would overflow.
                    // Equivalent to iszero(eq(div(xx, x), x)) here.
                    if shr(128, x) {
                        revert(0, 0)
                    }

                    // Store x squared.
                    let xx := mul(x, x)

                    // Round to the nearest number.
                    let xxRound := add(xx, half)

                    // Revert if xx + half overflowed.
                    if lt(xxRound, xx) {
                        revert(0, 0)
                    }

                    // Set x to scaled xxRound.
                    x := div(xxRound, scalar)

                    // If n is even:
                    if mod(n, 2) {
                        // Compute z * x.
                        let zx := mul(z, x)

                        // If z * x overflowed:
                        if iszero(eq(div(zx, x), z)) {
                            // Revert if x is non-zero.
                            if iszero(iszero(x)) {
                                revert(0, 0)
                            }
                        }

                        // Round to the nearest number.
                        let zxRound := add(zx, half)

                        // Revert if zx + half overflowed.
                        if lt(zxRound, zx) {
                            revert(0, 0)
                        }

                        // Return properly scaled zxRound.
                        z := div(zxRound, scalar)
                    }
                }
            }
        }
    }

    /*//////////////////////////////////////////////////////////////
                        GENERAL NUMBER UTILITIES
    //////////////////////////////////////////////////////////////*/

    function sqrt(uint256 x) internal pure returns (uint256 z) {
        assembly {
            // Start off with z at 1.
            z := 1

            // Used below to help find a nearby power of 2.
            let y := x

            // Find the lowest power of 2 that is at least sqrt(x).
            if iszero(lt(y, 0x100000000000000000000000000000000)) {
                y := shr(128, y) // Like dividing by 2 ** 128.
                z := shl(64, z) // Like multiplying by 2 ** 64.
            }
            if iszero(lt(y, 0x10000000000000000)) {
                y := shr(64, y) // Like dividing by 2 ** 64.
                z := shl(32, z) // Like multiplying by 2 ** 32.
            }
            if iszero(lt(y, 0x100000000)) {
                y := shr(32, y) // Like dividing by 2 ** 32.
                z := shl(16, z) // Like multiplying by 2 ** 16.
            }
            if iszero(lt(y, 0x10000)) {
                y := shr(16, y) // Like dividing by 2 ** 16.
                z := shl(8, z) // Like multiplying by 2 ** 8.
            }
            if iszero(lt(y, 0x100)) {
                y := shr(8, y) // Like dividing by 2 ** 8.
                z := shl(4, z) // Like multiplying by 2 ** 4.
            }
            if iszero(lt(y, 0x10)) {
                y := shr(4, y) // Like dividing by 2 ** 4.
                z := shl(2, z) // Like multiplying by 2 ** 2.
            }
            if iszero(lt(y, 0x8)) {
                // Equivalent to 2 ** z.
                z := shl(1, z)
            }

            // Shifting right by 1 is like dividing by 2.
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))

            // Compute a rounded down version of z.
            let zRoundDown := div(x, z)

            // If zRoundDown is smaller, use it.
            if lt(zRoundDown, z) {
                z := zRoundDown
            }
        }
    }

    function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
        assembly {
            // Mod x by y. Note this will return
            // 0 instead of reverting if y is zero.
            z := mod(x, y)
        }
    }

    function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {
        assembly {
            // Divide x by y. Note this will return
            // 0 instead of reverting if y is zero.
            r := div(x, y)
        }
    }

    function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        assembly {
            // Add 1 to x * y if x % y > 0. Note this will
            // return 0 instead of reverting if y is zero.
            z := add(gt(mod(x, y), 0), div(x, y))
        }
    }
}

Settings
{
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "metadata": {
    "useLiteralContent": true
  },
  "libraries": {}
}

Contract ABI

[{"inputs":[{"internalType":"uint256","name":"defaultRanking","type":"uint256"},{"internalType":"address","name":"_configAddress","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"}],"name":"AdminAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"}],"name":"AdminRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"winner","type":"address"},{"indexed":true,"internalType":"address","name":"loser","type":"address"},{"indexed":false,"internalType":"uint256","name":"battleId","type":"uint256"}],"name":"BattleFinished","type":"event"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"addAdmin","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"deckId","type":"uint256"}],"name":"addPveDeck","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"configAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"deckOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"deckId","type":"uint256"}],"name":"enter","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"deckId","type":"uint256"}],"name":"exit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"deckId","type":"uint256"}],"name":"forceExit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"winnerRating","type":"uint256"},{"internalType":"uint256","name":"loserRating","type":"uint256"}],"name":"getEloRatingChange","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"count","type":"uint256"},{"internalType":"uint256","name":"offset","type":"uint256"}],"name":"getPlayersRankings","outputs":[{"internalType":"address[]","name":"addresses","type":"address[]"},{"internalType":"uint256[]","name":"rankings","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getWaitingCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"isAdmin","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isPveMode","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"leaderboardPlayers","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"leaderboardPlayersCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256[]","name":"","type":"uint256[]"},{"internalType":"uint256[]","name":"","type":"uint256[]"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"onERC1155BatchReceived","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"onERC1155Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"onERC721Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"playerRanking","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"deckId","type":"uint256"}],"name":"removePveDeck","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceAdmin","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"allow","type":"bool"}],"name":"setAllowBattleAgainstOneself","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_configAddress","type":"address"}],"name":"setConfigAddress","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"kFactor","type":"uint256"}],"name":"setKFactor","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"matchRange","type":"uint256"},{"internalType":"uint256","name":"matchRangePerMinute","type":"uint256"}],"name":"setMatchRange","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"enable","type":"bool"}],"name":"setPveMode","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"syncConfig","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"waitingDecks","outputs":[{"internalType":"uint256","name":"deckId","type":"uint256"},{"internalType":"uint256","name":"enterTimestamp","type":"uint256"}],"stateMutability":"view","type":"function"}]

60a060405261012c600455600160055560106006553480156200002157600080fd5b5060405162002b8338038062002b838339810160408190526200004491620001c5565b8181620000513362000097565b608091909152600780546001600160a01b0319166001600160a01b039092169190911790556003805460ff60a01b191690556200008f6001620000e9565b505062000204565b620000b28160006200011c60201b62000fbe1790919060201c565b6040516001600160a01b038216907f44d6d25963f097ad14f29f06854a01f575648a1ef82f30e562ccd3889717e33990600090a250565b620000f4336200016c565b620000fe57600080fd5b60038054911515600160a81b0260ff60a81b19909216919091179055565b6001600160a01b0381166200013057600080fd5b6200013c82826200018f565b156200014757600080fd5b6001600160a01b0316600090815260209190915260409020805460ff19166001179055565b6000620001898260006200018f60201b6200100a1790919060201c565b92915050565b60006001600160a01b038216620001a557600080fd5b506001600160a01b03166000908152602091909152604090205460ff1690565b60008060408385031215620001d957600080fd5b825160208401519092506001600160a01b0381168114620001f957600080fd5b809150509250929050565b60805161295c62000227600039600081816109320152610d0e015261295c6000f3fe608060405234801561001057600080fd5b50600436106101c45760003560e01c80638a062ab7116100f9578063d671581f11610097578063e19e89ab11610071578063e19e89ab14610406578063f23a6e6114610418578063fa6285cc14610437578063fd12a4d21461045857600080fd5b8063d671581f146103b7578063d6c31871146103e0578063d8963fc4146103f357600080fd5b806396dc76c4116100d357806396dc76c414610352578063a59f3e0c14610372578063b2152aed14610385578063bc197c811461039857600080fd5b80638a062ab71461032f5780638a78c340146103425780638bad0c0a1461034a57600080fd5b806364375d2911610166578063839fcd5211610140578063839fcd52146102d657806383a12de9146102de57806386db4df7146102f1578063889f00471461030457600080fd5b806364375d291461029d57806370480275146102b05780637f8661a1146102c357600080fd5b806324d7806c116101a257806324d7806c1461023d5780633174d50714610250578063458870381461026257806359509b7a1461027557600080fd5b806301ffc9a7146101c95780630a962632146101f1578063150b7a0214610206575b600080fd5b6101dc6101d7366004612370565b61046b565b60405190151581526020015b60405180910390f35b6102046101ff36600461234e565b6104a2565b005b61022461021436600461227b565b630a85bd0160e11b949350505050565b6040516001600160e01b031990911681526020016101e8565b6101dc61024b36600461218d565b6104d2565b600a545b6040519081526020016101e8565b610204610270366004612435565b6104de565b610288610283366004612403565b6104fb565b604080519283526020830191909152016101e8565b6102546102ab366004612435565b610529565b6102046102be36600461218d565b610544565b6102046102d1366004612403565b610562565b610204610681565b6102046102ec36600461218d565b6108ac565b6102046102ff366004612403565b6108e0565b610317610312366004612403565b61099c565b6040516001600160a01b0390911681526020016101e8565b61020461033d366004612403565b6109c6565b600c54610254565b6102046109dd565b61025461036036600461218d565b600b6020526000908152604090205481565b610204610380366004612403565b6109e8565b610204610393366004612403565b610d97565b6102246103a63660046121ce565b63bc197c8160e01b95945050505050565b6103176103c5366004612403565b6009602052600090815260409020546001600160a01b031681565b600754610317906001600160a01b031681565b61020461040136600461234e565b610dc4565b600354600160a81b900460ff166101dc565b6102246104263660046122e6565b63f23a6e6160e01b95945050505050565b61044a610445366004612435565b610df4565b6040516101e8929190612614565b610204610466366004612403565b610fac565b60006001600160e01b03198216630271189760e51b148061049c57506301ffc9a760e01b6001600160e01b03198316145b92915050565b6104ab336104d2565b6104b457600080fd5b60038054911515600160a81b0260ff60a81b19909216919091179055565b600061049c818361100a565b6104e7336104d2565b6104f057600080fd5b600491909155600555565b600a818154811061050b57600080fd5b60009182526020909120600290910201805460019091015490915082565b60008061053b8484606460065461103f565b50949350505050565b61054d336104d2565b61055657600080fd5b61055f81611185565b50565b600a54158015906105a95750600081815260086020526040902054600a80549091908110610592576105926128c8565b906000526020600020906002020160000154600014155b6106125760405162461bcd60e51b815260206004820152602f60248201527f506570656d6f6e4d617463686d616b65723a204465636b206973206e6f74206960448201526e1b881d1a19481dd85a5d081b1a5cdd608a1b60648201526084015b60405180910390fd5b6000818152600960205260409020546001600160a01b031633146106785760405162461bcd60e51b815260206004820181905260248201527f506570656d6f6e4d617463686d616b65723a204e6f7420796f7572206465636b6044820152606401610609565b61055f816111c7565b61068a336104d2565b61069357600080fd5b600754604051637733e61560e11b815260206004820152600d60248201526c506570656d6f6e426174746c6560981b60448201526001600160a01b039091169063ee67cc2a9060640160206040518083038186803b1580156106f457600080fd5b505afa158015610708573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061072c91906121b1565b600180546001600160a01b0319166001600160a01b03928316179055600754604051637733e61560e11b815260206004820152600f60248201526e506570656d6f6e436172644465636b60881b604482015291169063ee67cc2a9060640160206040518083038186803b1580156107a257600080fd5b505afa1580156107b6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107da91906121b1565b600280546001600160a01b0319166001600160a01b03928316179055600754604051637733e61560e11b815260206004820152601160248201527014195c195b5bdb94995dd85c99141bdbdb607a1b604482015291169063ee67cc2a9060640160206040518083038186803b15801561085257600080fd5b505afa158015610866573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061088a91906121b1565b600380546001600160a01b0319166001600160a01b0392909216919091179055565b6108b5336104d2565b6108be57600080fd5b600780546001600160a01b0319166001600160a01b0392909216919091179055565b6108e9336104d2565b6108f257600080fd5b600354600160a81b900460ff16151560011461090d57600080fd5b336000908152600b602052604090205461099357336000818152600b602052604081207f00000000000000000000000000000000000000000000000000000000000000009055600c805460018101825591527fdf6966c971051c3d54ec59162606531493a51404a002842f56009d7e5cf4a8c70180546001600160a01b03191690911790555b61055f8161136e565b600c81815481106109ac57600080fd5b6000918252602090912001546001600160a01b0316905081565b6109cf336104d2565b6109d857600080fd5b600655565b6109e633611492565b565b6002546040516331a9108f60e11b8152600481018390526001600160a01b03909116908190636352211e9060240160206040518083038186803b158015610a2e57600080fd5b505afa158015610a42573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a6691906121b1565b6001600160a01b0316336001600160a01b031614610ac65760405162461bcd60e51b815260206004820181905260248201527f506570656d6f6e4d617463686d616b65723a204e6f7420796f7572206465636b6044820152606401610609565b6040516352637b1f60e11b8152600481018390526001600160a01b0382169063a4c6f63e9060240160206040518083038186803b158015610b0657600080fd5b505afa158015610b1a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b3e919061241c565b610b985760405162461bcd60e51b815260206004820152602560248201527f506570656d6f6e4d617463686d616b65723a20496e76616c696420626174746c6044820152641958d85c9960da1b6064820152608401610609565b60405163a090195d60e01b8152600481018390526000906001600160a01b0383169063a090195d90602401604080518083038186803b158015610bda57600080fd5b505afa158015610bee573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c129190612457565b915050816001600160a01b03166330ecf94e6040518163ffffffff1660e01b815260040160206040518083038186803b158015610c4e57600080fd5b505afa158015610c62573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c86919061241c565b811015610ce95760405162461bcd60e51b815260206004820152602b60248201527f506570656d6f6e4d617463686d616b65723a204e6f7420656e6f75676820737560448201526a70706f727420636172647360a81b6064820152608401610609565b336000908152600b6020526040902054610d6f57336000818152600b602052604081207f00000000000000000000000000000000000000000000000000000000000000009055600c805460018101825591527fdf6966c971051c3d54ec59162606531493a51404a002842f56009d7e5cf4a8c70180546001600160a01b03191690911790555b600354600160a81b900460ff16610d8e57610d89836114d4565b505050565b610d8983611507565b610da0336104d2565b610da957600080fd5b600354600160a81b900460ff16151560011461067857600080fd5b610dcd336104d2565b610dd657600080fd5b60038054911515600160a01b0260ff60a01b19909216919091179055565b600c546060908190808410610e3c5760405162461bcd60e51b815260206004820152600e60248201526d125b9d985b1a59081bd9999cd95d60921b6044820152606401610609565b80610e47858761282a565b1115610e51578094505b846001600160401b03811115610e6957610e696128de565b604051908082528060200260200182016040528015610e92578160200160208202803683370190505b509250846001600160401b03811115610ead57610ead6128de565b604051908082528060200260200182016040528015610ed6578160200160208202803683370190505b509150835b610ee586866127a0565b811015610fa357818110610ef857610fa3565b6000600c8281548110610f0d57610f0d6128c8565b6000918252602090912001546001600160a01b031690508085610f30888561282a565b81518110610f4057610f406128c8565b6001600160a01b039283166020918202929092018101919091529082166000908152600b909152604090205484610f77888561282a565b81518110610f8757610f876128c8565b602090810291909101015250610f9c81612841565b9050610edb565b50509250929050565b610fb5336104d2565b61067857600080fd5b6001600160a01b038116610fd157600080fd5b610fdb828261100a565b15610fe557600080fd5b6001600160a01b0316600090815260209190915260409020805460ff19166001179055565b60006001600160a01b03821661101f57600080fd5b506001600160a01b03166000908152602091909152604090205460ff1690565b600080612710830286861082816110585788880361105c565b8789035b905061046681106110af5760405162461bcd60e51b815260206004820152601b60248201527f526174696e6720646966666572656e636520746f6f206c6172676500000000006044820152606401610609565b81156111065761032081106111065760405162461bcd60e51b815260206004820152601b60248201527f526174696e6720646966666572656e636520746f6f206c6172676500000000006044820152606401610609565b60008060008060008661111d578561032001611123565b85610320035b9450611135600a601987046001611582565b935061114084611640565b925082606401888161115457611154612886565b0491508b8b02905081811098508861116e57818103611172565b8082035b9950505050505050505094509492505050565b611190600082610fbe565b6040516001600160a01b038216907f44d6d25963f097ad14f29f06854a01f575648a1ef82f30e562ccd3889717e33990600090a250565b600254600082815260096020526040808220549051635c46a7ef60e11b81523060048201526001600160a01b039182166024820152604481018590526080606482015260848101929092529091169063b88d4fde9060a401600060405180830381600087803b15801561123957600080fd5b505af115801561124d573d6000803e3d6000fd5b505050600082815260096020526040812080546001600160a01b0319169055600a5490915061127e9060019061282a565b90506000600a8281548110611295576112956128c8565b600091825260208083206002909202909101548583526008909152604080832054828452922091909155600a805491925090839081106112d7576112d76128c8565b9060005260206000209060020201600a60086000868152602001908152602001600020548154811061130b5761130b6128c8565b600091825260209091208254600290920201908155600191820154910155600a80548061133a5761133a6128b2565b6000828152602080822060026000199094019384020182815560010182905591909255938152600890935250506040812055565b60008181526009602052604080822080546001600160a01b031916339081179091556002549151635c46a7ef60e11b81526004810191909152306024820152604481018490526080606482015260848101929092526001600160a01b03169063b88d4fde9060a401600060405180830381600087803b1580156113f057600080fd5b505af1158015611404573d6000803e3d6000fd5b5050600a8054600085815260086020908152604080832084905580518082019091529687524290870190815260018301845592905293517fc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2a8600290950294850155517fc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2a9909301929092555050565b61149d600082611659565b6040516001600160a01b038216907fa3b62bc36326052d97ea62d63c3d60308ed4c3ea8ac079dd8499f1e9c4f80c0f90600090a250565b60006114df826116a1565b905080156114fe576114f18282611867565b6114fa816111c7565b5050565b6114fa8261136e565b600061151282611a2d565b90508015611524576114fa8282611867565b60405162461bcd60e51b815260206004820152602d60248201527f506570656d6f6e4d617463686d616b65723a204e6f20507645206f70706f6e6560448201526c6e747320617661696c61626c6560981b6064820152608401610609565b60008380156116225760018416801561159d578592506115a1565b8392505b508260011c8460011c94505b841561161c578560801c156115c157600080fd5b858602818101818110156115d457600080fd5b85900496505060018516156116115785830283878204146115fa5786156115fa57600080fd5b8181018181101561160a57600080fd5b8590049350505b8460011c94506115ad565b50611638565b8380156116325760009250611636565b8392505b505b509392505050565b600061049c61165461165461165485611ab2565b611ab2565b6001600160a01b03811661166c57600080fd5b611676828261100a565b61167f57600080fd5b6001600160a01b0316600090815260209190915260409020805460ff19169055565b6000805b600a5481101561185e576000600a82815481106116c4576116c46128c8565b9060005260206000209060020201600001549050838214806117115750600354600160a01b900460ff1615801561171157506000818152600960205260409020546001600160a01b031633145b1561171c575061184e565b6000603c600a8481548110611733576117336128c8565b90600052602060002090600202016001015442611750919061282a565b61175b9060786127cc565b61176591906127b8565b9050600060786005548361177991906127cc565b61178391906127b8565b60045461179091906127a0565b6000848152600960209081526040808320546001600160a01b03168352600b90915280822054338352912054919250906117cb9083906127a0565b11801561181557506000838152600960209081526040808320546001600160a01b03168352600b9091529020546118039082906127a0565b336000908152600b6020526040902054105b1561184a57600a848154811061182d5761182d6128c8565b906000526020600020906002020160000154945050505050919050565b5050505b61185781612841565b90506116a5565b50600092915050565b60008060006118768585611b8b565b925092509250816001600160a01b0316836001600160a01b03167f9b5363c49f40791b738dbe0ba63e6fa52ed52213cf8d4a2f3724e1389d72f14f836040516118c191815260200190565b60405180910390a36003546040516331f27b0760e01b8152600481018390526001600160a01b038581166024830152909116906331f27b0790604401600060405180830381600087803b15801561191757600080fd5b505af115801561192b573d6000803e3d6000fd5b5050506001600160a01b038085166000908152600b602052604080822054928616825281205490925060649161196091610529565b61196a91906127b8565b6001600160a01b0385166000908152600b60205260408120805492935083929091906119979084906127a0565b90915550506001600160a01b0383166000908152600b60205260408120546119c09083906127eb565b1315611a08576001600160a01b0383166000908152600b60205260409020546119ea90829061282a565b6001600160a01b0384166000908152600b6020526040902055611a25565b6001600160a01b0383166000908152600b60205260409020600190555b505050505050565b600a54600090611a3f57506000919050565b600a5460408051603f6020820152908101849052426060820152600091906080016040516020818303038152906040528051906020012060001c611a83919061285c565b9050600a8181548110611a9857611a986128c8565b906000526020600020906002020160000154915050919050565b600181600160801b8110611acb5760409190911b9060801c5b680100000000000000008110611ae65760209190911b9060401c5b6401000000008110611afd5760109190911b9060201c5b620100008110611b125760089190911b9060101c5b6101008110611b265760049190911b9060081c5b60108110611b395760029190911b9060041c5b60088110611b48578160011b91505b5080820401600190811c80830401811c80830401811c80830401811c80830401811c80830401811c80830401901c80820481811015611b85578091505b50919050565b6001546000828152600960205260408082205490516331acd38760e21b8152336004820152602481018690526001600160a01b039182166044820152606481018590529192839283928392839291169063c6b34e1c90608401611c2060405180830381600087803b158015611bff57600080fd5b505af1158015611c13573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c3791906123d4565b600154604051637cdb32cd60e01b81529294509092506000916001600160a01b0390911690637cdb32cd90611c70908690600401612698565b611c206040518083038186803b158015611c8957600080fd5b505afa158015611c9d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611cc1919061239a565b9150600090506001600160a01b0382163314611cdd5733611cf6565b6000888152600960205260409020546001600160a01b03165b9199919850919650945050505050565b600082601f830112611d1757600080fd5b611d1f61272c565b8083856103c086011115611d3257600080fd5b60005b6005811015611df85781870360c080821215611d5057600080fd5b611d58612704565b84518152602060a080601f1986011215611d7157600080fd5b611d7961272c565b9450818701518060010b8114611d8e57600080fd5b85526040611d9d888201612176565b8387015260608089015160068110611db457600080fd5b8083890152506080915081890151611dcb81612919565b90870152611dda888301612176565b90860152508181019390935286529401939190910190600101611d35565b509095945050505050565b600082601f830112611e1457600080fd5b6040516107808082018281106001600160401b0382111715611e3857611e386128de565b6040528184828101871015611e4c57600080fd5b600092505b603c831015611e7157805182526001929092019160209182019101611e51565b509195945050505050565b600082601f830112611e8d57600080fd5b6040516101008082018281106001600160401b0382111715611eb157611eb16128de565b6040528184828101871015611ec557600080fd5b600092505b6008831015611e7157805182526001929092019160209182019101611eca565b600082601f830112611efb57600080fd5b813560206001600160401b03821115611f1657611f166128de565b8160051b611f25828201612770565b838152828101908684018388018501891015611f4057600080fd5b600093505b85841015611f63578035835260019390930192918401918401611f45565b50979650505050505050565b600082601f830112611f8057600080fd5b81356001600160401b03811115611f9957611f996128de565b611fac601f8201601f1916602001612770565b818152846020838601011115611fc157600080fd5b816020850160208301376000918101602001919091529392505050565b6000611c008284031215611ff157600080fd5b611ff961274e565b90508151815261200c836020840161205d565b602082015261201f83610de0840161205d565b6040820152611ba08201516060820152611bc082015161203e81612919565b6080820152611be082015161205281612919565b60a082015292915050565b6000818303610dc081121561207157600080fd5b61207961272c565b9150825161208681612904565b8252602083810151908301526105e0603f19820112156120a557600080fd5b6120ad61274e565b604084015181526060840151602082015260c0607f19830112156120d057600080fd5b6120d861274e565b91506080840151825260a0840151602083015260c0840151604083015260e08401516060830152610100840151608083015261012084015160a0830152816040820152612129856101408601611e7c565b60608201526102408401516080820152612147856102608601611d06565b60a0820152604083015250612160836106208401611e03565b6060820152610da0820151608082015292915050565b805161ffff8116811461218857600080fd5b919050565b60006020828403121561219f57600080fd5b81356121aa81612904565b9392505050565b6000602082840312156121c357600080fd5b81516121aa81612904565b600080600080600060a086880312156121e657600080fd5b85356121f181612904565b9450602086013561220181612904565b935060408601356001600160401b038082111561221d57600080fd5b61222989838a01611eea565b9450606088013591508082111561223f57600080fd5b61224b89838a01611eea565b9350608088013591508082111561226157600080fd5b5061226e88828901611f6f565b9150509295509295909350565b6000806000806080858703121561229157600080fd5b843561229c81612904565b935060208501356122ac81612904565b92506040850135915060608501356001600160401b038111156122ce57600080fd5b6122da87828801611f6f565b91505092959194509250565b600080600080600060a086880312156122fe57600080fd5b853561230981612904565b9450602086013561231981612904565b9350604086013592506060860135915060808601356001600160401b0381111561234257600080fd5b61226e88828901611f6f565b60006020828403121561236057600080fd5b813580151581146121aa57600080fd5b60006020828403121561238257600080fd5b81356001600160e01b0319811681146121aa57600080fd5b600080611c2083850312156123ae57600080fd5b6123b88484611fde565b9150611c008301516123c981612904565b809150509250929050565b600080611c2083850312156123e857600080fd5b6123f28484611fde565b9150611c0083015190509250929050565b60006020828403121561241557600080fd5b5035919050565b60006020828403121561242e57600080fd5b5051919050565b6000806040838503121561244857600080fd5b50508035926020909101359150565b6000806040838503121561246a57600080fd5b505080516020909101519092909150565b8060005b6005811015612507578151805185526020808201519150815160010b8187015280820151604061ffff808316828a015281850151925060609150600683106124c9576124c961289c565b88820192909252830151906080906124e0836128f4565b88820192909252929092015190911660a086015260c090940193919091019060010161247f565b50505050565b8060005b603c811015612507578151845260209384019390910190600101612511565b8060005b6008811015612507578151845260209384019390910190600101612534565b60018060a01b0381511682526020810151602083015260408101518051604084015260208101516060840152604081015180516080850152602081015160a0850152604081015160c0850152606081015160e0850152608081015161010085015260a08101516101208501525060608101516125d3610140850182612530565b50608081015161024084015260a001516125f161026084018261247b565b50606081015161260561062084018261250d565b5060800151610da09190910152565b604080825283519082018190526000906020906060840190828701845b828110156126565781516001600160a01b031684529284019290840190600101612631565b5050508381038285015284518082528583019183019060005b8181101561268b5783518352928401929184019160010161266f565b5090979650505050505050565b81518152602080830151611c008301916126b490840182612553565b5060408301516126c8610de0840182612553565b506060830151611ba083015260808301516126e2816128f4565b611bc083015260a08301516126f6816128f4565b80611be08401525092915050565b604080519081016001600160401b0381118282101715612726576127266128de565b60405290565b60405160a081016001600160401b0381118282101715612726576127266128de565b60405160c081016001600160401b0381118282101715612726576127266128de565b604051601f8201601f191681016001600160401b0381118282101715612798576127986128de565b604052919050565b600082198211156127b3576127b3612870565b500190565b6000826127c7576127c7612886565b500490565b60008160001904831182151516156127e6576127e6612870565b500290565b60008083128015600160ff1b85018412161561280957612809612870565b6001600160ff1b038401831381161561282457612824612870565b50500390565b60008282101561283c5761283c612870565b500390565b600060001982141561285557612855612870565b5060010190565b60008261286b5761286b612886565b500690565b634e487b7160e01b600052601160045260246000fd5b634e487b7160e01b600052601260045260246000fd5b634e487b7160e01b600052602160045260246000fd5b634e487b7160e01b600052603160045260246000fd5b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052604160045260246000fd5b6002811061055f5761055f61289c565b6001600160a01b038116811461055f57600080fd5b6002811061055f57600080fdfea26469706673582212205233163a0fa970b177aaf0dea4137c35263b10bcf471e33fcddf95a474c7f52064736f6c6343000806003300000000000000000000000000000000000000000000000000000000000007d00000000000000000000000009460dfaad34bc55ee564a6851c58dfc390d7d4ac

Deployed Bytecode

0x608060405234801561001057600080fd5b50600436106101c45760003560e01c80638a062ab7116100f9578063d671581f11610097578063e19e89ab11610071578063e19e89ab14610406578063f23a6e6114610418578063fa6285cc14610437578063fd12a4d21461045857600080fd5b8063d671581f146103b7578063d6c31871146103e0578063d8963fc4146103f357600080fd5b806396dc76c4116100d357806396dc76c414610352578063a59f3e0c14610372578063b2152aed14610385578063bc197c811461039857600080fd5b80638a062ab71461032f5780638a78c340146103425780638bad0c0a1461034a57600080fd5b806364375d2911610166578063839fcd5211610140578063839fcd52146102d657806383a12de9146102de57806386db4df7146102f1578063889f00471461030457600080fd5b806364375d291461029d57806370480275146102b05780637f8661a1146102c357600080fd5b806324d7806c116101a257806324d7806c1461023d5780633174d50714610250578063458870381461026257806359509b7a1461027557600080fd5b806301ffc9a7146101c95780630a962632146101f1578063150b7a0214610206575b600080fd5b6101dc6101d7366004612370565b61046b565b60405190151581526020015b60405180910390f35b6102046101ff36600461234e565b6104a2565b005b61022461021436600461227b565b630a85bd0160e11b949350505050565b6040516001600160e01b031990911681526020016101e8565b6101dc61024b36600461218d565b6104d2565b600a545b6040519081526020016101e8565b610204610270366004612435565b6104de565b610288610283366004612403565b6104fb565b604080519283526020830191909152016101e8565b6102546102ab366004612435565b610529565b6102046102be36600461218d565b610544565b6102046102d1366004612403565b610562565b610204610681565b6102046102ec36600461218d565b6108ac565b6102046102ff366004612403565b6108e0565b610317610312366004612403565b61099c565b6040516001600160a01b0390911681526020016101e8565b61020461033d366004612403565b6109c6565b600c54610254565b6102046109dd565b61025461036036600461218d565b600b6020526000908152604090205481565b610204610380366004612403565b6109e8565b610204610393366004612403565b610d97565b6102246103a63660046121ce565b63bc197c8160e01b95945050505050565b6103176103c5366004612403565b6009602052600090815260409020546001600160a01b031681565b600754610317906001600160a01b031681565b61020461040136600461234e565b610dc4565b600354600160a81b900460ff166101dc565b6102246104263660046122e6565b63f23a6e6160e01b95945050505050565b61044a610445366004612435565b610df4565b6040516101e8929190612614565b610204610466366004612403565b610fac565b60006001600160e01b03198216630271189760e51b148061049c57506301ffc9a760e01b6001600160e01b03198316145b92915050565b6104ab336104d2565b6104b457600080fd5b60038054911515600160a81b0260ff60a81b19909216919091179055565b600061049c818361100a565b6104e7336104d2565b6104f057600080fd5b600491909155600555565b600a818154811061050b57600080fd5b60009182526020909120600290910201805460019091015490915082565b60008061053b8484606460065461103f565b50949350505050565b61054d336104d2565b61055657600080fd5b61055f81611185565b50565b600a54158015906105a95750600081815260086020526040902054600a80549091908110610592576105926128c8565b906000526020600020906002020160000154600014155b6106125760405162461bcd60e51b815260206004820152602f60248201527f506570656d6f6e4d617463686d616b65723a204465636b206973206e6f74206960448201526e1b881d1a19481dd85a5d081b1a5cdd608a1b60648201526084015b60405180910390fd5b6000818152600960205260409020546001600160a01b031633146106785760405162461bcd60e51b815260206004820181905260248201527f506570656d6f6e4d617463686d616b65723a204e6f7420796f7572206465636b6044820152606401610609565b61055f816111c7565b61068a336104d2565b61069357600080fd5b600754604051637733e61560e11b815260206004820152600d60248201526c506570656d6f6e426174746c6560981b60448201526001600160a01b039091169063ee67cc2a9060640160206040518083038186803b1580156106f457600080fd5b505afa158015610708573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061072c91906121b1565b600180546001600160a01b0319166001600160a01b03928316179055600754604051637733e61560e11b815260206004820152600f60248201526e506570656d6f6e436172644465636b60881b604482015291169063ee67cc2a9060640160206040518083038186803b1580156107a257600080fd5b505afa1580156107b6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107da91906121b1565b600280546001600160a01b0319166001600160a01b03928316179055600754604051637733e61560e11b815260206004820152601160248201527014195c195b5bdb94995dd85c99141bdbdb607a1b604482015291169063ee67cc2a9060640160206040518083038186803b15801561085257600080fd5b505afa158015610866573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061088a91906121b1565b600380546001600160a01b0319166001600160a01b0392909216919091179055565b6108b5336104d2565b6108be57600080fd5b600780546001600160a01b0319166001600160a01b0392909216919091179055565b6108e9336104d2565b6108f257600080fd5b600354600160a81b900460ff16151560011461090d57600080fd5b336000908152600b602052604090205461099357336000818152600b602052604081207f00000000000000000000000000000000000000000000000000000000000007d09055600c805460018101825591527fdf6966c971051c3d54ec59162606531493a51404a002842f56009d7e5cf4a8c70180546001600160a01b03191690911790555b61055f8161136e565b600c81815481106109ac57600080fd5b6000918252602090912001546001600160a01b0316905081565b6109cf336104d2565b6109d857600080fd5b600655565b6109e633611492565b565b6002546040516331a9108f60e11b8152600481018390526001600160a01b03909116908190636352211e9060240160206040518083038186803b158015610a2e57600080fd5b505afa158015610a42573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a6691906121b1565b6001600160a01b0316336001600160a01b031614610ac65760405162461bcd60e51b815260206004820181905260248201527f506570656d6f6e4d617463686d616b65723a204e6f7420796f7572206465636b6044820152606401610609565b6040516352637b1f60e11b8152600481018390526001600160a01b0382169063a4c6f63e9060240160206040518083038186803b158015610b0657600080fd5b505afa158015610b1a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b3e919061241c565b610b985760405162461bcd60e51b815260206004820152602560248201527f506570656d6f6e4d617463686d616b65723a20496e76616c696420626174746c6044820152641958d85c9960da1b6064820152608401610609565b60405163a090195d60e01b8152600481018390526000906001600160a01b0383169063a090195d90602401604080518083038186803b158015610bda57600080fd5b505afa158015610bee573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c129190612457565b915050816001600160a01b03166330ecf94e6040518163ffffffff1660e01b815260040160206040518083038186803b158015610c4e57600080fd5b505afa158015610c62573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c86919061241c565b811015610ce95760405162461bcd60e51b815260206004820152602b60248201527f506570656d6f6e4d617463686d616b65723a204e6f7420656e6f75676820737560448201526a70706f727420636172647360a81b6064820152608401610609565b336000908152600b6020526040902054610d6f57336000818152600b602052604081207f00000000000000000000000000000000000000000000000000000000000007d09055600c805460018101825591527fdf6966c971051c3d54ec59162606531493a51404a002842f56009d7e5cf4a8c70180546001600160a01b03191690911790555b600354600160a81b900460ff16610d8e57610d89836114d4565b505050565b610d8983611507565b610da0336104d2565b610da957600080fd5b600354600160a81b900460ff16151560011461067857600080fd5b610dcd336104d2565b610dd657600080fd5b60038054911515600160a01b0260ff60a01b19909216919091179055565b600c546060908190808410610e3c5760405162461bcd60e51b815260206004820152600e60248201526d125b9d985b1a59081bd9999cd95d60921b6044820152606401610609565b80610e47858761282a565b1115610e51578094505b846001600160401b03811115610e6957610e696128de565b604051908082528060200260200182016040528015610e92578160200160208202803683370190505b509250846001600160401b03811115610ead57610ead6128de565b604051908082528060200260200182016040528015610ed6578160200160208202803683370190505b509150835b610ee586866127a0565b811015610fa357818110610ef857610fa3565b6000600c8281548110610f0d57610f0d6128c8565b6000918252602090912001546001600160a01b031690508085610f30888561282a565b81518110610f4057610f406128c8565b6001600160a01b039283166020918202929092018101919091529082166000908152600b909152604090205484610f77888561282a565b81518110610f8757610f876128c8565b602090810291909101015250610f9c81612841565b9050610edb565b50509250929050565b610fb5336104d2565b61067857600080fd5b6001600160a01b038116610fd157600080fd5b610fdb828261100a565b15610fe557600080fd5b6001600160a01b0316600090815260209190915260409020805460ff19166001179055565b60006001600160a01b03821661101f57600080fd5b506001600160a01b03166000908152602091909152604090205460ff1690565b600080612710830286861082816110585788880361105c565b8789035b905061046681106110af5760405162461bcd60e51b815260206004820152601b60248201527f526174696e6720646966666572656e636520746f6f206c6172676500000000006044820152606401610609565b81156111065761032081106111065760405162461bcd60e51b815260206004820152601b60248201527f526174696e6720646966666572656e636520746f6f206c6172676500000000006044820152606401610609565b60008060008060008661111d578561032001611123565b85610320035b9450611135600a601987046001611582565b935061114084611640565b925082606401888161115457611154612886565b0491508b8b02905081811098508861116e57818103611172565b8082035b9950505050505050505094509492505050565b611190600082610fbe565b6040516001600160a01b038216907f44d6d25963f097ad14f29f06854a01f575648a1ef82f30e562ccd3889717e33990600090a250565b600254600082815260096020526040808220549051635c46a7ef60e11b81523060048201526001600160a01b039182166024820152604481018590526080606482015260848101929092529091169063b88d4fde9060a401600060405180830381600087803b15801561123957600080fd5b505af115801561124d573d6000803e3d6000fd5b505050600082815260096020526040812080546001600160a01b0319169055600a5490915061127e9060019061282a565b90506000600a8281548110611295576112956128c8565b600091825260208083206002909202909101548583526008909152604080832054828452922091909155600a805491925090839081106112d7576112d76128c8565b9060005260206000209060020201600a60086000868152602001908152602001600020548154811061130b5761130b6128c8565b600091825260209091208254600290920201908155600191820154910155600a80548061133a5761133a6128b2565b6000828152602080822060026000199094019384020182815560010182905591909255938152600890935250506040812055565b60008181526009602052604080822080546001600160a01b031916339081179091556002549151635c46a7ef60e11b81526004810191909152306024820152604481018490526080606482015260848101929092526001600160a01b03169063b88d4fde9060a401600060405180830381600087803b1580156113f057600080fd5b505af1158015611404573d6000803e3d6000fd5b5050600a8054600085815260086020908152604080832084905580518082019091529687524290870190815260018301845592905293517fc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2a8600290950294850155517fc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2a9909301929092555050565b61149d600082611659565b6040516001600160a01b038216907fa3b62bc36326052d97ea62d63c3d60308ed4c3ea8ac079dd8499f1e9c4f80c0f90600090a250565b60006114df826116a1565b905080156114fe576114f18282611867565b6114fa816111c7565b5050565b6114fa8261136e565b600061151282611a2d565b90508015611524576114fa8282611867565b60405162461bcd60e51b815260206004820152602d60248201527f506570656d6f6e4d617463686d616b65723a204e6f20507645206f70706f6e6560448201526c6e747320617661696c61626c6560981b6064820152608401610609565b60008380156116225760018416801561159d578592506115a1565b8392505b508260011c8460011c94505b841561161c578560801c156115c157600080fd5b858602818101818110156115d457600080fd5b85900496505060018516156116115785830283878204146115fa5786156115fa57600080fd5b8181018181101561160a57600080fd5b8590049350505b8460011c94506115ad565b50611638565b8380156116325760009250611636565b8392505b505b509392505050565b600061049c61165461165461165485611ab2565b611ab2565b6001600160a01b03811661166c57600080fd5b611676828261100a565b61167f57600080fd5b6001600160a01b0316600090815260209190915260409020805460ff19169055565b6000805b600a5481101561185e576000600a82815481106116c4576116c46128c8565b9060005260206000209060020201600001549050838214806117115750600354600160a01b900460ff1615801561171157506000818152600960205260409020546001600160a01b031633145b1561171c575061184e565b6000603c600a8481548110611733576117336128c8565b90600052602060002090600202016001015442611750919061282a565b61175b9060786127cc565b61176591906127b8565b9050600060786005548361177991906127cc565b61178391906127b8565b60045461179091906127a0565b6000848152600960209081526040808320546001600160a01b03168352600b90915280822054338352912054919250906117cb9083906127a0565b11801561181557506000838152600960209081526040808320546001600160a01b03168352600b9091529020546118039082906127a0565b336000908152600b6020526040902054105b1561184a57600a848154811061182d5761182d6128c8565b906000526020600020906002020160000154945050505050919050565b5050505b61185781612841565b90506116a5565b50600092915050565b60008060006118768585611b8b565b925092509250816001600160a01b0316836001600160a01b03167f9b5363c49f40791b738dbe0ba63e6fa52ed52213cf8d4a2f3724e1389d72f14f836040516118c191815260200190565b60405180910390a36003546040516331f27b0760e01b8152600481018390526001600160a01b038581166024830152909116906331f27b0790604401600060405180830381600087803b15801561191757600080fd5b505af115801561192b573d6000803e3d6000fd5b5050506001600160a01b038085166000908152600b602052604080822054928616825281205490925060649161196091610529565b61196a91906127b8565b6001600160a01b0385166000908152600b60205260408120805492935083929091906119979084906127a0565b90915550506001600160a01b0383166000908152600b60205260408120546119c09083906127eb565b1315611a08576001600160a01b0383166000908152600b60205260409020546119ea90829061282a565b6001600160a01b0384166000908152600b6020526040902055611a25565b6001600160a01b0383166000908152600b60205260409020600190555b505050505050565b600a54600090611a3f57506000919050565b600a5460408051603f6020820152908101849052426060820152600091906080016040516020818303038152906040528051906020012060001c611a83919061285c565b9050600a8181548110611a9857611a986128c8565b906000526020600020906002020160000154915050919050565b600181600160801b8110611acb5760409190911b9060801c5b680100000000000000008110611ae65760209190911b9060401c5b6401000000008110611afd5760109190911b9060201c5b620100008110611b125760089190911b9060101c5b6101008110611b265760049190911b9060081c5b60108110611b395760029190911b9060041c5b60088110611b48578160011b91505b5080820401600190811c80830401811c80830401811c80830401811c80830401811c80830401811c80830401901c80820481811015611b85578091505b50919050565b6001546000828152600960205260408082205490516331acd38760e21b8152336004820152602481018690526001600160a01b039182166044820152606481018590529192839283928392839291169063c6b34e1c90608401611c2060405180830381600087803b158015611bff57600080fd5b505af1158015611c13573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c3791906123d4565b600154604051637cdb32cd60e01b81529294509092506000916001600160a01b0390911690637cdb32cd90611c70908690600401612698565b611c206040518083038186803b158015611c8957600080fd5b505afa158015611c9d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611cc1919061239a565b9150600090506001600160a01b0382163314611cdd5733611cf6565b6000888152600960205260409020546001600160a01b03165b9199919850919650945050505050565b600082601f830112611d1757600080fd5b611d1f61272c565b8083856103c086011115611d3257600080fd5b60005b6005811015611df85781870360c080821215611d5057600080fd5b611d58612704565b84518152602060a080601f1986011215611d7157600080fd5b611d7961272c565b9450818701518060010b8114611d8e57600080fd5b85526040611d9d888201612176565b8387015260608089015160068110611db457600080fd5b8083890152506080915081890151611dcb81612919565b90870152611dda888301612176565b90860152508181019390935286529401939190910190600101611d35565b509095945050505050565b600082601f830112611e1457600080fd5b6040516107808082018281106001600160401b0382111715611e3857611e386128de565b6040528184828101871015611e4c57600080fd5b600092505b603c831015611e7157805182526001929092019160209182019101611e51565b509195945050505050565b600082601f830112611e8d57600080fd5b6040516101008082018281106001600160401b0382111715611eb157611eb16128de565b6040528184828101871015611ec557600080fd5b600092505b6008831015611e7157805182526001929092019160209182019101611eca565b600082601f830112611efb57600080fd5b813560206001600160401b03821115611f1657611f166128de565b8160051b611f25828201612770565b838152828101908684018388018501891015611f4057600080fd5b600093505b85841015611f63578035835260019390930192918401918401611f45565b50979650505050505050565b600082601f830112611f8057600080fd5b81356001600160401b03811115611f9957611f996128de565b611fac601f8201601f1916602001612770565b818152846020838601011115611fc157600080fd5b816020850160208301376000918101602001919091529392505050565b6000611c008284031215611ff157600080fd5b611ff961274e565b90508151815261200c836020840161205d565b602082015261201f83610de0840161205d565b6040820152611ba08201516060820152611bc082015161203e81612919565b6080820152611be082015161205281612919565b60a082015292915050565b6000818303610dc081121561207157600080fd5b61207961272c565b9150825161208681612904565b8252602083810151908301526105e0603f19820112156120a557600080fd5b6120ad61274e565b604084015181526060840151602082015260c0607f19830112156120d057600080fd5b6120d861274e565b91506080840151825260a0840151602083015260c0840151604083015260e08401516060830152610100840151608083015261012084015160a0830152816040820152612129856101408601611e7c565b60608201526102408401516080820152612147856102608601611d06565b60a0820152604083015250612160836106208401611e03565b6060820152610da0820151608082015292915050565b805161ffff8116811461218857600080fd5b919050565b60006020828403121561219f57600080fd5b81356121aa81612904565b9392505050565b6000602082840312156121c357600080fd5b81516121aa81612904565b600080600080600060a086880312156121e657600080fd5b85356121f181612904565b9450602086013561220181612904565b935060408601356001600160401b038082111561221d57600080fd5b61222989838a01611eea565b9450606088013591508082111561223f57600080fd5b61224b89838a01611eea565b9350608088013591508082111561226157600080fd5b5061226e88828901611f6f565b9150509295509295909350565b6000806000806080858703121561229157600080fd5b843561229c81612904565b935060208501356122ac81612904565b92506040850135915060608501356001600160401b038111156122ce57600080fd5b6122da87828801611f6f565b91505092959194509250565b600080600080600060a086880312156122fe57600080fd5b853561230981612904565b9450602086013561231981612904565b9350604086013592506060860135915060808601356001600160401b0381111561234257600080fd5b61226e88828901611f6f565b60006020828403121561236057600080fd5b813580151581146121aa57600080fd5b60006020828403121561238257600080fd5b81356001600160e01b0319811681146121aa57600080fd5b600080611c2083850312156123ae57600080fd5b6123b88484611fde565b9150611c008301516123c981612904565b809150509250929050565b600080611c2083850312156123e857600080fd5b6123f28484611fde565b9150611c0083015190509250929050565b60006020828403121561241557600080fd5b5035919050565b60006020828403121561242e57600080fd5b5051919050565b6000806040838503121561244857600080fd5b50508035926020909101359150565b6000806040838503121561246a57600080fd5b505080516020909101519092909150565b8060005b6005811015612507578151805185526020808201519150815160010b8187015280820151604061ffff808316828a015281850151925060609150600683106124c9576124c961289c565b88820192909252830151906080906124e0836128f4565b88820192909252929092015190911660a086015260c090940193919091019060010161247f565b50505050565b8060005b603c811015612507578151845260209384019390910190600101612511565b8060005b6008811015612507578151845260209384019390910190600101612534565b60018060a01b0381511682526020810151602083015260408101518051604084015260208101516060840152604081015180516080850152602081015160a0850152604081015160c0850152606081015160e0850152608081015161010085015260a08101516101208501525060608101516125d3610140850182612530565b50608081015161024084015260a001516125f161026084018261247b565b50606081015161260561062084018261250d565b5060800151610da09190910152565b604080825283519082018190526000906020906060840190828701845b828110156126565781516001600160a01b031684529284019290840190600101612631565b5050508381038285015284518082528583019183019060005b8181101561268b5783518352928401929184019160010161266f565b5090979650505050505050565b81518152602080830151611c008301916126b490840182612553565b5060408301516126c8610de0840182612553565b506060830151611ba083015260808301516126e2816128f4565b611bc083015260a08301516126f6816128f4565b80611be08401525092915050565b604080519081016001600160401b0381118282101715612726576127266128de565b60405290565b60405160a081016001600160401b0381118282101715612726576127266128de565b60405160c081016001600160401b0381118282101715612726576127266128de565b604051601f8201601f191681016001600160401b0381118282101715612798576127986128de565b604052919050565b600082198211156127b3576127b3612870565b500190565b6000826127c7576127c7612886565b500490565b60008160001904831182151516156127e6576127e6612870565b500290565b60008083128015600160ff1b85018412161561280957612809612870565b6001600160ff1b038401831381161561282457612824612870565b50500390565b60008282101561283c5761283c612870565b500390565b600060001982141561285557612855612870565b5060010190565b60008261286b5761286b612886565b500690565b634e487b7160e01b600052601160045260246000fd5b634e487b7160e01b600052601260045260246000fd5b634e487b7160e01b600052602160045260246000fd5b634e487b7160e01b600052603160045260246000fd5b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052604160045260246000fd5b6002811061055f5761055f61289c565b6001600160a01b038116811461055f57600080fd5b6002811061055f57600080fdfea26469706673582212205233163a0fa970b177aaf0dea4137c35263b10bcf471e33fcddf95a474c7f52064736f6c63430008060033

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

00000000000000000000000000000000000000000000000000000000000007d00000000000000000000000009460dfaad34bc55ee564a6851c58dfc390d7d4ac

-----Decoded View---------------
Arg [0] : defaultRanking (uint256): 2000
Arg [1] : _configAddress (address): 0x9460DfaAD34Bc55ee564A6851c58DFC390D7d4ac

-----Encoded View---------------
2 Constructor Arguments found :
Arg [0] : 00000000000000000000000000000000000000000000000000000000000007d0
Arg [1] : 0000000000000000000000009460dfaad34bc55ee564a6851c58dfc390d7d4ac


Block Transaction Gas Used Reward
view all blocks produced

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
[ Download: CSV Export  ]
[ Download: CSV Export  ]

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.