POL Price: $0.590261 (-8.58%)
 

Overview

POL Balance

Polygon PoS Chain LogoPolygon PoS Chain LogoPolygon PoS Chain Logo0 POL

POL Value

$0.00

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To

There are no matching entries

Please try again later

Parent Transaction Hash Block From To
View All Internal Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
AffiliateUtils

Compiler Version
v0.8.9+commit.e5eed63a

Optimization Enabled:
Yes with 200 runs

Other Settings:
default evmVersion
File 1 of 25 : utils.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;

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

import "./affiliates.sol";
import "./types.sol";

contract AffiliateUtils is AccessControl {
    bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");

    Affiliates public affiliatesContract;
    uint256 public maxPageSize = 100;

    constructor(Affiliates _affiliatesContract) {
        affiliatesContract = _affiliatesContract;
        _setupRole(ADMIN_ROLE, msg.sender);
    }

    /**
     * @notice Sets the maximum page size for paginated queries.
     * @param _maxPageSize The new maximum page size to be set.
     * @dev Only callable by users with the ADMIN_ROLE.
     */
    function setMaxPageSize(uint256 _maxPageSize) public onlyRole(ADMIN_ROLE) {
        maxPageSize = _maxPageSize;
    }

    /**
     * @notice Assigns the Affiliates contract to interact with.
     * @param _affiliatesContract The address of the Affiliates contract.
     * @dev Only callable by users with the ADMIN_ROLE.
     */
    function setAffiliatesContract(Affiliates _affiliatesContract) public onlyRole(ADMIN_ROLE) {
        affiliatesContract = _affiliatesContract;
    }

    /* 
    /////////////////////////////
    Utility Functions
    /////////////////////////////

        Include utility functions like getter methods.
    */ 


    /**
     * @notice Retrieves comprehensive affiliate information.
     * @param affiliateAddress The address of the affiliate.
     * @return referrer The general referrer of the affiliate.
     * @return rank The rank of the affiliate.
     * @return directReferrals The number of direct referrals made by the affiliate.
     * @return salesVolume The total sales volume generated by the affiliate.
     * @dev Pulls data from the Affiliates contract.
     */
    function getAffiliateInformation(address affiliateAddress) 
        public 
        view 
        returns (
            address referrer, 
            uint256 rank, 
            uint256 directReferrals, 
            uint256 salesVolume
        ) 
    {
        referrer = affiliatesContract.getAffiliateReferrer(affiliateAddress);
        rank = affiliatesContract.getAffiliateRank(affiliateAddress);
        directReferrals = affiliatesContract.getAffiliateDirectReferrals(affiliateAddress);
        salesVolume = affiliatesContract.getAffiliateSalesVolume(affiliateAddress);
    }

    /**
     * @notice Retrieves detailed affiliate information specific to a particular NFT.
     * @param tokenId The ID of the NFT.
     * @param affiliateAddress The address of the affiliate.
     * @return isAffiliated Indicates if the affiliate is enrolled for this NFT.
     * @return referrer The referrer for this specific NFT.
     * @return level The network depth or level of the affiliate in the referral hierarchy for this NFT.
     * @return totalRewards The total rewards earned by the affiliate for this NFT.
     * @return pendingRewards The pending rewards for the affiliate for this NFT.
     * @return referredUsers The list of users referred by this affiliate for this NFT.
     * @dev Pulls data from the Affiliates contract for NFT-specific information.
     */
    function getNFTAffiliateInformation(uint256 tokenId, address affiliateAddress) 
        public 
        view 
        returns (
            bool isAffiliated,
            address referrer,
            uint256 level,
            uint256 totalRewards,
            uint256 pendingRewards,
            address[] memory referredUsers
        ) 
    {
        // Access the affiliate's NFT data from the Affiliates contract
        SharedTypes.AffiliateNFTData memory nftAffiliateData = affiliatesContract.getAffiliateNFTData(tokenId, affiliateAddress);

        // Return the relevant information
        return (
            nftAffiliateData.isAffiliated,
            nftAffiliateData.referrer,
            nftAffiliateData.networkDepth,
            nftAffiliateData.totalRewards,
            nftAffiliateData.pendingRewards,
            nftAffiliateData.referredUsers
        );
    }

    /**
     * @notice Retrieves a list of affiliate addresses for a given page and page size.
     * @param page The page number for pagination.
     * @param pageSize The number of results per page.
     * @return results An array of affiliate addresses for the specified page.
     * @return count The total number of affiliates.
     * @dev This function provides a paginated view of all affiliates. It assumes the existence of a function in the Affiliates contract to fetch the total number of affiliates.
     */
    function getAffiliates(uint256 page, uint256 pageSize) 
        public 
        view 
        returns (
            address[] memory results, 
            uint256 count
        ) 
    {
        count = affiliatesContract.getTotalAffiliates(); // Assuming this function exists
        uint256 startIndex = (page - 1) * pageSize;
        require(startIndex < count, "Start index out of range");

        if (pageSize > maxPageSize) {
            pageSize = maxPageSize;
        }

        uint256 endIndex = startIndex + pageSize > count ? count : startIndex + pageSize;
        results = new address[](endIndex - startIndex);

        for (uint256 i = startIndex; i < endIndex; i++) {
            results[i - startIndex] = affiliatesContract.getAffiliateAtIndex(i); // Assuming this function exists
        }

        return (results, count);
    }

    /**
     * @notice Retrieves all rank criteria defined in the Affiliates contract.
     * @return criterias An array of RankCriteria, detailing the requirements for each rank.
     * @dev This function fetches the complete list of rank criteria, including required direct referrals and sales volume for each rank.
     */
    function getAllRankCriterias() 
        public view 
        returns (SharedTypes.RankCriteria[] memory
    ) 
    {
        uint256 count = affiliatesContract.rankCriteriasCount();
        SharedTypes.RankCriteria[] memory criterias = new SharedTypes.RankCriteria[](count);

        for (uint256 i = 0; i < count; i++) {
            criterias[i] = affiliatesContract.getRankCriteria(i);
        }

        return criterias;
    }

    /**
     * @notice Retrieves a paginated list of NFT-specific affiliate data for affiliates referred by a specific referrer.
     * @param tokenId The token ID for which to fetch affiliate data.
     * @param rootAffiliate The root affiliate (referrer) whose referrals are to be fetched.
     * @param page The page number for pagination.
     * @param pageSize The number of results per page.
     * @return paginatedAffiliates An array of AffiliateNFTData, representing the NFT-specific data of affiliates referred by the root affiliate.
     * @return totalReferred The total number of affiliates referred by the root affiliate.
     * @dev This function provides a paginated view of NFT-specific affiliate data for a given referrer.
     */
    function getNftAffiliatesForReferrer(uint256 tokenId, address rootAffiliate, uint256 page, uint256 pageSize) 
        public 
        view 
        returns (SharedTypes.AffiliateNFTData[] memory, uint256) 
    {
        SharedTypes.AffiliateNFTData memory rootAffiliateData = affiliatesContract.getAffiliateNFTData(tokenId, rootAffiliate);
        address[] memory referredUsers = rootAffiliateData.referredUsers;

        uint256 totalReferred = referredUsers.length;
        uint256 startIndex = (page - 1) * pageSize;
        require(startIndex < totalReferred, "Start index out of range");

        if (pageSize > maxPageSize) {
            pageSize = maxPageSize;
        }

        uint256 endIndex = startIndex + pageSize > totalReferred ? totalReferred : startIndex + pageSize;
        SharedTypes.AffiliateNFTData[] memory paginatedAffiliates = new SharedTypes.AffiliateNFTData[](endIndex - startIndex);

        for (uint256 i = startIndex; i < endIndex; i++) {
            SharedTypes.AffiliateNFTData memory affiliateData = affiliatesContract.getAffiliateNFTData(tokenId, referredUsers[i]);
            paginatedAffiliates[i - startIndex] = affiliateData;
        }

        return (paginatedAffiliates, totalReferred);
    }

    /**
     * @notice Retrieves the referral chain for a specific affiliate in the context of a specific NFT.
     * @param tokenId The token ID related to the affiliate data.
     * @param affiliateAddress The address of the affiliate whose referral chain is to be fetched.
     * @return referralChain An array of addresses representing the referral chain of the affiliate for the specified NFT.
     * @dev This function returns the direct referrals made by an affiliate for a specific NFT.
     */
    function getNFTAffiliateReferralsChain(uint256 tokenId, address affiliateAddress) 
        public 
        view 
        returns (address[] memory referralChain) 
    {
        // Get the AffiliateData for the given affiliateAddress

        // Get the AffiliateNFTData for the given tokenId
        SharedTypes.AffiliateNFTData memory nftAffiliateData = affiliatesContract.getAffiliateNFTData(tokenId, affiliateAddress);

        // Return the referredUsers array from the NFT data
        return nftAffiliateData.referredUsers;
    }
}

File 2 of 25 : AccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)

pragma solidity ^0.8.0;

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

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

    mapping(bytes32 => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

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

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

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

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

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

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

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

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

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

        _revokeRole(role, account);
    }

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

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

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

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

File 3 of 25 : IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)

pragma solidity ^0.8.0;

/**
 * @dev External interface of AccessControl declared to support ERC165 detection.
 */
interface IAccessControl {
    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     *
     * _Available since v3.1._
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call, an admin role
     * bearer except when using {AccessControl-_setupRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

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

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

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     */
    function renounceRole(bytes32 role, address account) external;
}

File 4 of 25 : PaymentSplitter.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (finance/PaymentSplitter.sol)

pragma solidity ^0.8.0;

import "../token/ERC20/utils/SafeERC20.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";

/**
 * @title PaymentSplitter
 * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware
 * that the Ether will be split in this way, since it is handled transparently by the contract.
 *
 * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each
 * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim
 * an amount proportional to the percentage of total shares they were assigned. The distribution of shares is set at the
 * time of contract deployment and can't be updated thereafter.
 *
 * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the
 * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release}
 * function.
 *
 * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and
 * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you
 * to run tests before sending real value to this contract.
 */
contract PaymentSplitter is Context {
    event PayeeAdded(address account, uint256 shares);
    event PaymentReleased(address to, uint256 amount);
    event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount);
    event PaymentReceived(address from, uint256 amount);

    uint256 private _totalShares;
    uint256 private _totalReleased;

    mapping(address => uint256) private _shares;
    mapping(address => uint256) private _released;
    address[] private _payees;

    mapping(IERC20 => uint256) private _erc20TotalReleased;
    mapping(IERC20 => mapping(address => uint256)) private _erc20Released;

    /**
     * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at
     * the matching position in the `shares` array.
     *
     * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no
     * duplicates in `payees`.
     */
    constructor(address[] memory payees, uint256[] memory shares_) payable {
        require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch");
        require(payees.length > 0, "PaymentSplitter: no payees");

        for (uint256 i = 0; i < payees.length; i++) {
            _addPayee(payees[i], shares_[i]);
        }
    }

    /**
     * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully
     * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the
     * reliability of the events, and not the actual splitting of Ether.
     *
     * To learn more about this see the Solidity documentation for
     * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
     * functions].
     */
    receive() external payable virtual {
        emit PaymentReceived(_msgSender(), msg.value);
    }

    /**
     * @dev Getter for the total shares held by payees.
     */
    function totalShares() public view returns (uint256) {
        return _totalShares;
    }

    /**
     * @dev Getter for the total amount of Ether already released.
     */
    function totalReleased() public view returns (uint256) {
        return _totalReleased;
    }

    /**
     * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20
     * contract.
     */
    function totalReleased(IERC20 token) public view returns (uint256) {
        return _erc20TotalReleased[token];
    }

    /**
     * @dev Getter for the amount of shares held by an account.
     */
    function shares(address account) public view returns (uint256) {
        return _shares[account];
    }

    /**
     * @dev Getter for the amount of Ether already released to a payee.
     */
    function released(address account) public view returns (uint256) {
        return _released[account];
    }

    /**
     * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an
     * IERC20 contract.
     */
    function released(IERC20 token, address account) public view returns (uint256) {
        return _erc20Released[token][account];
    }

    /**
     * @dev Getter for the address of the payee number `index`.
     */
    function payee(uint256 index) public view returns (address) {
        return _payees[index];
    }

    /**
     * @dev Getter for the amount of payee's releasable Ether.
     */
    function releasable(address account) public view returns (uint256) {
        uint256 totalReceived = address(this).balance + totalReleased();
        return _pendingPayment(account, totalReceived, released(account));
    }

    /**
     * @dev Getter for the amount of payee's releasable `token` tokens. `token` should be the address of an
     * IERC20 contract.
     */
    function releasable(IERC20 token, address account) public view returns (uint256) {
        uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token);
        return _pendingPayment(account, totalReceived, released(token, account));
    }

    /**
     * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
     * total shares and their previous withdrawals.
     */
    function release(address payable account) public virtual {
        require(_shares[account] > 0, "PaymentSplitter: account has no shares");

        uint256 payment = releasable(account);

        require(payment != 0, "PaymentSplitter: account is not due payment");

        // _totalReleased is the sum of all values in _released.
        // If "_totalReleased += payment" does not overflow, then "_released[account] += payment" cannot overflow.
        _totalReleased += payment;
        unchecked {
            _released[account] += payment;
        }

        Address.sendValue(account, payment);
        emit PaymentReleased(account, payment);
    }

    /**
     * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their
     * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20
     * contract.
     */
    function release(IERC20 token, address account) public virtual {
        require(_shares[account] > 0, "PaymentSplitter: account has no shares");

        uint256 payment = releasable(token, account);

        require(payment != 0, "PaymentSplitter: account is not due payment");

        // _erc20TotalReleased[token] is the sum of all values in _erc20Released[token].
        // If "_erc20TotalReleased[token] += payment" does not overflow, then "_erc20Released[token][account] += payment"
        // cannot overflow.
        _erc20TotalReleased[token] += payment;
        unchecked {
            _erc20Released[token][account] += payment;
        }

        SafeERC20.safeTransfer(token, account, payment);
        emit ERC20PaymentReleased(token, account, payment);
    }

    /**
     * @dev internal logic for computing the pending payment of an `account` given the token historical balances and
     * already released amounts.
     */
    function _pendingPayment(
        address account,
        uint256 totalReceived,
        uint256 alreadyReleased
    ) private view returns (uint256) {
        return (totalReceived * _shares[account]) / _totalShares - alreadyReleased;
    }

    /**
     * @dev Add a new payee to the contract.
     * @param account The address of the payee to add.
     * @param shares_ The number of shares owned by the payee.
     */
    function _addPayee(address account, uint256 shares_) private {
        require(account != address(0), "PaymentSplitter: account is the zero address");
        require(shares_ > 0, "PaymentSplitter: shares are 0");
        require(_shares[account] == 0, "PaymentSplitter: account already has shares");

        _payees.push(account);
        _shares[account] = shares_;
        _totalShares = _totalShares + shares_;
        emit PayeeAdded(account, shares_);
    }
}

File 5 of 25 : IERC2981.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)

pragma solidity ^0.8.0;

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

/**
 * @dev Interface for the NFT Royalty Standard.
 *
 * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
 * support for royalty payments across all NFT marketplaces and ecosystem participants.
 *
 * _Available since v4.5._
 */
interface IERC2981 is IERC165 {
    /**
     * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
     * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.
     */
    function royaltyInfo(uint256 tokenId, uint256 salePrice)
        external
        view
        returns (address receiver, uint256 royaltyAmount);
}

File 6 of 25 : ERC1155.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC1155/ERC1155.sol)

pragma solidity ^0.8.0;

import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./extensions/IERC1155MetadataURI.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/introspection/ERC165.sol";

/**
 * @dev Implementation of the basic standard multi-token.
 * See https://eips.ethereum.org/EIPS/eip-1155
 * Originally based on code by Enjin: https://github.com/enjin/erc-1155
 *
 * _Available since v3.1._
 */
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
    using Address for address;

    // Mapping from token ID to account balances
    mapping(uint256 => mapping(address => uint256)) private _balances;

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

    // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
    string private _uri;

    /**
     * @dev See {_setURI}.
     */
    constructor(string memory uri_) {
        _setURI(uri_);
    }

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

    /**
     * @dev See {IERC1155MetadataURI-uri}.
     *
     * This implementation returns the same URI for *all* token types. It relies
     * on the token type ID substitution mechanism
     * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
     *
     * Clients calling this function must replace the `\{id\}` substring with the
     * actual token type ID.
     */
    function uri(uint256) public view virtual override returns (string memory) {
        return _uri;
    }

    /**
     * @dev See {IERC1155-balanceOf}.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
        require(account != address(0), "ERC1155: address zero is not a valid owner");
        return _balances[id][account];
    }

    /**
     * @dev See {IERC1155-balanceOfBatch}.
     *
     * Requirements:
     *
     * - `accounts` and `ids` must have the same length.
     */
    function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
        public
        view
        virtual
        override
        returns (uint256[] memory)
    {
        require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");

        uint256[] memory batchBalances = new uint256[](accounts.length);

        for (uint256 i = 0; i < accounts.length; ++i) {
            batchBalances[i] = balanceOf(accounts[i], ids[i]);
        }

        return batchBalances;
    }

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

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

    /**
     * @dev See {IERC1155-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 id,
        uint256 amount,
        bytes memory data
    ) public virtual override {
        require(
            from == _msgSender() || isApprovedForAll(from, _msgSender()),
            "ERC1155: caller is not token owner or approved"
        );
        _safeTransferFrom(from, to, id, amount, data);
    }

    /**
     * @dev See {IERC1155-safeBatchTransferFrom}.
     */
    function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) public virtual override {
        require(
            from == _msgSender() || isApprovedForAll(from, _msgSender()),
            "ERC1155: caller is not token owner or approved"
        );
        _safeBatchTransferFrom(from, to, ids, amounts, data);
    }

    /**
     * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `from` must have a balance of tokens of type `id` of at least `amount`.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function _safeTransferFrom(
        address from,
        address to,
        uint256 id,
        uint256 amount,
        bytes memory data
    ) internal virtual {
        require(to != address(0), "ERC1155: transfer to the zero address");

        address operator = _msgSender();
        uint256[] memory ids = _asSingletonArray(id);
        uint256[] memory amounts = _asSingletonArray(amount);

        _beforeTokenTransfer(operator, from, to, ids, amounts, data);

        uint256 fromBalance = _balances[id][from];
        require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
        unchecked {
            _balances[id][from] = fromBalance - amount;
        }
        _balances[id][to] += amount;

        emit TransferSingle(operator, from, to, id, amount);

        _afterTokenTransfer(operator, from, to, ids, amounts, data);

        _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
    }

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function _safeBatchTransferFrom(
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) internal virtual {
        require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
        require(to != address(0), "ERC1155: transfer to the zero address");

        address operator = _msgSender();

        _beforeTokenTransfer(operator, from, to, ids, amounts, data);

        for (uint256 i = 0; i < ids.length; ++i) {
            uint256 id = ids[i];
            uint256 amount = amounts[i];

            uint256 fromBalance = _balances[id][from];
            require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
            unchecked {
                _balances[id][from] = fromBalance - amount;
            }
            _balances[id][to] += amount;
        }

        emit TransferBatch(operator, from, to, ids, amounts);

        _afterTokenTransfer(operator, from, to, ids, amounts, data);

        _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
    }

    /**
     * @dev Sets a new URI for all token types, by relying on the token type ID
     * substitution mechanism
     * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
     *
     * By this mechanism, any occurrence of the `\{id\}` substring in either the
     * URI or any of the amounts in the JSON file at said URI will be replaced by
     * clients with the token type ID.
     *
     * For example, the `https://token-cdn-domain/\{id\}.json` URI would be
     * interpreted by clients as
     * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
     * for token type ID 0x4cce0.
     *
     * See {uri}.
     *
     * Because these URIs cannot be meaningfully represented by the {URI} event,
     * this function emits no events.
     */
    function _setURI(string memory newuri) internal virtual {
        _uri = newuri;
    }

    /**
     * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function _mint(
        address to,
        uint256 id,
        uint256 amount,
        bytes memory data
    ) internal virtual {
        require(to != address(0), "ERC1155: mint to the zero address");

        address operator = _msgSender();
        uint256[] memory ids = _asSingletonArray(id);
        uint256[] memory amounts = _asSingletonArray(amount);

        _beforeTokenTransfer(operator, address(0), to, ids, amounts, data);

        _balances[id][to] += amount;
        emit TransferSingle(operator, address(0), to, id, amount);

        _afterTokenTransfer(operator, address(0), to, ids, amounts, data);

        _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
    }

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - `ids` and `amounts` must have the same length.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function _mintBatch(
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) internal virtual {
        require(to != address(0), "ERC1155: mint to the zero address");
        require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");

        address operator = _msgSender();

        _beforeTokenTransfer(operator, address(0), to, ids, amounts, data);

        for (uint256 i = 0; i < ids.length; i++) {
            _balances[ids[i]][to] += amounts[i];
        }

        emit TransferBatch(operator, address(0), to, ids, amounts);

        _afterTokenTransfer(operator, address(0), to, ids, amounts, data);

        _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
    }

    /**
     * @dev Destroys `amount` tokens of token type `id` from `from`
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `from` must have at least `amount` tokens of token type `id`.
     */
    function _burn(
        address from,
        uint256 id,
        uint256 amount
    ) internal virtual {
        require(from != address(0), "ERC1155: burn from the zero address");

        address operator = _msgSender();
        uint256[] memory ids = _asSingletonArray(id);
        uint256[] memory amounts = _asSingletonArray(amount);

        _beforeTokenTransfer(operator, from, address(0), ids, amounts, "");

        uint256 fromBalance = _balances[id][from];
        require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
        unchecked {
            _balances[id][from] = fromBalance - amount;
        }

        emit TransferSingle(operator, from, address(0), id, amount);

        _afterTokenTransfer(operator, from, address(0), ids, amounts, "");
    }

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - `ids` and `amounts` must have the same length.
     */
    function _burnBatch(
        address from,
        uint256[] memory ids,
        uint256[] memory amounts
    ) internal virtual {
        require(from != address(0), "ERC1155: burn from the zero address");
        require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");

        address operator = _msgSender();

        _beforeTokenTransfer(operator, from, address(0), ids, amounts, "");

        for (uint256 i = 0; i < ids.length; i++) {
            uint256 id = ids[i];
            uint256 amount = amounts[i];

            uint256 fromBalance = _balances[id][from];
            require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
            unchecked {
                _balances[id][from] = fromBalance - amount;
            }
        }

        emit TransferBatch(operator, from, address(0), ids, amounts);

        _afterTokenTransfer(operator, from, address(0), ids, amounts, "");
    }

    /**
     * @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, "ERC1155: setting approval status for self");
        _operatorApprovals[owner][operator] = approved;
        emit ApprovalForAll(owner, operator, approved);
    }

    /**
     * @dev Hook that is called before any token transfer. This includes minting
     * and burning, as well as batched variants.
     *
     * The same hook is called on both single and batched variants. For single
     * transfers, the length of the `ids` and `amounts` arrays will be 1.
     *
     * Calling conditions (for each `id` and `amount` pair):
     *
     * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * of token type `id` will be  transferred to `to`.
     * - When `from` is zero, `amount` tokens of token type `id` will be minted
     * for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
     * will be burned.
     * - `from` and `to` are never both zero.
     * - `ids` and `amounts` have the same, non-zero length.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(
        address operator,
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) internal virtual {}

    /**
     * @dev Hook that is called after any token transfer. This includes minting
     * and burning, as well as batched variants.
     *
     * The same hook is called on both single and batched variants. For single
     * transfers, the length of the `id` and `amount` arrays will be 1.
     *
     * Calling conditions (for each `id` and `amount` pair):
     *
     * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * of token type `id` will be  transferred to `to`.
     * - When `from` is zero, `amount` tokens of token type `id` will be minted
     * for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
     * will be burned.
     * - `from` and `to` are never both zero.
     * - `ids` and `amounts` have the same, non-zero length.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(
        address operator,
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) internal virtual {}

    function _doSafeTransferAcceptanceCheck(
        address operator,
        address from,
        address to,
        uint256 id,
        uint256 amount,
        bytes memory data
    ) private {
        if (to.isContract()) {
            try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
                if (response != IERC1155Receiver.onERC1155Received.selector) {
                    revert("ERC1155: ERC1155Receiver rejected tokens");
                }
            } catch Error(string memory reason) {
                revert(reason);
            } catch {
                revert("ERC1155: transfer to non-ERC1155Receiver implementer");
            }
        }
    }

    function _doSafeBatchTransferAcceptanceCheck(
        address operator,
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) private {
        if (to.isContract()) {
            try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
                bytes4 response
            ) {
                if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
                    revert("ERC1155: ERC1155Receiver rejected tokens");
                }
            } catch Error(string memory reason) {
                revert(reason);
            } catch {
                revert("ERC1155: transfer to non-ERC1155Receiver implementer");
            }
        }
    }

    function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
        uint256[] memory array = new uint256[](1);
        array[0] = element;

        return array;
    }
}

File 7 of 25 : ERC1155Supply.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC1155/extensions/ERC1155Supply.sol)

pragma solidity ^0.8.0;

import "../ERC1155.sol";

/**
 * @dev Extension of ERC1155 that adds tracking of total supply per id.
 *
 * Useful for scenarios where Fungible and Non-fungible tokens have to be
 * clearly identified. Note: While a totalSupply of 1 might mean the
 * corresponding is an NFT, there is no guarantees that no other token with the
 * same id are not going to be minted.
 */
abstract contract ERC1155Supply is ERC1155 {
    mapping(uint256 => uint256) private _totalSupply;

    /**
     * @dev Total amount of tokens in with a given id.
     */
    function totalSupply(uint256 id) public view virtual returns (uint256) {
        return _totalSupply[id];
    }

    /**
     * @dev Indicates whether any token exist with a given id, or not.
     */
    function exists(uint256 id) public view virtual returns (bool) {
        return ERC1155Supply.totalSupply(id) > 0;
    }

    /**
     * @dev See {ERC1155-_beforeTokenTransfer}.
     */
    function _beforeTokenTransfer(
        address operator,
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) internal virtual override {
        super._beforeTokenTransfer(operator, from, to, ids, amounts, data);

        if (from == address(0)) {
            for (uint256 i = 0; i < ids.length; ++i) {
                _totalSupply[ids[i]] += amounts[i];
            }
        }

        if (to == address(0)) {
            for (uint256 i = 0; i < ids.length; ++i) {
                uint256 id = ids[i];
                uint256 amount = amounts[i];
                uint256 supply = _totalSupply[id];
                require(supply >= amount, "ERC1155: burn amount exceeds totalSupply");
                unchecked {
                    _totalSupply[id] = supply - amount;
                }
            }
        }
    }
}

File 8 of 25 : IERC1155MetadataURI.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)

pragma solidity ^0.8.0;

import "../IERC1155.sol";

/**
 * @dev Interface of the optional ERC1155MetadataExtension interface, as defined
 * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
 *
 * _Available since v3.1._
 */
interface IERC1155MetadataURI is IERC1155 {
    /**
     * @dev Returns the URI for token type `id`.
     *
     * If the `\{id\}` substring is present in the URI, it must be replaced by
     * clients with the actual token type ID.
     */
    function uri(uint256 id) external view returns (string memory);
}

File 9 of 25 : IERC1155.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/IERC1155.sol)

pragma solidity ^0.8.0;

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

/**
 * @dev Required interface of an ERC1155 compliant contract, as defined in the
 * https://eips.ethereum.org/EIPS/eip-1155[EIP].
 *
 * _Available since v3.1._
 */
interface IERC1155 is IERC165 {
    /**
     * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
     */
    event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);

    /**
     * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
     * transfers.
     */
    event TransferBatch(
        address indexed operator,
        address indexed from,
        address indexed to,
        uint256[] ids,
        uint256[] values
    );

    /**
     * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
     * `approved`.
     */
    event ApprovalForAll(address indexed account, address indexed operator, bool approved);

    /**
     * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
     *
     * If an {URI} event was emitted for `id`, the standard
     * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
     * returned by {IERC1155MetadataURI-uri}.
     */
    event URI(string value, uint256 indexed id);

    /**
     * @dev Returns the amount of tokens of token type `id` owned by `account`.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function balanceOf(address account, uint256 id) external view returns (uint256);

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
     *
     * Requirements:
     *
     * - `accounts` and `ids` must have the same length.
     */
    function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
        external
        view
        returns (uint256[] memory);

    /**
     * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
     *
     * Emits an {ApprovalForAll} event.
     *
     * Requirements:
     *
     * - `operator` cannot be the caller.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
     *
     * See {setApprovalForAll}.
     */
    function isApprovedForAll(address account, address operator) external view returns (bool);

    /**
     * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
     * - `from` must have a balance of tokens of type `id` of at least `amount`.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 id,
        uint256 amount,
        bytes calldata data
    ) external;

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - `ids` and `amounts` must have the same length.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] calldata ids,
        uint256[] calldata amounts,
        bytes calldata data
    ) external;
}

File 10 of 25 : 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 11 of 25 : draft-IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

File 12 of 25 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

File 13 of 25 : SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/draft-IERC20Permit.sol";
import "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    function safeTransfer(
        IERC20 token,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    function safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    function safeIncreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        uint256 newAllowance = token.allowance(address(this), spender) + value;
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    function safeDecreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            uint256 newAllowance = oldAllowance - value;
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
        }
    }

    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        if (returndata.length > 0) {
            // Return data is optional
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}

File 14 of 25 : Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.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
     * ====
     *
     * [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://diligence.consensys.net/posts/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.5.11/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 15 of 25 : Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

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

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

File 16 of 25 : 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 17 of 25 : 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 18 of 25 : Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.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) {
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1);

            ///////////////////////////////////////////////
            // 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 10, 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 * 8) < value ? 1 : 0);
        }
    }
}

File 19 of 25 : SafeMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.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 20 of 25 : Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

import "./math/Math.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 `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);
    }
}

File 21 of 25 : affiliates.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;

import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";

import './types.sol';
import "../tickets/registry.sol";

/*
    The contract supports rank progression based on the number of direct referrals 
    and the sales volume generated by each referrer.

    The `RankCriteria` struct is used to define the criteria for each rank, and the `rankCriterias` 
    array stores these structs.

    The contract has been updated to include the following new functions:
    1. `updateSalesVolume(address referrer, uint256 amount)` - Updates the sales volume for a referrer.
    2. `checkEligibilityForRankUp(address referrer)` - Checks if a referrer is eligible for a rank up based on the rank criteria.
    3. `rankUp(address referrer)` - Performs a rank up for a referrer if they are eligible.
    
    Additionally, the `handleAffiliateProgram` function has been updated to update the sales volume for each 
    referrer in the hierarchy when processing rewards.
 */

/// @custom:security-contact [email protected]
contract Affiliates is AccessControl {
    using SafeMath for uint256;

    /* 
    /////////////////////////////////
    1. Role Declarations 
    /////////////////////////////////

      - Define a constant role for the booth role
      - Define a constant role for the affiliates role

    */ 

    bytes32 public constant BOOTH_ROLE = keccak256("BOOTH_ROLE");
    
    /* 
    /////////////////////////////
    2. Structs and State Variables
    /////////////////////////////

        - referralRewardBasisPoints: The percentage of the reward to be given to referrers at each level and rank (in basis points, e.g., 1000 = 10%)
        - referrers: The mapping to store referrer addresses
        - referrerRanks: The mapping to store the rank of each referrer
        - directReferrals: The mapping to store the number of direct referrals for each referrer
        - salesVolume: The mapping to store the sales volume for each referrer
        - rankCriterias: The mapping to store RankCriteria structs defining the criteria for each rank
        - rankCriteriasCount: The total number of rank criterias
        - maxDepth: The maximum depth of the MLM hierarchy
        - affiliates: Array to store all affiliate addresses
        - nftAffiliates: Map each NFT token ID to a mapping of addresses to their affiliate data
        - nftAffiliateCounts: 
        - nftReferralRewards: 
    */ 

    TicketRegistry private ticketRegistry;
    uint256 public maxDepth;
    uint256[][] public referralRewardBasisPoints;
    uint256 public rankCriteriasCount;
    mapping(uint256 => SharedTypes.RankCriteria) public rankCriterias;
    mapping(address => SharedTypes.AffiliateData) public affiliates;
    mapping(uint256 => uint256) public nftAffiliateCounts;
    uint256 public affiliatesCount;
    address[] public affiliateAddresses;

    /* 
    /////////////////////////////
    3. Constructor and events
    /////////////////////////////

        The constructor initializes the contract's state.
      
        With this structure, affiliates are incentivized to improve their rank and work on their direct
        referrals as they receive higher rewards for higher ranks and closer relationships.
        At the same time, the maximum reward an affiliate can get from a single sale is capped at 25 %,
        ensuring a balance in the reward distribution.
        Level 1: Bronze 8%, Silver 10%, Gold 12%, Platinum 14%, Diamond 16%
        Level 2: Bronze 6%, Silver 8%,  Gold 10%, Platinum 12%, Diamond 14%
        Level 3: Bronze 4%, Silver 6%,  Gold 8%,  Platinum 10%, Diamond 12%
        Level 4: Bronze 2%, Silver 4%,  Gold 6%,  Platinum 8%,  Diamond 10%
        Level 5: Bronze 1%, Silver 2%,  Gold 4%,  Platinum 6%,  Diamond 8%
        
        // Define the rewrd bsis points array
        const referralRewardBasisPointsArray = [
            [1000, 1100, 1200, 1300, 1400],  Level 1: Bronze 10%, Silver 11%, Gold 12%, Platinum 13%, Diamond 14%
            [700,  850,  1000, 1150, 1300],  Level 2: Increase by a factor that reduces the gap slightly but still provides incentive for higher ranks
            [500,  650,  800,  950,  1100],  Level 3: Same as above, continue reducing the gap
            [300,  450,  600,  750,  900],   Level 4: Continue the trend
            [150,  300,  450,  600,  750]    Level 5: By this level, the difference between ranks narrows as the depth increases
        ];

        // Define the rank criteria
        const rankCriteriasArray = [
            {requiredDirectReferrals: 5, requiredSalesVolume: ethers.utils.parseEther("1")},
            {requiredDirectReferrals: 10, requiredSalesVolume: ethers.utils.parseEther("5")},
            {requiredDirectReferrals: 20, requiredSalesVolume: ethers.utils.parseEther("10")},
            {requiredDirectReferrals: 50, requiredSalesVolume: ethers.utils.parseEther("20")},
            {requiredDirectReferrals: 100, requiredSalesVolume: ethers.utils.parseEther("50")}
        ];

        maxDepth is the number of referrers an affiliate can have in their chain
    */ 

    // Constructor
    constructor(uint256[][] memory _referralRewardBasisPoints, SharedTypes.RankCriteria[] memory _rankCriterias, uint256 _maxDepth, address _ticketRegistryAddress) {
        referralRewardBasisPoints = _referralRewardBasisPoints;
        for (uint256 i = 0; i < _rankCriterias.length; i++) {
            rankCriterias[i] = _rankCriterias[i];
        }
        rankCriteriasCount = _rankCriterias.length;
        maxDepth = _maxDepth;
        ticketRegistry = TicketRegistry(_ticketRegistryAddress);
        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
    }
    
    event AffiliateEnrolledForNFT(uint256 indexed tokenId, address indexed affiliateAddress, address referrerAddress);
    event SalesVolumeUpdated(address indexed referrer, uint256 newSalesVolume);
    event RankUp(address indexed referrer, uint256 newRank);
    event ReferralRewardUpdated(uint256 level, uint256 rank, uint256 reward);
    event ReferrerRankUpdated(address indexed referrer, uint256 rank);
    event RankCriteriaUpdated(uint256 indexed rank, SharedTypes.RankCriteria newCriteria);

    /* 
    /////////////////////////////
    4. Role-Based Functionality
    /////////////////////////////

      Group functions by the roles that can call them. 
      For example, all functions that require BOOTH_ROLE should be together.
    */ 

    /**
     * @notice Updates the maximum depth of the affiliate referral hierarchy.
     * @param newMaxDepth The new maximum depth to set.
     */
    function setMaxDepth(uint256 newMaxDepth) public onlyRole(BOOTH_ROLE) {
        maxDepth = newMaxDepth;
    }

    /**
     * @notice Modifier to ensure an affiliate is not already enrolled for a specific NFT.
     * @param tokenId The token ID of the NFT.
     * @param affiliateAddress The address of the affiliate.
     */
    modifier notAlreadyEnrolled(uint256 tokenId, address affiliateAddress) {
        require(!affiliates[affiliateAddress].nftAffiliations[tokenId].isAffiliated, "Already an affiliate for this NFT");
        _;
    }

    /**
     * @notice Enrolls the initial affiliate for a specific NFT.
     * @param tokenId The token ID of the NFT.
     * @param sellerAddress The address of the seller to be enrolled as an affiliate.
     */
    function enrollInitialAffiliateForNFT(uint256 tokenId, address sellerAddress) public 
        onlyRole(BOOTH_ROLE) 
        onlyRegisteredToken(tokenId) 
        notAlreadyEnrolled(tokenId, sellerAddress) 
    {
        // Enrolling seller as their own referrer for this NFT
        affiliates[sellerAddress].nftAffiliations[tokenId] = SharedTypes.AffiliateNFTData({
            isAffiliated: true,
            referrer: sellerAddress,
            networkDepth: 0,
            totalRewards: 0,
            pendingRewards: 0,
            referredUsers: new address[](0)
        });

        // Updating affiliate counts and addresses
        nftAffiliateCounts[tokenId]++;
        affiliatesCount++;
        affiliateAddresses.push(sellerAddress);
        emit AffiliateEnrolledForNFT(tokenId, sellerAddress, sellerAddress);
    }

    /**
     * @notice Enrolls an affiliate for a specific NFT.
     * @param tokenId The token ID of the NFT.
     * @param affiliateAddress The address of the affiliate to enroll.
     * @param referrerAddress The address of the affiliate's referrer.
     */
    function enrollAffiliateForNFT(uint256 tokenId, address affiliateAddress, address referrerAddress) public 
        onlyRole(BOOTH_ROLE) 
        onlyRegisteredToken(tokenId) 
        notAlreadyEnrolled(tokenId, affiliateAddress) 
        isReferrerAffiliate(tokenId, referrerAddress) 
    {
        // Initializing general affiliate data for new affiliates
        SharedTypes.AffiliateData storage affiliate = affiliates[affiliateAddress];
        if (affiliate.generalReferrer == address(0)) {
            affiliate.generalReferrer = referrerAddress;
            affiliate.rank = 0;
            affiliate.directReferrals = 0;
            affiliate.salesVolume = 0;
        }

        // Calculating new affiliate level based on referrer's level
        uint256 referrerLevel = affiliates[referrerAddress].nftAffiliations[tokenId].networkDepth;
        uint256 newLevel = referrerLevel + 1;

        // Handling max depth limit
        if (newLevel >= maxDepth) {
            newLevel = 0;
            referrerAddress = referrerAddress;
        }

        // Enrolling affiliate and updating relevant data
        affiliate.nftAffiliations[tokenId] = SharedTypes.AffiliateNFTData({
            isAffiliated: true,
            referrer: referrerAddress,
            networkDepth: newLevel,
            totalRewards: 0,
            pendingRewards: 0,
            referredUsers: new address[](0)
        });
        affiliates[referrerAddress].nftAffiliations[tokenId].referredUsers.push(affiliateAddress);
        affiliates[referrerAddress].directReferrals = affiliates[referrerAddress].directReferrals.add(1);

        nftAffiliateCounts[tokenId]++;
        affiliatesCount++;
        affiliateAddresses.push(affiliateAddress);
        emit AffiliateEnrolledForNFT(tokenId, affiliateAddress, referrerAddress);
    }

    /**
     * @notice Checks if an affiliate is eligible for a rank upgrade.
     * @param affiliateAddress The address of the affiliate.
     * @return eligible Boolean indicating if the affiliate is eligible for a rank up.
     * @return currentRank The current rank of the affiliate.
     * @return requiredDirectReferrals The required direct referrals for the next rank.
     * @return requiredSalesVolume The required sales volume for the next rank.
     */
    function checkEligibilityForRankUp(address affiliateAddress) public view returns (bool eligible, uint256 currentRank, uint256 requiredDirectReferrals, uint256 requiredSalesVolume) {
        SharedTypes.AffiliateData storage affiliate = affiliates[affiliateAddress];
        currentRank = affiliate.rank;

        // Handling the highest rank limit
        if (currentRank >= rankCriteriasCount - 1) {
            return (false, currentRank, 0, 0);
        }

        // Fetching next rank criteria
        SharedTypes.RankCriteria memory nextRankCriteria = rankCriterias[currentRank + 1];
        requiredDirectReferrals = nextRankCriteria.requiredDirectReferrals;
        requiredSalesVolume = nextRankCriteria.requiredSalesVolume;

        // Checking eligibility
        eligible = (affiliate.directReferrals >= requiredDirectReferrals) && (affiliate.salesVolume >= requiredSalesVolume);
        return (eligible, currentRank, requiredDirectReferrals, requiredSalesVolume);
    }

    /**
     * @notice Sets new referral reward basis points for a specific level and rank.
     * @param level The level for which to set the new reward basis points.
     * @param rank The rank for which to set the new reward basis points.
     * @param newRewardBasisPoints The new reward basis points to set.
     */
    function setReferralRewardBasisPoints(uint256 level, uint256 rank, uint256 newRewardBasisPoints) public onlyRole(BOOTH_ROLE) {
        referralRewardBasisPoints[level][rank] = newRewardBasisPoints;
        emit ReferralRewardUpdated(level, rank, newRewardBasisPoints);
    }

    /**
     * @notice Update the criteria for a specific rank.
     * @param rank The rank to update.
     * @param newCriteria The new criteria for the rank.
     */
    function setRankCriteria(uint256 rank, SharedTypes.RankCriteria memory newCriteria) public onlyRole(BOOTH_ROLE) {
        require(rank < rankCriteriasCount, "Invalid rank");
        rankCriterias[rank] = newCriteria;
        emit RankCriteriaUpdated(rank, newCriteria);
    }

    /**
     * @notice Set the rank of a referrer.
     * @param affiliateAddress The address of the referrer.
     * @param rank The new rank to be set.
     */
    function setReferrerRank(address affiliateAddress, uint256 rank, uint256 tokenId) external onlyRole(BOOTH_ROLE) onlyRegisteredToken(tokenId) {
        require(affiliateAddress != address(0), "Invalid referrer address");
        require(rank < rankCriteriasCount, "Invalid rank");
        require(affiliates[affiliateAddress].nftAffiliations[tokenId].isAffiliated, "Referrer not enrolled for NFT");
        SharedTypes.AffiliateData storage affiliate = affiliates[affiliateAddress];
        affiliate.rank = rank;
        emit ReferrerRankUpdated(affiliateAddress, rank);
    }
    
    /**
     * @notice Updates the sales volume for a specific affiliate.
     * @param affiliateAddress The address of the affiliate whose sales volume is to be updated.
     * @param amount The amount to add to the affiliate's sales volume.
     * @dev This function should only be called by roles with the BOOTH_ROLE permission.
     */
    function updateSalesVolume(address affiliateAddress, uint256 amount) external onlyRole(BOOTH_ROLE) {
        require(affiliates[affiliateAddress].generalReferrer != address(0), "Affiliate does not exist");
        SharedTypes.AffiliateData storage affiliate = affiliates[affiliateAddress];
        affiliate.salesVolume = affiliates[affiliateAddress].salesVolume.add(amount);
        emit SalesVolumeUpdated(affiliateAddress, affiliates[affiliateAddress].salesVolume);
    }

    /**
     * @notice Increments the rank of an affiliate if they are eligible for a rank up.
     * @param affiliateAddress The address of the affiliate to rank up.
     * @dev This function checks the affiliate's eligibility before increasing their rank.
     *      Only callable by roles with the BOOTH_ROLE permission.
     */
    function rankUp(address affiliateAddress) external onlyRole(BOOTH_ROLE) {
        require(affiliates[affiliateAddress].generalReferrer != address(0), "Affiliate does not exist");
        (bool eligible, uint256 currentRank, , ) = checkEligibilityForRankUp(affiliateAddress);
        require(eligible, "Affiliate is not eligible for rank up");
        affiliates[affiliateAddress].rank = currentRank + 1;
        emit RankUp(affiliateAddress, currentRank + 1);
    }

    /**
     * @notice Handles the distribution of referral rewards for an NFT purchase.
     * @param tokenId The token ID of the NFT involved in the transaction.
     * @param buyer The address of the buyer.
     * @param referrer The address of the referrer.
     * @return remainingRewards The amount of funds remaining after distributing the rewards.
     * @dev Distributes referral rewards up the referral chain and updates sales volumes.
     *      Only callable by roles with the BOOTH_ROLE permission and for registered tokens.
     */
    function handleAffiliateProgram(uint256 tokenId, address buyer, address referrer) external payable onlyRole(BOOTH_ROLE) onlyRegisteredToken(tokenId) returns (uint256) {        
        if(!(affiliates[buyer].nftAffiliations[tokenId].isAffiliated)){
            enrollAffiliateForNFT(tokenId, buyer, referrer);
        }

        uint256 remainingRewards = msg.value;
        address currentAffiliate = referrer;
        uint256 currentDepth = 0;

        while (currentAffiliate != address(0) && currentDepth < maxDepth) {
            SharedTypes.AffiliateData storage affiliate = affiliates[currentAffiliate];
            SharedTypes.AffiliateNFTData storage nftAffiliateData = affiliate.nftAffiliations[tokenId];

            if (nftAffiliateData.isAffiliated) {
                uint256 referralReward = calculateReward(tokenId, currentAffiliate, msg.value);  // Using msg.value instead of remainingRewards

                payable(currentAffiliate).transfer(referralReward);
                remainingRewards -= referralReward;

                affiliate.salesVolume = affiliate.salesVolume.add(referralReward);
                nftAffiliateData.totalRewards = nftAffiliateData.totalRewards.add(referralReward);

                emit SalesVolumeUpdated(currentAffiliate, affiliate.salesVolume);
            }

            currentAffiliate = nftAffiliateData.referrer;
            currentDepth++;
        }
        return remainingRewards;
    }

    /**
     * @notice Calculates the referral reward for an affiliate based on the purchase price.
     * @param tokenId The token ID of the NFT involved in the transaction.
     * @param affiliate The address of the affiliate for whom the reward is being calculated.
     * @param purchasePrice The price of the NFT purchase.
     * @return referralReward The calculated referral reward for the affiliate.
     * @dev This calculation is based on the affiliate's rank and level within the referral system.
     *      Only callable for registered tokens.
     */
    function calculateReward(uint256 tokenId, address affiliate, uint256 purchasePrice) public view onlyRegisteredToken(tokenId) returns (uint256) {
        SharedTypes.AffiliateData storage affiliateData = affiliates[affiliate];
        SharedTypes.AffiliateNFTData storage nftAffiliateData = affiliateData.nftAffiliations[tokenId];

        require(nftAffiliateData.isAffiliated, "Affiliate not enrolled for this NFT");

        uint256 affiliateRank = affiliateData.rank;
        uint256 affiliateLevel = nftAffiliateData.networkDepth;

        uint256 referralRewardBasisPoint = referralRewardBasisPoints[affiliateLevel][affiliateRank];
        uint256 referralReward = (purchasePrice * referralRewardBasisPoint) / 10000;

        return referralReward;
    }

    /* 
    /////////////////////////////
    5. Helper Functions
    /////////////////////////////

      Include helper functions.
    */ 

    /**
     * @notice Retrieves the general referrer of an affiliate.
     * @param affiliate The address of the affiliate.
     * @return The address of the general referrer of the specified affiliate.
     */
    function getAffiliateReferrer(address affiliate) public view returns (address) {
        return affiliates[affiliate].generalReferrer;
    }

    /**
     * @notice Returns the number of direct referrals made by an affiliate.
     * @param affiliate The address of the affiliate.
     * @return The number of direct referrals made by the affiliate.
     */
    function getAffiliateDirectReferrals(address affiliate) public view returns (uint256) {
        return affiliates[affiliate].directReferrals;
    }

    /**
     * @notice Retrieves NFT-specific affiliate data.
     * @param tokenId The ID of the NFT.
     * @param affiliate The address of the affiliate.
     * @return NFT-specific affiliate data for the specified affiliate and NFT.
     */
    function getAffiliateNFTData(uint256 tokenId, address affiliate) public view onlyRegisteredToken(tokenId) returns (SharedTypes.AffiliateNFTData memory) {
        return affiliates[affiliate].nftAffiliations[tokenId];
    }

    /**
     * @notice Retrieves the rank of an affiliate.
     * @param affiliate The address of the affiliate.
     * @return The rank of the specified affiliate.
     */
    function getAffiliateRank(address affiliate) public view returns (uint256) {
        return affiliates[affiliate].rank;
    }

    /**
     * @notice Retrieves the total sales volume generated by an affiliate.
     * @param affiliate The address of the affiliate.
     * @return The total sales volume of the affiliate.
     */
    function getAffiliateSalesVolume(address affiliate) public view returns (uint256) {
        return affiliates[affiliate].salesVolume;
    }

    /**
     * @notice Retrieves the total rewards earned by an affiliate for a specific NFT.
     * @param tokenId The token ID of the NFT.
     * @param affiliate The address of the affiliate.
     * @return Total rewards earned by the affiliate for the specified NFT.
     */
    function getAffiliateTotalRewards(uint256 tokenId, address affiliate) public view onlyRegisteredToken(tokenId) returns (uint256) {
        return affiliates[affiliate].nftAffiliations[tokenId].totalRewards;
    }

    /**
     * @notice Retrieves the list of users referred by an affiliate for a specific NFT.
     * @param tokenId The token ID of the NFT.
     * @param affiliate The address of the affiliate.
     * @return List of users referred by the affiliate for the specified NFT.
     */
    function getNFTAffiliateReferredUsers(uint256 tokenId, address affiliate) public view onlyRegisteredToken(tokenId) returns (address[] memory) {
        return affiliates[affiliate].nftAffiliations[tokenId].referredUsers;
    }

    /**
     * @notice Retrieves the level of an affiliate for a specific NFT.
     * @param tokenId The token ID of the NFT.
     * @param affiliateAddress The address of the affiliate.
     * @return The level of the affiliate for the specified NFT.
     */
    function getAffiliateLevel(uint256 tokenId, address affiliateAddress) public view onlyRegisteredToken(tokenId) returns (uint256) {
        // Ensure the affiliate is enrolled for the specified NFT
        require(affiliates[affiliateAddress].nftAffiliations[tokenId].isAffiliated, "Affiliate not enrolled for this NFT");

        // Return the level of the affiliate for the specific NFT
        return affiliates[affiliateAddress].nftAffiliations[tokenId].networkDepth;
    }

    /**
     * @notice Retrieves the referral reward basis points for all levels and ranks.
     * @return A two-dimensional array containing the referral reward basis points.
     */
    function getReferralRewardBasisPoints() public view returns (uint256[][] memory) {
        return referralRewardBasisPoints;
    }

    /**
     * @notice Retrieves the maximum depth allowed in the affiliate hierarchy.
     * @return The maximum depth of the affiliate hierarchy.
     */
    function getMaxDepth() public view returns (uint256) {
        return maxDepth;
    }

    /**
     * @notice Retrieves the referral reward basis points for a specific level and rank.
     * @param level The affiliate level.
     * @param rank The affiliate rank.
     * @return The referral reward basis points for the specified level and rank.
     */
    function getReferralRewardBasisPointsForLevelAndRank(uint256 level, uint256 rank) public view returns (uint256) {
        // Ensure the level and rank are within the bounds of the referralRewardBasisPoints array
        require(level < referralRewardBasisPoints.length, "Level out of range");
        require(rank < referralRewardBasisPoints[level].length, "Rank out of range");

        // Return the basis points for the given level and rank
        return referralRewardBasisPoints[level][rank];
    }
    
    /**
     * @notice Retrieves the criteria for a specific rank.
     * @param rank The rank number.
     * @return The criteria for the specified rank.
     */
    function getRankCriteria(uint256 rank) public view returns (SharedTypes.RankCriteria memory) {
        require(rank < rankCriteriasCount, "Rank number out of range");
        return rankCriterias[rank];
    }
    
    /**
     * @notice Retrieves the total number of affiliates.
     * @return The total number of affiliates.
     */
    function getTotalAffiliates() public view returns (uint256) {
        return affiliatesCount;
    }

    /**
     * @notice Retrieves the total number of affiliates for a specific NFT.
     * @param tokenId The token ID of the NFT.
     * @return The total number of affiliates for the specified NFT.
     */
    function getTotalNFTAffiliates(uint256 tokenId) public view onlyRegisteredToken(tokenId) returns (uint256) {
        return nftAffiliateCounts[tokenId];
    }
    
    /**
     * @notice Checks if a given address is an affiliate for a specific NFT.
     * @param tokenId The token ID of the NFT.
     * @param affiliateAddress The address to check.
     * @return True if the address is an affiliate for the NFT, otherwise false.
     */
    function isAffiliateForNFT(uint256 tokenId, address affiliateAddress) public view onlyRegisteredToken(tokenId) returns (bool) {
        // Access the affiliate's data for the specific NFT
        SharedTypes.AffiliateNFTData storage nftAffiliateData = affiliates[affiliateAddress].nftAffiliations[tokenId];

        // Check if the affiliate is affiliated with the specified NFT
        return nftAffiliateData.isAffiliated;
    }

    /**
     * @notice Retrieves the affiliate address at a given index in the affiliate list.
     * @param index The index in the affiliate list.
     * @return The address of the affiliate at the specified index.
     */
    function getAffiliateAtIndex(uint256 index) public view returns (address) {
        require(index < affiliateAddresses.length, "Index out of bounds");
        return affiliateAddresses[index];
    }

    /**
     * @notice Ensures that the specified token ID is registered.
     * @param _tokenId The token ID to check.
     */
    modifier onlyRegisteredToken(uint256 _tokenId) {
        require(ticketRegistry.isObjectRegistered(_tokenId), "Object is not registered");
        _;
    }

    /**
     * @notice Ensures that the specified referrer is an affiliate for the given token ID.
     * @param _tokenId The token ID.
     * @param referrer The address of the referrer.
     */
    modifier isReferrerAffiliate(uint256 _tokenId, address referrer) {
        require(affiliates[referrer].nftAffiliations[_tokenId].isAffiliated, "Referrer is not an affiliate for this tokenId");
        _;
    }
}

File 22 of 25 : types.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;

contract SharedTypes {
    struct RankCriteria {
        uint256 requiredDirectReferrals;
        uint256 requiredSalesVolume;
    }

    struct AffiliateNFTData {
        bool isAffiliated;
        address referrer; // Referrer for this specific NFT
        uint256 networkDepth; // The depth of the affiliate's network for this NFT
        uint256 totalRewards;
        uint256 pendingRewards;
        address[] referredUsers; // Users directly referred by this affiliate for this NFT
    }

    struct AffiliateData {
        address generalReferrer; // General referrer (across all NFTs)
        uint256 rank;
        uint256 directReferrals;
        uint256 salesVolume;
        mapping(uint256 => AffiliateNFTData) nftAffiliations; // NFT specific data
        // mapping(address => uint256) recruitsNetworkDepth; // General network depth of each recruit
    }
}

File 23 of 25 : ITicketRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;

interface ITicketRegistry {
    function specialUpdateOnMint(
        address _guy, 
        uint256 _tokenId, 
        uint256 _nftId, 
        uint256 _qty, 
        uint256 _price, 
        string memory _uri
    ) external;

    function specialUpdateOnTransfer(
        address _from, 
        address _to, 
        uint256 _tokenId, 
        uint256 _nftId, 
        uint256 _qty, 
        uint256 _price, 
        string memory _uri
    ) external;

    function isCurrentlyMinting() external view returns (bool);
}

File 24 of 25 : registry.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;

import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";

import "./ticket.sol";

/// @custom:security-contact [email protected]
contract TicketRegistry is IERC165, IERC1155Receiver, AccessControl {

    /* 
    /////////////////////////////////
    1. Contract and Role Declarations 
    /////////////////////////////////
    
      - Define a constant role for the booking role
    */ 

    bytes32 public constant BOOTH_ROLE = keccak256("BOOTH_ROLE");

    /* 
    /////////////////////////////
    2. Structs and State Variables
    /////////////////////////////
    */ 

    struct NFTTransactionDetails {
        uint256 tokenId;
        uint256 nftId;
        address owner;
        uint256 qty;
        uint256 price;
        string uri;
    }

    // Mapping to store the registered objects and their ticket contracts
    mapping(address => mapping(uint256 => NFTTransactionDetails[])) private userOwnedNFTs;
    mapping(address => mapping(uint256 => uint256)) private userTokenIdCount;
    mapping(uint256 => Ticket) public objectToTicket;
    uint256 public maxPageSize = 100;

    /* 
    /////////////////////////////
    3. Constructor and events
    /////////////////////////////
    
      The constructor initializes the contract's state.
      The deployer will be granted the Booking Role.
    */ 

    constructor() {
        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
        _grantRole(BOOTH_ROLE, msg.sender);
    }

    event ObjectRegistered(uint256 tokenId, address ticketContract);

    /* 
    /////////////////////////////
    4. Role-Based Functionality
    /////////////////////////////

      Group functions by the roles that can call them. 
      For example, all functions that require BOOTH_ROLE should be together.
    */ 

    /**
     * @notice Registers a new NFT object and its corresponding ticket contract.
     * @param _tokenId The ID of the NFT to register.
     * @param _address The associated Ticket contract for the NFT.
     * @dev Only callable by users with the BOOTH_ROLE.
     *      Prevents re-registering an already registered object.
     */
    function registerObject(uint256 _tokenId, Ticket _address) external onlyRole(BOOTH_ROLE) {
        // Only allow registering an object once
        require(address(objectToTicket[_tokenId]) == address(0), "Object already registered");
        objectToTicket[_tokenId] = _address;
        emit ObjectRegistered(_tokenId, address(_address));
    }

    /**
     * @notice Checks if an NFT object is registered in the system.
     * @param _tokenId The ID of the NFT to check.
     * @return True if the NFT object is registered, false otherwise.
     */
    function isObjectRegistered(uint256 _tokenId) external view returns (bool) {
        return address(objectToTicket[_tokenId]) != address(0);
    }

    /**
     * @notice Modifier to ensure an NFT object is registered.
     * @param _tokenId The ID of the NFT to check.
     * @dev Reverts if the NFT object is not registered.
     */
    modifier isRegistered(uint256 _tokenId) {
        require(address(objectToTicket[_tokenId]) != address(0), "Object is not registered");
        _;
    }

    /**
     * @notice Modifier to ensure an NFT object is registered.
     * @param _tokenId The ID of the NFT to check.
     * @dev Reverts if the NFT object is not registered.
     */
    modifier onlyAllowDuringMint(uint256 _tokenId) {
        Ticket ticketContract = objectToTicket[_tokenId];
        require(ticketContract.isCurrentlyMinting(), "Can only be called during minting");
        _;
    }
    

    /**
     * @notice Updates ownership details in the registry when a new NFT is minted.
     * @param _guy The address of the user who mints the NFT.
     * @param _tokenId The ID of the token.
     * @param _nftId The ID of the NFT.
     * @param _qty The quantity of NFTs minted.
     * @param _price The price of the NFT.
     * @param _uri The URI of the NFT.
     * @dev Only callable by users with the BOOTH_ROLE.
     */
    function updateOwnershipOnMint(
        address _guy, 
        uint256 _tokenId, 
        uint256 _nftId, 
        uint256 _qty, 
        uint256 _price, 
        string memory _uri
    ) external onlyRole(BOOTH_ROLE) {
        _updateOwnershipOnMint(_guy,_tokenId,_nftId, _qty, _price, _uri);
    }

    function specialUpdateOnMint(
        address _guy, 
        uint256 _tokenId, 
        uint256 _nftId, 
        uint256 _qty, 
        uint256 _price, 
        string memory _uri
    ) external isRegistered(_tokenId) onlyAllowDuringMint(_tokenId) {
        Ticket ticketContract = objectToTicket[_tokenId];
        require(msg.sender == address(ticketContract), "Unauthorized caller");

        _updateOwnershipOnMint(_guy,_tokenId,_nftId, _qty, _price, _uri);
    }

    function _updateOwnershipOnMint(
        address _guy, 
        uint256 _tokenId, 
        uint256 _nftId, 
        uint256 _qty, 
        uint256 _price, 
        string memory _uri
    ) private {
        for (uint256 i = 0; i < _qty; ++i) {
            NFTTransactionDetails memory newNFT = NFTTransactionDetails({
                nftId: _nftId,
                tokenId: _tokenId,
                owner: _guy,
                qty: 1,
                price: _price,
                uri: _uri
            });

            userOwnedNFTs[_guy][_tokenId].push(newNFT);
            userTokenIdCount[_guy][_tokenId] += _qty;
        }
    }

    /**
     * @notice Updates ownership details in the registry when an NFT is transferred.
     * @param _from The address of the sender.
     * @param _to The address of the receiver.
     * @param _tokenId The ID of the token.
     * @param _nftId The ID of the NFT.
     * @param _qty The quantity of NFTs transferred.
     * @param _price The price of the NFT.
     * @param _uri The URI of the NFT.
     * @dev Only callable by users with the BOOTH_ROLE.
     */
    function updateOwnershipOnTransfer(
        address _from, 
        address _to, 
        uint256 _tokenId, 
        uint256 _nftId, 
        uint256 _qty, 
        uint256 _price, 
        string memory _uri
    ) external onlyRole(BOOTH_ROLE) {
        require(userTokenIdCount[_from][_tokenId] >= _qty, "Insufficient NFTs to transfer");

        // TODO: Verify from address owns the nft being transfered
        _updateOwnershipOnTransfer(_from, _to, _tokenId, _nftId, _qty, _price, _uri);
    }

    function specialUpdateOnTransfer(
        address _from, 
        address _to, 
        uint256 _tokenId, 
        uint256 _nftId, 
        uint256 _qty, 
        uint256 _price, 
        string memory _uri
    ) external isRegistered(_tokenId){
        Ticket ticketContract = objectToTicket[_tokenId];
        require(msg.sender == address(ticketContract), "Unauthorized caller");

        // TODO: Verify from address owns the nft being transfered
        _updateOwnershipOnTransfer(_from, _to, _tokenId, _nftId, _qty, _price, _uri);
    }

    function _updateOwnershipOnTransfer(
        address _from, 
        address _to, 
        uint256 _tokenId, 
        uint256 _nftId, 
        uint256 _qty, 
        uint256 _price, 
        string memory _uri
    ) private {
        // First, reduce the quantity from the sender's account
        bool isFound = false;
        uint256 i;
        for (i = 0; i < userOwnedNFTs[_from][_tokenId].length; i++) {
            if (userOwnedNFTs[_from][_tokenId][i].nftId == _nftId) {
                require(userOwnedNFTs[_from][_tokenId][i].qty >= _qty, "Insufficient NFT quantity");
                userOwnedNFTs[_from][_tokenId][i].qty -= _qty;
                isFound = true;
                break;
            }
        }
        require(isFound, "NFT not found for transfer");

        // If the NFT quantity becomes zero, we could choose to remove it from the array
        if (userOwnedNFTs[_from][_tokenId][i].qty == 0) {
            removeNFTFromOwner(_from, _tokenId, i);
        }

        // Now, add the NFT to the receiver's account
        isFound = false;
        for (i = 0; i < userOwnedNFTs[_to][_tokenId].length; i++) {
            if (userOwnedNFTs[_to][_tokenId][i].nftId == _nftId) {
                userOwnedNFTs[_to][_tokenId][i].qty += _qty;
                isFound = true;
                break;
            }
        }

        // If the NFT does not exist in the receiver's account, create a new entry
        if (!isFound) {
            NFTTransactionDetails memory newNFT = NFTTransactionDetails({
                nftId: _nftId,
                tokenId: _tokenId,
                owner: _to,
                qty: _qty,
                price: _price,
                uri: _uri
            });
            userOwnedNFTs[_to][_tokenId].push(newNFT);
        }

        // Update the token count for both sender and receiver
        userTokenIdCount[_from][_tokenId] -= _qty;
        userTokenIdCount[_to][_tokenId] += _qty;
    }

    // Helper function to remove an NFT from an owner's list if the quantity is zero
    function removeNFTFromOwner(address _owner, uint256 _tokenId, uint256 index) private {
        require(index < userOwnedNFTs[_owner][_tokenId].length, "Index out of bounds");

        // Move the last element to the index being removed and then pop the last element
        userOwnedNFTs[_owner][_tokenId][index] = userOwnedNFTs[_owner][_tokenId][userOwnedNFTs[_owner][_tokenId].length - 1];
        userOwnedNFTs[_owner][_tokenId].pop();
    }

    /* 
    /////////////////////////////
    5. Utility Functions
    /////////////////////////////
    
      Include utility functions like getStock and getNftId.
    */ 

    /**
     * @notice Retrieves the Ticket contract associated with a registered NFT.
     * @param _tokenId The ID of the NFT.
     * @return The associated Ticket contract.
     * @dev Ensures that the NFT is registered before returning the Ticket contract.
     */
    function getRegisteredNFT(uint256 _tokenId) public view isRegistered(_tokenId) returns (Ticket) {
        Ticket nft = objectToTicket[_tokenId];
        return nft;
    }

    /**
     * @notice Checks if a user owns a specific NFT.
     * @param _guy The address of the user.
     * @param _tokenId The ID of the NFT to check.
     * @return True if the user owns the NFT, false otherwise.
     */
    function doesUserOwnNFT(address _guy, uint256 _tokenId) public view returns (bool) {
        return userTokenIdCount[_guy][_tokenId] > 0;
    }

    /**
     * @notice Gets the remaining stock of a specific NFT.
     * @param _tokenId The ID of the NFT.
     * @return The remaining stock of the NFT.
     * @dev Returns -1 if the NFT does not use stock management.
     */
    function getStock(uint256 _tokenId) public view isRegistered(_tokenId) returns (int256) {
        Ticket ticketContract = objectToTicket[_tokenId];
        int256 remainingStock = -1;
        if (ticketContract.useStock()) {
            remainingStock = int256(ticketContract.stock(_tokenId)) - int256(ticketContract.totalSupply(_tokenId));
        }
        return remainingStock;
    }

    /**
     * @notice Checks if stock management is used for a specific NFT.
     * @param _tokenId The ID of the NFT.
     * @return True if the NFT uses stock management, false otherwise.
     */
    function getUseStock(uint256 _tokenId) public view isRegistered(_tokenId) returns (bool) {
        Ticket ticketContract = objectToTicket[_tokenId];
        bool usesStock = ticketContract.useStock();
        return usesStock;
    }

    /**
     * @notice Retrieves a paginated list of NFTs owned by a user for a specific tokenId.
     * @param user The address of the user.
     * @param tokenId The ID of the token.
     * @param page The page number of the paginated results.
     * @param pageSize The number of items per page.
     * @return ownedNFTDetails The list of NFTs owned by the user for the specified tokenId and page.
     * @return totalNFTs The total number of NFTs of the specified tokenId owned by the user.
     * @dev Pagination is implemented to manage large datasets.
     */
    function getOwnedNFTs(
        address user, 
        uint256 tokenId,
        uint256 page, 
        uint256 pageSize
    ) public view returns (NFTTransactionDetails[] memory ownedNFTDetails, uint256 totalNFTs) {
        totalNFTs = userOwnedNFTs[user][tokenId].length;
        uint256 startIndex = (page - 1) * pageSize;
        if (startIndex >= totalNFTs) {
            return (new NFTTransactionDetails[](0), totalNFTs);
        }

        uint256 endIndex = startIndex + pageSize > totalNFTs ? totalNFTs : startIndex + pageSize;
        ownedNFTDetails = new NFTTransactionDetails[](endIndex - startIndex);

        for (uint256 i = startIndex; i < endIndex; i++) {
            ownedNFTDetails[i - startIndex] = userOwnedNFTs[user][tokenId][i];
        }

        return (ownedNFTDetails, totalNFTs);
    }

    /**
     * @notice Retrieves the first owned NFT ID for a given tokenId.
     * @param user The address of the user.
     * @param tokenId The ID of the token.
     * @return The first NFT ID for the given tokenId owned by the user.
     */
    function getFirstOwnedNftIdForTokenId(address user, uint256 tokenId) public view returns (uint256) {
        require(userOwnedNFTs[user][tokenId].length > 0, "User does not own any NFTs for this tokenId");
        return userOwnedNFTs[user][tokenId][0].nftId;
    }

    /**
     * @notice Retrieves a paginated list of owned NFT IDs for a given tokenId.
     * @param user The address of the user.
     * @param tokenId The ID of the token.
     * @param page The page number for pagination.
     * @param pageSize The number of items per page.
     * @return ownedNftIds The paginated list of NFT IDs for the given tokenId.
     * @return totalNftCount The total count of NFTs for the given tokenId owned by the user.
     */
    function getOwnedNftIdsForTokenId(address user, uint256 tokenId, uint256 page, uint256 pageSize) public view returns (uint256[] memory ownedNftIds, uint256 totalNftCount) {
        totalNftCount = userOwnedNFTs[user][tokenId].length;
        uint256 startIndex = (page - 1) * pageSize;
        if (startIndex >= totalNftCount) {
            return (new uint256[](0), totalNftCount);
        }

        uint256 endIndex = startIndex + pageSize > totalNftCount ? totalNftCount : startIndex + pageSize;
        ownedNftIds = new uint256[](endIndex - startIndex);

        for (uint256 i = startIndex; i < endIndex; i++) {
            ownedNftIds[i - startIndex] = userOwnedNFTs[user][tokenId][i].nftId;
        }

        return (ownedNftIds, totalNftCount);
    }

    /* 
    /////////////////////////////
    6. ERC1155 and Interface Implementations
    /////////////////////////////
    
      Place the ERC1155 token reception and interface support functions at the end.
    */ 

    // Interface to allow receiving ERC1155 tokens.
    function onERC1155Received(
        address,
        address,
        uint256,
        uint256,
        bytes calldata
    ) external pure override returns (bytes4) {
        return this.onERC1155Received.selector;
    }

    // Interface to allow receiving batch ERC1155 tokens.
    function onERC1155BatchReceived(
        address,
        address,
        uint256[] calldata,
        uint256[] calldata,
        bytes calldata
    ) external pure override returns (bytes4) {
        return this.onERC1155BatchReceived.selector;
    }

    function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, AccessControl) returns (bool) {
        return
            interfaceId == type(IERC1155Receiver).interfaceId ||
            interfaceId == type(IERC165).interfaceId;
    }
}

File 25 of 25 : ticket.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;

import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/finance/PaymentSplitter.sol";
import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol";
import "@openzeppelin/contracts/interfaces/IERC2981.sol";
import "@openzeppelin/contracts/utils/Strings.sol";

import "./ITicketRegistry.sol";


/// @custom:security-contact [email protected]
contract Ticket is ERC1155, AccessControl, ERC1155Supply, PaymentSplitter,IERC2981 {
    
    /* 
    /////////////////////////////////
    1. Contract and Role Declarations 
    /////////////////////////////////

        - Define a constant role for the booth role
    */ 
   
    bytes32 public constant BOOTH_ROLE = keccak256("BOOTH_ROLE");

    /* 
    /////////////////////////////
    2. Structs and State Variables
    /////////////////////////////
        
        This section declares the state variables and data structures used in the contract.

        - price: The price of the NFT in wei.
        - tokenId: The unique identifier for each NFT.
        - stock: A mapping that associates each token ID with its stock limit. A value of 0 means there is no limit.
        - useStock: A boolean variable that indicates whether the contract should use the stock limit.
        - limitedEdition: A boolean variable that indicates whether the NFT is a limited edition.
        - userNFTs: A nested mapping that associates each user address with the number of NFTs they have minted for each token ID.
        - royaltyReceiver: The address that will receive the royalties from sales.
        - royaltyPercentage: The percentage of the sale price that will be paid as royalties. This is represented as a number out of 10000 (for example, 500 represents 5%).
    */

    ITicketRegistry private ticketRegistry;
    bool private isMintingActive = false;
    uint256 public price;
    uint256 public tokenId;
    mapping(uint256 => uint256) public stock;
    bool public useStock;
    bool public limitedEdition;
    address public royaltyReceiver;
    uint256 public royaltyPercentage;
    
    /* 
    /////////////////////////////
    3. Constructor and Events
    /////////////////////////////

        The constructor initializes the state of the contract with the following parameters:

        - uint256 _tokenId: This is the unique identifier for each NFT. For example, 8263712349.

        - uint256 _price: This is the price of the NFT in wei. The price is converted from ether to wei as follows:
            price = float(product.price)
            ticket_price = web3.to_wei(price, "ether")

        - uint256 _initialStock: This is the initial stock of the NFT. 
            For example, if _initialStock is 100, only 100 NFTs can be minted before a resupply is required.

        - bool _useStock: This boolean value indicates whether the contract should consider the stock limit. 
            If _useStock is true, the stock limit is considered; otherwise, the product is assumed to have an unlimited supply.

        - bool _limitedEdition: This boolean value restricts minting once the stock limit is reached. 
            If _limitedEdition is true, new NFTs cannot be minted once the stock limit is reached. This works in conjunction with the _useStock parameter.

        - address _royaltyReceiver: This is the address of the creator who will receive royalties. 
            Note that not all platforms enforce royalties.

        - uint256 _royaltyPercentage: This is the percentage of the sale price that will be paid as royalties, 
            represented as a number out of 10000 basis points. For example, 500 represents a 5% royalty.

        - address[] memory _payees: This is a list of addresses that will receive payments from each NFT sale. 
            Each payee must claim their profit by executing the required method. For example, [owner.address, seller.address].

        - uint256[] memory _shares: This is a list of shares corresponding to each payee. 
            The number of shares must add up to 100, and the number of items in the list must be the same as the number of payees. 
            For example, [10, 90]. In this scenario, owner.address would receive 10% of every NFT sale, and seller.address could claim the remaining 90%. Note that addresses cannot be repeated.

        - string memory _uri: This is the base URI for the NFT, which is the HTTPS address hosting the NFT metadata. 
            For example, "https://api.boomslag.com/api/courses/nft/{tokenId}".
    */
    
    constructor(
        uint256 _tokenId,
        uint256 _price,
        uint256 _initialStock,
        bool _useStock,
        bool _limitedEdition,
        address _royaltyReceiver,
        uint256 _royaltyPercentage,
        address[] memory _payees,
        uint256[] memory _shares,
        string memory _uri,
        address _ticketRegistryAddress

    )
    ERC1155(_uri) 
    PaymentSplitter(_payees, _shares)
    {
        tokenId = _tokenId;
        price = _price;
        useStock = _useStock;
        limitedEdition = _limitedEdition;
        if (limitedEdition)
            useStock = true;
        stock[tokenId] = _initialStock;
        royaltyReceiver = _royaltyReceiver;
        royaltyPercentage = _royaltyPercentage;
        ticketRegistry = ITicketRegistry(_ticketRegistryAddress);

        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
    }

    event Mint(uint256 indexed tokenId, uint256 indexed nftId, uint256 qty, uint256 price, address indexed guy, string uri);
    event Transfer(address indexed from, address indexed to, uint256 indexed nftId, uint256 tokenId, uint256 qty, string uri);
    event StockUpdated(uint256 indexed tokenId, uint256 stock);
    event UseStockUpdated(bool useStock);
    event SetUri(string newuri);

    /* 
    /////////////////////////////
    4. Role-Based Functionality
    /////////////////////////////

        Group functions by the roles that can call them. 
        For example, all functions that require BOOTH_ROLE should be together.
    */ 

    /**
     * @notice Sets the stock limit for a specific token.
     * @param _tokenId The ID of the token.
     * @param _stock The stock limit to be set.
     * @dev Only callable by users with DEFAULT_ADMIN_ROLE. Applies only if the token is not a limited edition.
     */
    function setStock(uint256 _tokenId, uint256 _stock) public onlyRole(DEFAULT_ADMIN_ROLE) {
        if (!limitedEdition){
            stock[_tokenId] = _stock;
            emit StockUpdated(_tokenId, _stock);
        }
    }
    
    /**
     * @notice Enables or disables stock management for NFTs.
     * @param _useStock True to enable stock management, false to disable it.
     * @dev Only callable by users with DEFAULT_ADMIN_ROLE. Applies only if the token is not a limited edition.
     */
    function setUseStock(bool _useStock) public onlyRole(DEFAULT_ADMIN_ROLE) {
        if (!limitedEdition){
            useStock = _useStock;
            emit UseStockUpdated(_useStock);
        }
    }
    
    /**
     * @notice Updates the base URI for all tokens.
     * @param newuri The new base URI to be set.
     * @dev Only callable by users with DEFAULT_ADMIN_ROLE. Emits an event with the new URI.
     */
    function setURI(string memory newuri) public onlyRole(DEFAULT_ADMIN_ROLE) {
        // Sets the new URI for the token
        _setURI(newuri);
        // Emits an event with the new URI
        emit SetUri(newuri);
    }
    
    /**
     * @notice Updates the price of the NFT.
     * @param newPrice The new price to be set.
     * @dev Only callable by users with DEFAULT_ADMIN_ROLE. Updates the global price of the NFT ticket.
     */
    function updatePrice(uint256 newPrice) public onlyRole(DEFAULT_ADMIN_ROLE) {
        // Updates the price of the NFT ticket
        price = newPrice;
    }
    
    /**
     * @notice Retrieves the royalty information for a token sale.
     * @param _salePrice The sale price of the NFT.
     * @return receiver The address entitled to receive the royalties.
     * @return royaltyAmount The amount of royalty to be paid.
     * @dev Assumes the royaltyPercentage is out of 10000 for percentage calculation.
     */
    function royaltyInfo(uint256 /*_tokenId*/, uint256 _salePrice) external view override returns (address receiver, uint256 royaltyAmount) {
        receiver = royaltyReceiver;
        royaltyAmount = (_salePrice * royaltyPercentage) / 10000; // assuming the royaltyPercentage is out of 10000 for a percentage calculation
    }
    
    /* 
    /////////////////////////////
    5. Purchase and Minting
    /////////////////////////////
        
        Group together all functions related to purchasing and minting.
            
    */ 
    
    /**
     * @notice Mints a specific quantity of NFTs.
     * @param _tokenId The ID of the token to mint.
     * @param _nftId The ID of the NFT.
     * @param _qty The quantity of NFTs to mint.
     * @param _guy The address to receive the minted NFTs.
     * @dev Requires the caller to pay the correct ETH amount if not having BOOTH_ROLE. Stock is checked if useStock is enabled.
     */
    function mint(uint256 _tokenId, uint256 _nftId, uint256 _qty, address _guy) public payable {
        // If the caller is not the BOOTH_ROLE, apply the requirement
        if (!hasRole(BOOTH_ROLE, msg.sender)) {
             // Price check for regular buyers
            require(msg.value >= price * _qty, "Not Enough ETH to Buy NFT");
        }

        // Check if the NFT stock limit has been reached
        if (useStock) {
            uint256 remainingStock = stock[_tokenId];
            require(remainingStock >= _qty, "NFT Out of Stock");
            // Update the stock mapping
            stock[_tokenId] = remainingStock - _qty;
        }
        
        // Mint new NFTs to the user and emit an event
        _mint(_guy, _nftId, _qty, "");

        // Call TicketRegistry to update ownership
        string memory _uri = string(abi.encodePacked(super.uri(_nftId),Strings.toString(_nftId), ".json" ));
        isMintingActive = true;
        ticketRegistry.specialUpdateOnMint(_guy, _tokenId, _nftId, _qty, msg.value, _uri);
        isMintingActive = false;
        emit Mint(_tokenId, _nftId, _qty, msg.value, _guy, _uri);
    }
    
    /**
     * @notice Mints a batch of NFTs to a specified address. (Disabled for this implementation)
     * @param _to The address to receive the minted NFTs.
     * @param _ids Array of token IDs to mint.
     * @param _amounts Array of quantities for each token ID.
     * @param _data Additional data (unused in this contract).
     * @dev Method DISABLED: Only callable by users with DEFAULT_ADMIN_ROLE. Batch minting is disabled in this contract.
     */
    function mintBatch(address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
        public
        onlyRole(DEFAULT_ADMIN_ROLE)
    {
        // Mints a batch of NFTs to the specified address
        // _mintBatch(_to, _ids, _amounts, _data);
        // Mint Batch is Disabled in this contract
    }

    /* 
    /////////////////////////////
    6. Utility Functions
    /////////////////////////////

        Include utility functions like isObjectRegistered and hasAccess.
    */ 

    /**
     * @notice Checks if the mint method is being used.
     * @return The boolean value true or false.
     */
    function isCurrentlyMinting() external view returns (bool) {
        return isMintingActive;
    }

    /**
     * @notice Retrieves the URI for a specific token.
     * @param _id The ID of the token.
     * @return The URI associated with the token, appended with the token ID.
     * @dev Ensures that the token exists before returning the URI.
     */
    function uri(uint256 _id) public view virtual override returns (string memory) {
        // Checks if the specified token exists
        require(exists(_id),"URI: Token does not exist.");
        // Retrieves the URI for the token and appends the token ID to the end of the URI
        return string(abi.encodePacked(super.uri(_id),Strings.toString(_id), ".json" ));
    }

    /* 
    /////////////////////////////
    7. ERC1155 and Interface Implementations
    /////////////////////////////

        Place the ERC1155 token reception and interface support functions at the end.
    */
    
    function _beforeTokenTransfer(address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data)
        internal
        override(ERC1155, ERC1155Supply)
    {
        super._beforeTokenTransfer(operator, from, to, ids, amounts, data);

        // Check if this is a transfer (not minting or burning)
        if (from != address(0) && to != address(0)) {
            for (uint256 i = 0; i < ids.length; i++) { 
                // Emit the Transfer event with NFT details
                string memory _uri = string(abi.encodePacked(super.uri(ids[i]), Strings.toString(ids[i]), ".json" ));
                ticketRegistry.specialUpdateOnTransfer(from, to, tokenId, ids[i], amounts[i], 0, _uri);
                emit Transfer(from, to, ids[i], tokenId, amounts[i], _uri);
            }
        }
    }

    // The following functions are overrides required by Solidity.
    function supportsInterface(bytes4 interfaceId)
        public
        view
        override(ERC1155, AccessControl, IERC165)
        returns (bool)
    {
        return super.supportsInterface(interfaceId);
    }
}

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

Contract Security Audit

Contract ABI

[{"inputs":[{"internalType":"contract Affiliates","name":"_affiliatesContract","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"inputs":[],"name":"ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"affiliatesContract","outputs":[{"internalType":"contract Affiliates","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"affiliateAddress","type":"address"}],"name":"getAffiliateInformation","outputs":[{"internalType":"address","name":"referrer","type":"address"},{"internalType":"uint256","name":"rank","type":"uint256"},{"internalType":"uint256","name":"directReferrals","type":"uint256"},{"internalType":"uint256","name":"salesVolume","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"page","type":"uint256"},{"internalType":"uint256","name":"pageSize","type":"uint256"}],"name":"getAffiliates","outputs":[{"internalType":"address[]","name":"results","type":"address[]"},{"internalType":"uint256","name":"count","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getAllRankCriterias","outputs":[{"components":[{"internalType":"uint256","name":"requiredDirectReferrals","type":"uint256"},{"internalType":"uint256","name":"requiredSalesVolume","type":"uint256"}],"internalType":"struct SharedTypes.RankCriteria[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"address","name":"affiliateAddress","type":"address"}],"name":"getNFTAffiliateInformation","outputs":[{"internalType":"bool","name":"isAffiliated","type":"bool"},{"internalType":"address","name":"referrer","type":"address"},{"internalType":"uint256","name":"level","type":"uint256"},{"internalType":"uint256","name":"totalRewards","type":"uint256"},{"internalType":"uint256","name":"pendingRewards","type":"uint256"},{"internalType":"address[]","name":"referredUsers","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"address","name":"affiliateAddress","type":"address"}],"name":"getNFTAffiliateReferralsChain","outputs":[{"internalType":"address[]","name":"referralChain","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"address","name":"rootAffiliate","type":"address"},{"internalType":"uint256","name":"page","type":"uint256"},{"internalType":"uint256","name":"pageSize","type":"uint256"}],"name":"getNftAffiliatesForReferrer","outputs":[{"components":[{"internalType":"bool","name":"isAffiliated","type":"bool"},{"internalType":"address","name":"referrer","type":"address"},{"internalType":"uint256","name":"networkDepth","type":"uint256"},{"internalType":"uint256","name":"totalRewards","type":"uint256"},{"internalType":"uint256","name":"pendingRewards","type":"uint256"},{"internalType":"address[]","name":"referredUsers","type":"address[]"}],"internalType":"struct SharedTypes.AffiliateNFTData[]","name":"","type":"tuple[]"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxPageSize","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract Affiliates","name":"_affiliatesContract","type":"address"}],"name":"setAffiliatesContract","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_maxPageSize","type":"uint256"}],"name":"setMaxPageSize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"}]

608060405260646002553480156200001657600080fd5b5060405162001a7538038062001a75833981016040819052620000399162000137565b600180546001600160a01b0319166001600160a01b038316179055620000807fa49807205ce4d355092ef5a8a18f56e8913cf4a201fbe287825b095693c217753362000087565b5062000169565b62000093828262000097565b5050565b6000828152602081815260408083206001600160a01b038516845290915290205460ff1662000093576000828152602081815260408083206001600160a01b03851684529091529020805460ff19166001179055620000f33390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b6000602082840312156200014a57600080fd5b81516001600160a01b03811681146200016257600080fd5b9392505050565b6118fc80620001796000396000f3fe608060405234801561001057600080fd5b50600436106101165760003560e01c80638c411222116100a2578063bca4c66911610071578063bca4c66914610297578063d32b8d46146102b8578063d547741f146102cb578063d6ef8ade146102de578063f141fe9b1461030357600080fd5b80638c4112221461023e57806391d1485414610251578063a0a9983e14610264578063a217fddf1461028f57600080fd5b80632f2ff15d116100e95780632f2ff15d146101a957806336568abe146101be578063507b9572146101d1578063579a735e1461020e57806375b238fc1461021757600080fd5b806301ffc9a71461011b5780630821b13f146101435780630b378de214610158578063248a9ca314610178575b600080fd5b61012e610129366004611223565b610324565b60405190151581526020015b60405180910390f35b61014b61035b565b60405161013a919061124d565b61016b6101663660046112b1565b610507565b60405161013a9190611325565b61019b610186366004611338565b60009081526020819052604090206001015490565b60405190815260200161013a565b6101bc6101b73660046112b1565b6105a0565b005b6101bc6101cc3660046112b1565b6105ca565b6101e46101df366004611351565b61064d565b604080516001600160a01b039095168552602085019390935291830152606082015260800161013a565b61019b60025481565b61019b7fa49807205ce4d355092ef5a8a18f56e8913cf4a201fbe287825b095693c2177581565b6101bc61024c366004611338565b610857565b61012e61025f3660046112b1565b610887565b600154610277906001600160a01b031681565b6040516001600160a01b03909116815260200161013a565b61019b600081565b6102aa6102a536600461136e565b6108b0565b60405161013a929190611390565b6101bc6102c6366004611351565b610af8565b6101bc6102d93660046112b1565b610b45565b6102f16102ec3660046112b1565b610b6a565b60405161013a969594939291906113b2565b6103166103113660046113f9565b610c32565b60405161013a929190611436565b60006001600160e01b03198216637965db0b60e01b148061035557506301ffc9a760e01b6001600160e01b03198316145b92915050565b60606000600160009054906101000a90046001600160a01b03166001600160a01b031663609a233d6040518163ffffffff1660e01b815260040160206040518083038186803b1580156103ad57600080fd5b505afa1580156103c1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103e59190611516565b905060008167ffffffffffffffff8111156104025761040261152f565b60405190808252806020026020018201604052801561044757816020015b60408051808201909152600080825260208201528152602001906001900390816104205790505b50905060005b8281101561050057600154604051633aebbcb960e11b8152600481018390526001600160a01b03909116906375d7797290602401604080518083038186803b15801561049857600080fd5b505afa1580156104ac573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104d0919061156e565b8282815181106104e2576104e26115bd565b602002602001018190525080806104f8906115e9565b91505061044d565b5092915050565b600154604051638fa44dc160e01b8152600481018490526001600160a01b038381166024830152606092600092911690638fa44dc19060440160006040518083038186803b15801561055857600080fd5b505afa15801561056c573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261059491908101906116b8565b60a00151949350505050565b6000828152602081905260409020600101546105bb81610f1f565b6105c58383610f2c565b505050565b6001600160a01b038116331461063f5760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b60648201526084015b60405180910390fd5b6106498282610fb0565b5050565b6001546040516313b8fe0d60e11b81526001600160a01b0383811660048301526000928392839283921690632771fc1a9060240160206040518083038186803b15801561069957600080fd5b505afa1580156106ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106d1919061176c565b600154604051630afdbb7160e31b81526001600160a01b0388811660048301529296509116906357eddb889060240160206040518083038186803b15801561071857600080fd5b505afa15801561072c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107509190611516565b60015460405163043803e360e51b81526001600160a01b0388811660048301529295509116906387007c609060240160206040518083038186803b15801561079757600080fd5b505afa1580156107ab573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107cf9190611516565b60015460405163272e974f60e01b81526001600160a01b03888116600483015292945091169063272e974f9060240160206040518083038186803b15801561081657600080fd5b505afa15801561082a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061084e9190611516565b90509193509193565b7fa49807205ce4d355092ef5a8a18f56e8913cf4a201fbe287825b095693c2177561088181610f1f565b50600255565b6000918252602082815260408084206001600160a01b0393909316845291905290205460ff1690565b60606000600160009054906101000a90046001600160a01b03166001600160a01b031663b94063136040518163ffffffff1660e01b815260040160206040518083038186803b15801561090257600080fd5b505afa158015610916573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061093a9190611516565b905060008361094a600187611789565b61095491906117a0565b90508181106109a05760405162461bcd60e51b8152602060048201526018602482015277537461727420696e646578206f7574206f662072616e676560401b6044820152606401610636565b6002548411156109b05760025493505b6000826109bd86846117bf565b116109d1576109cc85836117bf565b6109d3565b825b90506109df8282611789565b67ffffffffffffffff8111156109f7576109f761152f565b604051908082528060200260200182016040528015610a20578160200160208202803683370190505b509350815b81811015610aee57600154604051633671c88760e21b8152600481018390526001600160a01b039091169063d9c7221c9060240160206040518083038186803b158015610a7157600080fd5b505afa158015610a85573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610aa9919061176c565b85610ab48584611789565b81518110610ac457610ac46115bd565b6001600160a01b039092166020928302919091019091015280610ae6816115e9565b915050610a25565b5050509250929050565b7fa49807205ce4d355092ef5a8a18f56e8913cf4a201fbe287825b095693c21775610b2281610f1f565b50600180546001600160a01b0319166001600160a01b0392909216919091179055565b600082815260208190526040902060010154610b6081610f1f565b6105c58383610fb0565b600154604051638fa44dc160e01b8152600481018490526001600160a01b038381166024830152600092839283928392839260609284921690638fa44dc19060440160006040518083038186803b158015610bc457600080fd5b505afa158015610bd8573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610c0091908101906116b8565b8051602082015160408301516060840151608085015160a090950151939e929d50909b50995091975095509350505050565b600154604051638fa44dc160e01b8152600481018690526001600160a01b038581166024830152606092600092839290911690638fa44dc19060440160006040518083038186803b158015610c8657600080fd5b505afa158015610c9a573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610cc291908101906116b8565b60a0810151805191925090600086610cdb60018a611789565b610ce591906117a0565b9050818110610d315760405162461bcd60e51b8152602060048201526018602482015277537461727420696e646578206f7574206f662072616e676560401b6044820152606401610636565b600254871115610d415760025496505b600082610d4e89846117bf565b11610d6257610d5d88836117bf565b610d64565b825b90506000610d728383611789565b67ffffffffffffffff811115610d8a57610d8a61152f565b604051908082528060200260200182016040528015610dff57816020015b610dec6040518060c0016040528060001515815260200160006001600160a01b03168152602001600081526020016000815260200160008152602001606081525090565b815260200190600190039081610da85790505b509050825b82811015610f0d576000600160009054906101000a90046001600160a01b03166001600160a01b0316638fa44dc18f898581518110610e4557610e456115bd565b60200260200101516040518363ffffffff1660e01b8152600401610e7c9291909182526001600160a01b0316602082015260400190565b60006040518083038186803b158015610e9457600080fd5b505afa158015610ea8573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610ed091908101906116b8565b90508083610ede8785611789565b81518110610eee57610eee6115bd565b6020026020010181905250508080610f05906115e9565b915050610e04565b509b929a509198505050505050505050565b610f298133611015565b50565b610f368282610887565b610649576000828152602081815260408083206001600160a01b03851684529091529020805460ff19166001179055610f6c3390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b610fba8282610887565b15610649576000828152602081815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b61101f8282610887565b6106495761102c8161106e565b611037836020611080565b604051602001611048929190611807565b60408051601f198184030181529082905262461bcd60e51b82526106369160040161187c565b60606103556001600160a01b03831660145b6060600061108f8360026117a0565b61109a9060026117bf565b67ffffffffffffffff8111156110b2576110b261152f565b6040519080825280601f01601f1916602001820160405280156110dc576020820181803683370190505b509050600360fc1b816000815181106110f7576110f76115bd565b60200101906001600160f81b031916908160001a905350600f60fb1b81600181518110611126576111266115bd565b60200101906001600160f81b031916908160001a905350600061114a8460026117a0565b6111559060016117bf565b90505b60018111156111cd576f181899199a1a9b1b9c1cb0b131b232b360811b85600f1660108110611189576111896115bd565b1a60f81b82828151811061119f5761119f6115bd565b60200101906001600160f81b031916908160001a90535060049490941c936111c6816118af565b9050611158565b50831561121c5760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e746044820152606401610636565b9392505050565b60006020828403121561123557600080fd5b81356001600160e01b03198116811461121c57600080fd5b602080825282518282018190526000919060409081850190868401855b8281101561128f5781518051855286015186850152928401929085019060010161126a565b5091979650505050505050565b6001600160a01b0381168114610f2957600080fd5b600080604083850312156112c457600080fd5b8235915060208301356112d68161129c565b809150509250929050565b600081518084526020808501945080840160005b8381101561131a5781516001600160a01b0316875295820195908201906001016112f5565b509495945050505050565b60208152600061121c60208301846112e1565b60006020828403121561134a57600080fd5b5035919050565b60006020828403121561136357600080fd5b813561121c8161129c565b6000806040838503121561138157600080fd5b50508035926020909101359150565b6040815260006113a360408301856112e1565b90508260208301529392505050565b861515815260018060a01b038616602082015284604082015283606082015282608082015260c060a082015260006113ed60c08301846112e1565b98975050505050505050565b6000806000806080858703121561140f57600080fd5b8435935060208501356114218161129c565b93969395505050506040820135916060013590565b60006040808301818452808651808352606092508286019150828160051b8701016020808a016000805b85811015611500578a8503605f190187528251805115158652848101516001600160a01b03908116868801528a8201518b880152898201518a8801526080808301519088015260a09182015160c0928801839052805192880183905286019160e08801918591905b818310156114ea578451811684529388019392880192600192909201916114c8565b5050509785019795505091830191600101611460565b5050509690960196909652509295945050505050565b60006020828403121561152857600080fd5b5051919050565b634e487b7160e01b600052604160045260246000fd5b60405160c0810167ffffffffffffffff811182821017156115685761156861152f565b60405290565b60006040828403121561158057600080fd5b6040516040810181811067ffffffffffffffff821117156115a3576115a361152f565b604052825181526020928301519281019290925250919050565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b60006000198214156115fd576115fd6115d3565b5060010190565b805161160f8161129c565b919050565b600082601f83011261162557600080fd5b8151602067ffffffffffffffff808311156116425761164261152f565b8260051b604051601f19603f830116810181811084821117156116675761166761152f565b60405293845285810183019383810192508785111561168557600080fd5b83870191505b848210156116ad57815161169e8161129c565b8352918301919083019061168b565b979650505050505050565b6000602082840312156116ca57600080fd5b815167ffffffffffffffff808211156116e257600080fd5b9083019060c082860312156116f657600080fd5b6116fe611545565b8251801515811461170e57600080fd5b815261171c60208401611604565b602082015260408301516040820152606083015160608201526080830151608082015260a08301518281111561175157600080fd5b61175d87828601611614565b60a08301525095945050505050565b60006020828403121561177e57600080fd5b815161121c8161129c565b60008282101561179b5761179b6115d3565b500390565b60008160001904831182151516156117ba576117ba6115d3565b500290565b600082198211156117d2576117d26115d3565b500190565b60005b838110156117f25781810151838201526020016117da565b83811115611801576000848401525b50505050565b7f416363657373436f6e74726f6c3a206163636f756e742000000000000000000081526000835161183f8160178501602088016117d7565b7001034b99036b4b9b9b4b733903937b6329607d1b60179184019182015283516118708160288401602088016117d7565b01602801949350505050565b602081526000825180602084015261189b8160408501602087016117d7565b601f01601f19169190910160400192915050565b6000816118be576118be6115d3565b50600019019056fea2646970667358221220d4963446da0a4fc55a04178bce9512733336b50d58802a41dd518f0e71f51aa464736f6c63430008090033000000000000000000000000ce12d7f0d936805c604dc8b31d4db6f8138c7d7e

Deployed Bytecode

0x608060405234801561001057600080fd5b50600436106101165760003560e01c80638c411222116100a2578063bca4c66911610071578063bca4c66914610297578063d32b8d46146102b8578063d547741f146102cb578063d6ef8ade146102de578063f141fe9b1461030357600080fd5b80638c4112221461023e57806391d1485414610251578063a0a9983e14610264578063a217fddf1461028f57600080fd5b80632f2ff15d116100e95780632f2ff15d146101a957806336568abe146101be578063507b9572146101d1578063579a735e1461020e57806375b238fc1461021757600080fd5b806301ffc9a71461011b5780630821b13f146101435780630b378de214610158578063248a9ca314610178575b600080fd5b61012e610129366004611223565b610324565b60405190151581526020015b60405180910390f35b61014b61035b565b60405161013a919061124d565b61016b6101663660046112b1565b610507565b60405161013a9190611325565b61019b610186366004611338565b60009081526020819052604090206001015490565b60405190815260200161013a565b6101bc6101b73660046112b1565b6105a0565b005b6101bc6101cc3660046112b1565b6105ca565b6101e46101df366004611351565b61064d565b604080516001600160a01b039095168552602085019390935291830152606082015260800161013a565b61019b60025481565b61019b7fa49807205ce4d355092ef5a8a18f56e8913cf4a201fbe287825b095693c2177581565b6101bc61024c366004611338565b610857565b61012e61025f3660046112b1565b610887565b600154610277906001600160a01b031681565b6040516001600160a01b03909116815260200161013a565b61019b600081565b6102aa6102a536600461136e565b6108b0565b60405161013a929190611390565b6101bc6102c6366004611351565b610af8565b6101bc6102d93660046112b1565b610b45565b6102f16102ec3660046112b1565b610b6a565b60405161013a969594939291906113b2565b6103166103113660046113f9565b610c32565b60405161013a929190611436565b60006001600160e01b03198216637965db0b60e01b148061035557506301ffc9a760e01b6001600160e01b03198316145b92915050565b60606000600160009054906101000a90046001600160a01b03166001600160a01b031663609a233d6040518163ffffffff1660e01b815260040160206040518083038186803b1580156103ad57600080fd5b505afa1580156103c1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103e59190611516565b905060008167ffffffffffffffff8111156104025761040261152f565b60405190808252806020026020018201604052801561044757816020015b60408051808201909152600080825260208201528152602001906001900390816104205790505b50905060005b8281101561050057600154604051633aebbcb960e11b8152600481018390526001600160a01b03909116906375d7797290602401604080518083038186803b15801561049857600080fd5b505afa1580156104ac573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104d0919061156e565b8282815181106104e2576104e26115bd565b602002602001018190525080806104f8906115e9565b91505061044d565b5092915050565b600154604051638fa44dc160e01b8152600481018490526001600160a01b038381166024830152606092600092911690638fa44dc19060440160006040518083038186803b15801561055857600080fd5b505afa15801561056c573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261059491908101906116b8565b60a00151949350505050565b6000828152602081905260409020600101546105bb81610f1f565b6105c58383610f2c565b505050565b6001600160a01b038116331461063f5760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b60648201526084015b60405180910390fd5b6106498282610fb0565b5050565b6001546040516313b8fe0d60e11b81526001600160a01b0383811660048301526000928392839283921690632771fc1a9060240160206040518083038186803b15801561069957600080fd5b505afa1580156106ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106d1919061176c565b600154604051630afdbb7160e31b81526001600160a01b0388811660048301529296509116906357eddb889060240160206040518083038186803b15801561071857600080fd5b505afa15801561072c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107509190611516565b60015460405163043803e360e51b81526001600160a01b0388811660048301529295509116906387007c609060240160206040518083038186803b15801561079757600080fd5b505afa1580156107ab573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107cf9190611516565b60015460405163272e974f60e01b81526001600160a01b03888116600483015292945091169063272e974f9060240160206040518083038186803b15801561081657600080fd5b505afa15801561082a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061084e9190611516565b90509193509193565b7fa49807205ce4d355092ef5a8a18f56e8913cf4a201fbe287825b095693c2177561088181610f1f565b50600255565b6000918252602082815260408084206001600160a01b0393909316845291905290205460ff1690565b60606000600160009054906101000a90046001600160a01b03166001600160a01b031663b94063136040518163ffffffff1660e01b815260040160206040518083038186803b15801561090257600080fd5b505afa158015610916573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061093a9190611516565b905060008361094a600187611789565b61095491906117a0565b90508181106109a05760405162461bcd60e51b8152602060048201526018602482015277537461727420696e646578206f7574206f662072616e676560401b6044820152606401610636565b6002548411156109b05760025493505b6000826109bd86846117bf565b116109d1576109cc85836117bf565b6109d3565b825b90506109df8282611789565b67ffffffffffffffff8111156109f7576109f761152f565b604051908082528060200260200182016040528015610a20578160200160208202803683370190505b509350815b81811015610aee57600154604051633671c88760e21b8152600481018390526001600160a01b039091169063d9c7221c9060240160206040518083038186803b158015610a7157600080fd5b505afa158015610a85573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610aa9919061176c565b85610ab48584611789565b81518110610ac457610ac46115bd565b6001600160a01b039092166020928302919091019091015280610ae6816115e9565b915050610a25565b5050509250929050565b7fa49807205ce4d355092ef5a8a18f56e8913cf4a201fbe287825b095693c21775610b2281610f1f565b50600180546001600160a01b0319166001600160a01b0392909216919091179055565b600082815260208190526040902060010154610b6081610f1f565b6105c58383610fb0565b600154604051638fa44dc160e01b8152600481018490526001600160a01b038381166024830152600092839283928392839260609284921690638fa44dc19060440160006040518083038186803b158015610bc457600080fd5b505afa158015610bd8573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610c0091908101906116b8565b8051602082015160408301516060840151608085015160a090950151939e929d50909b50995091975095509350505050565b600154604051638fa44dc160e01b8152600481018690526001600160a01b038581166024830152606092600092839290911690638fa44dc19060440160006040518083038186803b158015610c8657600080fd5b505afa158015610c9a573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610cc291908101906116b8565b60a0810151805191925090600086610cdb60018a611789565b610ce591906117a0565b9050818110610d315760405162461bcd60e51b8152602060048201526018602482015277537461727420696e646578206f7574206f662072616e676560401b6044820152606401610636565b600254871115610d415760025496505b600082610d4e89846117bf565b11610d6257610d5d88836117bf565b610d64565b825b90506000610d728383611789565b67ffffffffffffffff811115610d8a57610d8a61152f565b604051908082528060200260200182016040528015610dff57816020015b610dec6040518060c0016040528060001515815260200160006001600160a01b03168152602001600081526020016000815260200160008152602001606081525090565b815260200190600190039081610da85790505b509050825b82811015610f0d576000600160009054906101000a90046001600160a01b03166001600160a01b0316638fa44dc18f898581518110610e4557610e456115bd565b60200260200101516040518363ffffffff1660e01b8152600401610e7c9291909182526001600160a01b0316602082015260400190565b60006040518083038186803b158015610e9457600080fd5b505afa158015610ea8573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610ed091908101906116b8565b90508083610ede8785611789565b81518110610eee57610eee6115bd565b6020026020010181905250508080610f05906115e9565b915050610e04565b509b929a509198505050505050505050565b610f298133611015565b50565b610f368282610887565b610649576000828152602081815260408083206001600160a01b03851684529091529020805460ff19166001179055610f6c3390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b610fba8282610887565b15610649576000828152602081815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b61101f8282610887565b6106495761102c8161106e565b611037836020611080565b604051602001611048929190611807565b60408051601f198184030181529082905262461bcd60e51b82526106369160040161187c565b60606103556001600160a01b03831660145b6060600061108f8360026117a0565b61109a9060026117bf565b67ffffffffffffffff8111156110b2576110b261152f565b6040519080825280601f01601f1916602001820160405280156110dc576020820181803683370190505b509050600360fc1b816000815181106110f7576110f76115bd565b60200101906001600160f81b031916908160001a905350600f60fb1b81600181518110611126576111266115bd565b60200101906001600160f81b031916908160001a905350600061114a8460026117a0565b6111559060016117bf565b90505b60018111156111cd576f181899199a1a9b1b9c1cb0b131b232b360811b85600f1660108110611189576111896115bd565b1a60f81b82828151811061119f5761119f6115bd565b60200101906001600160f81b031916908160001a90535060049490941c936111c6816118af565b9050611158565b50831561121c5760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e746044820152606401610636565b9392505050565b60006020828403121561123557600080fd5b81356001600160e01b03198116811461121c57600080fd5b602080825282518282018190526000919060409081850190868401855b8281101561128f5781518051855286015186850152928401929085019060010161126a565b5091979650505050505050565b6001600160a01b0381168114610f2957600080fd5b600080604083850312156112c457600080fd5b8235915060208301356112d68161129c565b809150509250929050565b600081518084526020808501945080840160005b8381101561131a5781516001600160a01b0316875295820195908201906001016112f5565b509495945050505050565b60208152600061121c60208301846112e1565b60006020828403121561134a57600080fd5b5035919050565b60006020828403121561136357600080fd5b813561121c8161129c565b6000806040838503121561138157600080fd5b50508035926020909101359150565b6040815260006113a360408301856112e1565b90508260208301529392505050565b861515815260018060a01b038616602082015284604082015283606082015282608082015260c060a082015260006113ed60c08301846112e1565b98975050505050505050565b6000806000806080858703121561140f57600080fd5b8435935060208501356114218161129c565b93969395505050506040820135916060013590565b60006040808301818452808651808352606092508286019150828160051b8701016020808a016000805b85811015611500578a8503605f190187528251805115158652848101516001600160a01b03908116868801528a8201518b880152898201518a8801526080808301519088015260a09182015160c0928801839052805192880183905286019160e08801918591905b818310156114ea578451811684529388019392880192600192909201916114c8565b5050509785019795505091830191600101611460565b5050509690960196909652509295945050505050565b60006020828403121561152857600080fd5b5051919050565b634e487b7160e01b600052604160045260246000fd5b60405160c0810167ffffffffffffffff811182821017156115685761156861152f565b60405290565b60006040828403121561158057600080fd5b6040516040810181811067ffffffffffffffff821117156115a3576115a361152f565b604052825181526020928301519281019290925250919050565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b60006000198214156115fd576115fd6115d3565b5060010190565b805161160f8161129c565b919050565b600082601f83011261162557600080fd5b8151602067ffffffffffffffff808311156116425761164261152f565b8260051b604051601f19603f830116810181811084821117156116675761166761152f565b60405293845285810183019383810192508785111561168557600080fd5b83870191505b848210156116ad57815161169e8161129c565b8352918301919083019061168b565b979650505050505050565b6000602082840312156116ca57600080fd5b815167ffffffffffffffff808211156116e257600080fd5b9083019060c082860312156116f657600080fd5b6116fe611545565b8251801515811461170e57600080fd5b815261171c60208401611604565b602082015260408301516040820152606083015160608201526080830151608082015260a08301518281111561175157600080fd5b61175d87828601611614565b60a08301525095945050505050565b60006020828403121561177e57600080fd5b815161121c8161129c565b60008282101561179b5761179b6115d3565b500390565b60008160001904831182151516156117ba576117ba6115d3565b500290565b600082198211156117d2576117d26115d3565b500190565b60005b838110156117f25781810151838201526020016117da565b83811115611801576000848401525b50505050565b7f416363657373436f6e74726f6c3a206163636f756e742000000000000000000081526000835161183f8160178501602088016117d7565b7001034b99036b4b9b9b4b733903937b6329607d1b60179184019182015283516118708160288401602088016117d7565b01602801949350505050565b602081526000825180602084015261189b8160408501602087016117d7565b601f01601f19169190910160400192915050565b6000816118be576118be6115d3565b50600019019056fea2646970667358221220d4963446da0a4fc55a04178bce9512733336b50d58802a41dd518f0e71f51aa464736f6c63430008090033

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

000000000000000000000000ce12d7f0d936805c604dc8b31d4db6f8138c7d7e

-----Decoded View---------------
Arg [0] : _affiliatesContract (address): 0xce12d7F0d936805C604DC8B31d4Db6F8138C7D7E

-----Encoded View---------------
1 Constructor Arguments found :
Arg [0] : 000000000000000000000000ce12d7f0d936805c604dc8b31d4db6f8138c7d7e


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

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.