ETH Price: $2,107.09 (+1.37%)

Contract

0x00aAEfE80E43ffd60236aec0FC8a4BA3f4Be6fc3
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To
Add Trait209342002024-10-10 9:05:35520 days ago1728551135IN
0x00aAEfE8...3f4Be6fc3
0 ETH0.0575007812.91916498

Latest 2 internal transactions

Advanced mode:
Parent Transaction Hash Method Block
From
To
0x3d602d80209342002024-10-10 9:05:35520 days ago1728551135
0x00aAEfE8...3f4Be6fc3
 Contract Creation0 ETH
0x60a06040209342002024-10-10 9:05:35520 days ago1728551135
0x00aAEfE8...3f4Be6fc3
 Contract Creation0 ETH
Loading...
Loading
Loading...
Loading
Cross-Chain Transactions

Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
UTDigitalRedeemFactory

Compiler Version
v0.8.25+commit.b61c2a91

Optimization Enabled:
Yes with 200 runs

Other Settings:
paris EvmVersion
// SPDX-License-Identifier: UNLICENCED
pragma solidity 0.8.25;

import "../../@galaxis/registries/contracts/CommunityList.sol";
import "../../@galaxis/registries/contracts/CommunityRegistry.sol";
import "../Registry/GTRegistry.sol";
import "../extras/recovery/BlackHolePrevention.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../extras/recovery/BlackHolePrevention.sol";
import "./GenericTraitFactory.sol";
import {DigitalRedeemConsumer} from "../../TraitConsumers/DigitalRedeemConsumer.sol";

/**
 * @dev This factory is used to create new traits (perks) in a community
 */
contract UTDigitalRedeemFactory is GenericTraitFactory {

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


    function version() public pure override returns (uint256) {
        return 2024091301;
    }

    function TRAIT_TYPE() public pure override returns (uint8) {
        return 6;
    }

    function REGISTRY_KEY_FACTORY() public pure override returns (string memory) {
        return "TRAIT_TYPE_6_FACTORY";
    }

    function GOLDEN_KEY() public pure override returns (string memory) {
        return "GOLDEN_TRAIT_TYPE_6";
    }

    constructor(address _galaxisRegistry) GenericTraitFactory(_galaxisRegistry) {
        
    }


    function deploy(
        address traitRegistryAddress,
        uint16 traitId,
        traitConfig memory _traitConfig,
        bytes[] memory traitDefaults
    )
        internal
        override
        returns (address controllerCtrAddress, address storageCtrAddress)
    {
        address controllerCtr = GTRegistry(traitRegistryAddress)
            .getDefaultTraitControllerByType(TRAIT_TYPE());

        if (controllerCtr == address(0)) {
            controllerCtr = address(new DigitalRedeemConsumer(address(galaxisRegistry)));
            
            GTRegistry(traitRegistryAddress).setDefaultTraitControllerType(
                controllerCtr,
                TRAIT_TYPE()
            );

            if (!thisCommunityRegistry.hasRole(TRAIT_CONSUMER, controllerCtr)) {
                thisCommunityRegistry.grantRole(TRAIT_CONSUMER, controllerCtr);
            }
            if (!thisCommunityRegistry.hasRole(RANDOM_CONSUMER, controllerCtr)) {
                thisCommunityRegistry.grantRole(RANDOM_CONSUMER, controllerCtr);
            }
        }

        // Launch new trait contract via proxy
        address traitProxy = newProxy(GOLDEN_KEY());
        GenericTraitInterface trait = GenericTraitInterface(
            traitProxy
        );

        // init proxy contract
        trait.setup(traitRegistryAddress, traitId, _traitConfig, traitDefaults);
        trait.init();

        return (controllerCtr, address(trait));
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.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(uint160(account), 20),
                        " 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());
        }
    }
}

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

pragma solidity ^0.8.0;

import "./IAccessControlEnumerable.sol";
import "./AccessControl.sol";
import "../utils/structs/EnumerableSet.sol";

/**
 * @dev Extension of {AccessControl} that allows enumerating the members of each role.
 */
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
    using EnumerableSet for EnumerableSet.AddressSet;

    mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;

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

    /**
     * @dev Returns one of the accounts that have `role`. `index` must be a
     * value between 0 and {getRoleMemberCount}, non-inclusive.
     *
     * Role bearers are not sorted in any particular way, and their ordering may
     * change at any point.
     *
     * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
     * you perform all queries on the same block. See the following
     * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
     * for more information.
     */
    function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {
        return _roleMembers[role].at(index);
    }

    /**
     * @dev Returns the number of accounts that have `role`. Can be used
     * together with {getRoleMember} to enumerate all bearers of a role.
     */
    function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {
        return _roleMembers[role].length();
    }

    /**
     * @dev Overload {_grantRole} to track enumerable memberships
     */
    function _grantRole(bytes32 role, address account) internal virtual override {
        super._grantRole(role, account);
        _roleMembers[role].add(account);
    }

    /**
     * @dev Overload {_revokeRole} to track enumerable memberships
     */
    function _revokeRole(bytes32 role, address account) internal virtual override {
        super._revokeRole(role, account);
        _roleMembers[role].remove(account);
    }
}

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)

pragma solidity ^0.8.0;

import "./IAccessControl.sol";

/**
 * @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
 */
interface IAccessControlEnumerable is IAccessControl {
    /**
     * @dev Returns one of the accounts that have `role`. `index` must be a
     * value between 0 and {getRoleMemberCount}, non-inclusive.
     *
     * Role bearers are not sorted in any particular way, and their ordering may
     * change at any point.
     *
     * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
     * you perform all queries on the same block. See the following
     * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
     * for more information.
     */
    function getRoleMember(bytes32 role, uint256 index) external view returns (address);

    /**
     * @dev Returns the number of accounts that have `role`. Can be used
     * together with {getRoleMember} to enumerate all bearers of a role.
     */
    function getRoleMemberCount(bytes32 role) external view returns (uint256);
}

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

pragma solidity ^0.8.0;

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

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

File 7 of 38 : ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        // On the first call to nonReentrant, _notEntered will be true
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;

        _;

        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }
}

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.0;

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

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes calldata data
    ) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool _approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

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

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC777Token standard as defined in the EIP.
 *
 * This contract uses the
 * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let
 * token holders and recipients react to token movements by using setting implementers
 * for the associated interfaces in said registry. See {IERC1820Registry} and
 * {ERC1820Implementer}.
 */
interface IERC777 {
    /**
     * @dev Emitted when `amount` tokens are created by `operator` and assigned to `to`.
     *
     * Note that some additional user `data` and `operatorData` can be logged in the event.
     */
    event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);

    /**
     * @dev Emitted when `operator` destroys `amount` tokens from `account`.
     *
     * Note that some additional user `data` and `operatorData` can be logged in the event.
     */
    event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);

    /**
     * @dev Emitted when `operator` is made operator for `tokenHolder`
     */
    event AuthorizedOperator(address indexed operator, address indexed tokenHolder);

    /**
     * @dev Emitted when `operator` is revoked its operator status for `tokenHolder`
     */
    event RevokedOperator(address indexed operator, address indexed tokenHolder);

    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the smallest part of the token that is not divisible. This
     * means all token operations (creation, movement and destruction) must have
     * amounts that are a multiple of this number.
     *
     * For most token contracts, this value will equal 1.
     */
    function granularity() external view returns (uint256);

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

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

    /**
     * @dev Moves `amount` tokens from the caller's account to `recipient`.
     *
     * If send or receive hooks are registered for the caller and `recipient`,
     * the corresponding functions will be called with `data` and empty
     * `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
     *
     * Emits a {Sent} event.
     *
     * Requirements
     *
     * - the caller must have at least `amount` tokens.
     * - `recipient` cannot be the zero address.
     * - if `recipient` is a contract, it must implement the {IERC777Recipient}
     * interface.
     */
    function send(
        address recipient,
        uint256 amount,
        bytes calldata data
    ) external;

    /**
     * @dev Destroys `amount` tokens from the caller's account, reducing the
     * total supply.
     *
     * If a send hook is registered for the caller, the corresponding function
     * will be called with `data` and empty `operatorData`. See {IERC777Sender}.
     *
     * Emits a {Burned} event.
     *
     * Requirements
     *
     * - the caller must have at least `amount` tokens.
     */
    function burn(uint256 amount, bytes calldata data) external;

    /**
     * @dev Returns true if an account is an operator of `tokenHolder`.
     * Operators can send and burn tokens on behalf of their owners. All
     * accounts are their own operator.
     *
     * See {operatorSend} and {operatorBurn}.
     */
    function isOperatorFor(address operator, address tokenHolder) external view returns (bool);

    /**
     * @dev Make an account an operator of the caller.
     *
     * See {isOperatorFor}.
     *
     * Emits an {AuthorizedOperator} event.
     *
     * Requirements
     *
     * - `operator` cannot be calling address.
     */
    function authorizeOperator(address operator) external;

    /**
     * @dev Revoke an account's operator status for the caller.
     *
     * See {isOperatorFor} and {defaultOperators}.
     *
     * Emits a {RevokedOperator} event.
     *
     * Requirements
     *
     * - `operator` cannot be calling address.
     */
    function revokeOperator(address operator) external;

    /**
     * @dev Returns the list of default operators. These accounts are operators
     * for all token holders, even if {authorizeOperator} was never called on
     * them.
     *
     * This list is immutable, but individual holders may revoke these via
     * {revokeOperator}, in which case {isOperatorFor} will return false.
     */
    function defaultOperators() external view returns (address[] memory);

    /**
     * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must
     * be an operator of `sender`.
     *
     * If send or receive hooks are registered for `sender` and `recipient`,
     * the corresponding functions will be called with `data` and
     * `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
     *
     * Emits a {Sent} event.
     *
     * Requirements
     *
     * - `sender` cannot be the zero address.
     * - `sender` must have at least `amount` tokens.
     * - the caller must be an operator for `sender`.
     * - `recipient` cannot be the zero address.
     * - if `recipient` is a contract, it must implement the {IERC777Recipient}
     * interface.
     */
    function operatorSend(
        address sender,
        address recipient,
        uint256 amount,
        bytes calldata data,
        bytes calldata operatorData
    ) external;

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the total supply.
     * The caller must be an operator of `account`.
     *
     * If a send hook is registered for `account`, the corresponding function
     * will be called with `data` and `operatorData`. See {IERC777Sender}.
     *
     * Emits a {Burned} event.
     *
     * Requirements
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     * - the caller must be an operator for `account`.
     */
    function operatorBurn(
        address account,
        uint256 amount,
        bytes calldata data,
        bytes calldata operatorData
    ) external;

    event Sent(
        address indexed operator,
        address indexed from,
        address indexed to,
        uint256 amount,
        bytes data,
        bytes operatorData
    );
}

File 11 of 38 : IERC777Recipient.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC777/IERC777Recipient.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP.
 *
 * Accounts can be notified of {IERC777} tokens being sent to them by having a
 * contract implement this interface (contract holders can be their own
 * implementer) and registering it on the
 * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
 *
 * See {IERC1820Registry} and {ERC1820Implementer}.
 */
interface IERC777Recipient {
    /**
     * @dev Called by an {IERC777} token contract whenever tokens are being
     * moved or created into a registered account (`to`). The type of operation
     * is conveyed by `from` being the zero address or not.
     *
     * This call occurs _after_ the token contract's state is updated, so
     * {IERC777-balanceOf}, etc., can be used to query the post-operation state.
     *
     * This function may revert to prevent the operation from being executed.
     */
    function tokensReceived(
        address operator,
        address from,
        address to,
        uint256 amount,
        bytes calldata userData,
        bytes calldata operatorData
    ) external;
}

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

pragma solidity ^0.8.0;

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

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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;
    }
}

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

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

pragma solidity ^0.8.0;

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _HEX_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) {
        // Inspired by OraclizeAPI's implementation - MIT licence
        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol

        if (value == 0) {
            return "0";
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        bytes memory buffer = new bytes(digits);
        while (value != 0) {
            digits -= 1;
            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
            value /= 10;
        }
        return string(buffer);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        if (value == 0) {
            return "0x00";
        }
        uint256 temp = value;
        uint256 length = 0;
        while (temp != 0) {
            length++;
            temp >>= 8;
        }
        return toHexString(value, length);
    }

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/structs/EnumerableSet.sol)

pragma solidity ^0.8.0;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 *  Trying to delete such a structure from storage will likely result in data corruption, rendering the structure unusable.
 *  See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 *  In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position of the value in the `values` array, plus 1 because index 0
        // means a value is not in the set.
        mapping(bytes32 => uint256) _indexes;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._indexes[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We read and store the value's index to prevent multiple reads from the same storage slot
        uint256 valueIndex = set._indexes[value];

        if (valueIndex != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 toDeleteIndex = valueIndex - 1;
            uint256 lastIndex = set._values.length - 1;

            if (lastIndex != toDeleteIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the last value to the index where the value to delete is
                set._values[toDeleteIndex] = lastValue;
                // Update the index for the moved value
                set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the index for the deleted slot
            delete set._indexes[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._indexes[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        return _values(set._inner);
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }
}

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.25;

import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
import "./Versionable/IVersionable.sol";

contract CommunityList is AccessControlEnumerable, IVersionable { 

    function version() external pure returns (uint256) {
        return 2024040301;
    }

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


    uint256                              public numberOfEntries;

    struct community_entry {
        string      name;
        address     registry;
        uint32      id;
    }
    
    mapping(uint32 => community_entry)  public communities;   // community_id => record
    mapping(uint256 => uint32)           public index;         // entryNumber => community_id for enumeration

    event CommunityAdded(uint256 pos, string community_name, address community_registry, uint32 community_id);

    constructor() {
        _setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
        _setupRole(CONTRACT_ADMIN,msg.sender);
    }

    function addCommunity(uint32 community_id, string memory community_name, address community_registry) external onlyRole(CONTRACT_ADMIN) {
        uint256 pos = numberOfEntries++;
        index[pos]  = community_id;
        communities[community_id] = community_entry(community_name, community_registry, community_id);
        emit CommunityAdded(pos, community_name, community_registry, community_id);
    }

}

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.25;

import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./Versionable/IVersionable.sol";
import "./UsesGalaxisRegistry.sol";

contract CommunityRegistry is AccessControlEnumerable, UsesGalaxisRegistry, IVersionable  {

    function version() virtual external pure returns(uint256) {
        return 2024040401;
    }

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

    uint32                      public  community_id;
    string                      public  community_name;
    

    mapping(bytes32 => address)         addresses;
    mapping(bytes32 => uint256)         uints;
    mapping(bytes32 => bool)            booleans;
    mapping(bytes32 => string)          strings;

    mapping (uint => string)    public  addressEntries;
    mapping (uint => string)    public  uintEntries;
    mapping (uint => string)    public  boolEntries;
    mapping (uint => string)    public  stringEntries;
    uint                        public  numberOfAddresses;
    uint                        public  numberOfUINTs;
    uint                        public  numberOfBooleans;
    uint                        public  numberOfStrings;

    bool                                initialised;

    bool                        public  independant;

    event IndependanceDay(bool gain_independance);

    modifier onlyAdmin() {
        require(
            isUserCommunityAdmin(COMMUNITY_REGISTRY_ADMIN,msg.sender)
            ,"CommunityRegistry : Unauthorised");
        _;
    }

    modifier onlyPropertyAdmin() {
        require(
            isUserCommunityAdmin(COMMUNITY_REGISTRY_ADMIN,msg.sender) ||
            hasRole(COMMUNITY_REGISTRY_ADMIN,msg.sender)
            ,"CommunityRegistry : Unauthorised");
        _;
    }



    function isUserCommunityAdmin(bytes32 role, address user) public view returns (bool) {
        if (hasRole(DEFAULT_ADMIN_ROLE,user) ) return true; // community_admin can do anything
        if (independant){        
            return(
                hasRole(role,user)
            );
        } else { // for Factories
           return(roleManager().hasRole(role,user));
        }
    }

    function roleManager() internal view returns (IAccessControlEnumerable) {
        address addr = galaxisRegistry.getRegistryAddress("ROLE_MANAGER"); // universal
        if (addr != address(0)) return IAccessControlEnumerable(addr);
        addr = galaxisRegistry.getRegistryAddress("MAINNET_CHAIN_IMPLEMENTER"); // mainnet
        if (addr != address(0)) return IAccessControlEnumerable(addr);
        addr = galaxisRegistry.getRegistryAddress("L2_RECEIVER"); // mainnet
        require(addr != address(0),"CommunityRegistry : no higher authority found");
        return IAccessControlEnumerable(addr);
    }

    function grantRole(bytes32 key, address user) public override(AccessControl,IAccessControl) onlyAdmin {
        _grantRole(key,user); // need to be able to grant it
    }


 
    constructor (
        address _galaxisRegistry,
        uint32  _community_id, 
        address _community_admin, 
        string memory _community_name
    ) UsesGalaxisRegistry(_galaxisRegistry){
        _init(_community_id,_community_admin,_community_name);
    }

    
    function init(
        uint32  _community_id, 
        address _community_admin, 
        string memory _community_name
    ) external {
        _init(_community_id,_community_admin,_community_name);
    }

    function _init(
        uint32  _community_id, 
        address _community_admin, 
        string memory _community_name
    ) internal {
        require(!initialised,"This can only be called once");
        initialised = true;
        community_id = _community_id;
        community_name  = _community_name;
        _setupRole(DEFAULT_ADMIN_ROLE, _community_admin); // default admin = launchpad
    }



    event AdminUpdated(address user, bool isAdmin);
    event AppAdminChanged(address app,address user,bool state);
    //===
    event AddressChanged(string key, address value);
    event UintChanged(string key, uint256 value);
    event BooleanChanged(string key, bool value);
    event StringChanged(string key, string value);

    function setIndependant(bool gain_independance) external onlyAdmin {
        if (independant != gain_independance) {
                independant = gain_independance;
                emit IndependanceDay(gain_independance);
        }
    }


    function setAdmin(address user,bool status ) external onlyAdmin {
        if (status)
            _grantRole(COMMUNITY_REGISTRY_ADMIN,user);
        else
            _revokeRole(COMMUNITY_REGISTRY_ADMIN,user);
    }

    function hash(string memory field) internal pure returns (bytes32) {
        return keccak256(abi.encode(field));
    }

    function setRegistryAddress(string memory fn, address value) external onlyPropertyAdmin {
        bytes32 hf = hash(fn);
        addresses[hf] = value;
        addressEntries[numberOfAddresses++] = fn;
        emit AddressChanged(fn,value);
    }

    function setRegistryBool(string memory fn, bool value) external onlyPropertyAdmin {
        bytes32 hf = hash(fn);
        booleans[hf] = value;
        boolEntries[numberOfBooleans++] = fn;
        emit BooleanChanged(fn,value);
    }

    function setRegistryString(string memory fn, string memory value) external onlyPropertyAdmin {
        bytes32 hf = hash(fn);
        strings[hf] = value;
        stringEntries[numberOfStrings++] = fn;
        emit StringChanged(fn,value);
    }

    function setRegistryUINT(string memory fn, uint value) external onlyPropertyAdmin {
        bytes32 hf = hash(fn);
        uints[hf] = value;
        uintEntries[numberOfUINTs++] = fn;
        emit UintChanged(fn,value);
    }

    function getRegistryAddress(string memory key) external view returns (address) {
        return addresses[hash(key)];
    }

    function getRegistryBool(string memory key) external view returns (bool) {
        return booleans[hash(key)];
    }

    function getRegistryUINT(string memory key) external view returns (uint256) {
        return uints[hash(key)];
    }

    function getRegistryString(string memory key) external view returns (string memory) {
        return strings[hash(key)];
    }

}

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.25;

interface ICommunityList {
    // struct community_entry {
    //     string      name;
    //     address     registry;
    //     uint32      id;
    // }
    // mapping(uint32 => community_entry)  public communities;   // community_id => record

    // function communities(uint32) external returns (struct community_entry memory);
    function communities(uint32) external view returns (string memory, address, uint32);
    function addCommunity(uint32, string memory, address community_registry) external;
}

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.25;

interface IRegistry {
    function setRegistryAddress(string memory fn, address value) external ;
    function setRegistryBool(string memory fn, bool value) external ;
    function setRegistryUINT(string memory key) external returns (uint256) ;
    function setRegistryString(string memory fn, string memory value) external ;
    function setAdmin(address user,bool status ) external;
    function setAppAdmin(address app, address user, bool state) external;

    function getRegistryAddress(string memory key) external view returns (address) ;
    function getRegistryBool(string memory key) external view returns (bool);
    function getRegistryUINT(string memory key) external view returns (uint256) ;
    function getRegistryString(string memory key) external view returns (string memory) ;
    function isAdmin(address user) external view returns (bool) ;
    function isAppAdmin(address app, address user) external view returns (bool);

    function numberOfAddresses() external view returns(uint256);
    function addressEntries(uint256) external view returns(string memory);
}

// SPDX-License-Identifier: CC0-1.0
pragma solidity 0.8.25;

import "./UsesGalaxisRegistry.sol";

// EIP 1167 MinimalProxy Contract
contract NewProxy  is UsesGalaxisRegistry {
    error FailedCreateClone();

    constructor(address _galaxisRegistry) UsesGalaxisRegistry(_galaxisRegistry) {
    }

    function newProxy(string memory golden) public payable returns (address result) {
        address target = galaxisRegistry.getRegistryAddress(golden);
        bytes20 targetBytes = bytes20(target);
        assembly {
            let clone := mload(0x40)
            mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
            mstore(add(clone, 0x14), targetBytes)
            mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
            result := create(0, clone, 0x37)
        }
        if (result == address(0)) {
            revert FailedCreateClone();
        }
    }


}

File 22 of 38 : UsesGalaxisRegistry.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.25;

import "./IRegistry.sol";

contract UsesGalaxisRegistry {

    IRegistry   immutable   public   galaxisRegistry;

    constructor(address _galaxisRegistry) {
        galaxisRegistry = IRegistry(_galaxisRegistry);
    }

}

//SPDX-License-Identifier: Unlicensed
pragma solidity 0.8.25;

import "./IVersionable.sol";

/**
 * @title IGenericVersionable
 * @dev Interface for generic versionable contracts extending IVersionable.
 */
interface IGenericVersionable is IVersionable {
    /**
     * @notice Get the base version of the contract.
     * @return The base version.
     */
    function baseVersion() external pure returns (uint256);
}

File 24 of 38 : IVersionable.sol
//SPDX-License-Identifier: Unlicensed
pragma solidity 0.8.25;

/**
 * @title IVersionable
 * @dev Interface for versionable contracts.
 */
interface IVersionable {
    /**
     * @notice Get the current version of the contract.
     * @return The current version.
     */
    function version() external pure returns (uint256);
}

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.25;

interface IActionHub {

    struct ExpandedTokenContracts {
        address _communityRegistryContract;
        address _tokenContract;
        address _traitRegistryContract;
        address _traitImplementerContract;
        address _traitImplementerContractFirstTrait;
        address _membershipTokenContract;
        address _tokenDepositorContract;
    }

    enum ActionType {
        NONE,
        PAY_ROYALTIES,
        USE_TRAIT,
        FORWARD_TO
    }

    struct UserAction {
        ActionType _type;
        uint32 membershipCardId;
        uint32 communityId;
        uint32 collectionId;
        uint32 tokenId;
        uint16 traitId;
        address consumer;
        bytes userData;
    }

    function refreshRegistries() external;
    function doAction(UserAction[] memory messages) external;
}

// SPDX-License-Identifier: UNLICENCED
pragma solidity 0.8.25;

interface IPaymentMatrix {
    function getDevIDAndAmountForTraitType(uint16 _traitType) external view returns(uint256 devId, uint256 amount);
    function getArtistIDAndAmountForCollection(uint32 _communityId, uint32 _collectionId) external view returns(uint256 artistId, uint256 amount);
}

// SPDX-License-Identifier: UNLICENCED
pragma solidity 0.8.25;

import "./GenericTraitConsumer.sol";

import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../@galaxis/registries/contracts/CommunityRegistry.sol";
import "../Traits/interfaces/IECRegistry.sol";

import {DigitalRedeem, TraitStatus} from "../Traits/Implementers/DigitalRedeem/DigitalRedeem.sol";
import {ICommunityVaultsRegistry} from "../vaults/interfaces/ICommunityVaultsRegistry.sol";
import {IGenericVault} from "../vaults/interfaces/IGenericVault.sol";

import {GenericTraitConsumer} from "./GenericTraitConsumer.sol";

contract DigitalRedeemConsumer is GenericTraitConsumer, ReentrancyGuard {
    error DigitalRedeemConsumerUserActionAndUserDataTokenIdDoNotMatch(
        uint32 communityId,
        uint32 collectionId,
        uint32 action_tokenId,
        uint32 userData_tokenId
    );

    error DigitalRedeemConsumerNotOwnerOfToken(
        address currentOwner,
        uint32 communityId,
        uint32 collectionId,
        uint32 tokenId
    );

    error DigitalRedeemConsumerTraitDoesNotExist(
        uint32 communityId,
        uint32 collectionId,
        uint32 tokenId,
        uint16 traitId
    );

    error DigitalRedeemConsumerInvalidTraitType(uint16 traitType);

    struct UserDataMessage {
        uint32 tokenId;
        uint16 traitId;
        bytes redeemData;
    }

    function version() public pure virtual override returns (uint256) {
        return 2024040401;
    }

    constructor(address _galaxisRegistry) GenericTraitConsumer(_galaxisRegistry) {
        
    }


    function handleAction(
        address from,
        IActionHub.ExpandedTokenContracts calldata etc,
        IActionHub.UserAction calldata action
    ) internal virtual override nonReentrant {
        UserDataMessage memory message_ = abi.decode(
            action.userData,
            (UserDataMessage)
        );

        // make sure the token account is the same as the one in the message we received
        if (message_.tokenId != action.tokenId) {
            revert DigitalRedeemConsumerUserActionAndUserDataTokenIdDoNotMatch(
                action.communityId,
                action.collectionId,
                action.tokenId,
                message_.tokenId
            );
        }

        IERC721 token_ = IERC721(etc._tokenContract);
        address ownerOfToken_ = token_.ownerOf(message_.tokenId);

        if (ownerOfToken_ != from) {
            revert DigitalRedeemConsumerNotOwnerOfToken(
                ownerOfToken_,
                action.communityId,
                action.collectionId,
                message_.tokenId
            );
        }

        // find trait implementer
        DigitalRedeem trait = DigitalRedeem(
            IECRegistry(etc._traitRegistryContract).getImplementer(
                message_.traitId
            )
        );

        if (address(trait) == address(0)) {
            revert DigitalRedeemConsumerTraitDoesNotExist(
                action.communityId,
                action.collectionId,
                message_.tokenId,
                message_.traitId
            );
        }

        uint16 traitType_ = trait.TRAIT_TYPE();
        if (traitType_ != 6) {
            revert DigitalRedeemConsumerInvalidTraitType(traitType_);
        }

        if (trait.status(message_.tokenId) == uint8(TraitStatus.ACTIVE)) {
            ICommunityVaultsRegistry communityVaultsRegistry_ = ICommunityVaultsRegistry(
                CommunityRegistry(etc._communityRegistryContract).getRegistryAddress("COMMUNITY_VAULTS_REGISTRY")
            );

            IGenericVault vault_ = IGenericVault(
                communityVaultsRegistry_.getVaultAddressById(trait.vaultID())
            );

            vault_.traitWithdraw(
                IGenericVault.TraitWithdrawParams(
                    trait,
                    message_.tokenId,
                    message_.redeemData
                )
            );

            // ReentrancyGuard takes care of this
            trait.decrementCounter(message_.tokenId);
        }
    }
}

// SPDX-License-Identifier: UNLICENCED
pragma solidity 0.8.25;

import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC777/IERC777Recipient.sol";
import "@openzeppelin/contracts/token/ERC777/IERC777.sol";
import "../Traits/interfaces/IECRegistry.sol";
import "../@galaxis/registries/contracts/ICommunityList.sol";
import "../@galaxis/registries/contracts/CommunityRegistry.sol";
import "../Traits/Implementers/Generic/GenericTrait.sol";
import "../ActionHub/IActionHub.sol";
import "./IGenericTraitConsumer.sol";

 
contract GenericTraitConsumer is IGenericTraitConsumer, UsesGalaxisRegistry {
    using Strings for uint256;
	
    function baseVersion() public pure returns (uint256) {
        return 2023092401;
    }

    function version() public pure virtual returns (uint256) {
        return 2024040401;
    }

    constructor(address _galaxisRegistry) UsesGalaxisRegistry(_galaxisRegistry) {

    }


    function doAction(
        address from,
        IActionHub.ExpandedTokenContracts calldata etc,
        IActionHub.UserAction calldata action
    ) external {
        require(msg.sender == galaxisRegistry.getRegistryAddress("ACTION_HUB"), "GenericTraitConsumer: invalid msg.sender");
        require(action._type == IActionHub.ActionType.USE_TRAIT, "GenericTraitConsumer: invalid ActionType");
        handleAction(from, etc, action);
    }

    function handleAction(
        address from,
        IActionHub.ExpandedTokenContracts calldata etc,
        IActionHub.UserAction calldata action
    ) internal virtual {
        
    }
   

}

File 29 of 38 : IGenericTraitConsumer.sol
// SPDX-License-Identifier: UNLICENCED
pragma solidity 0.8.25;

import "../ActionHub/IActionHub.sol";
import "../@galaxis/registries/contracts/Versionable/IGenericVersionable.sol";

interface IGenericTraitConsumer is IGenericVersionable {
    function doAction(
        address from,
        IActionHub.ExpandedTokenContracts calldata etc,
        IActionHub.UserAction calldata action
    ) external;
}

// SPDX-License-Identifier: UNLICENCED
pragma solidity 0.8.25;

import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract BlackHolePrevention is Ownable {
    // blackhole prevention methods
    function retrieveETH() external onlyOwner {
        payable(msg.sender).transfer(address(this).balance);
    }
    
    function retrieveERC20(address _tracker, uint256 amount) external onlyOwner {
        IERC20(_tracker).transfer(msg.sender, amount);
    }

    function retrieve721(address _tracker, uint256 id) external onlyOwner {
        IERC721(_tracker).transferFrom(address(this), msg.sender, id);
    }
}

// SPDX-License-Identifier: UNLICENCED
pragma solidity 0.8.25;

import "@openzeppelin/contracts/access/Ownable.sol";
import "../../@galaxis/registries/contracts/CommunityList.sol";
import "../../@galaxis/registries/contracts/CommunityRegistry.sol";
import "../../@galaxis/registries/contracts/NewProxy.sol";
import "../Registry/GTRegistry.sol";
import "../extras/recovery/BlackHolePrevention.sol";
import "../extras/recovery/BlackHolePrevention.sol";
import "../../@galaxis/registries/contracts/Versionable/IGenericVersionable.sol";

struct traitConfig {
    bool inverted;
}

interface GenericTraitInterface {
    function setup(
        address _registry,
        uint16 _traitId,
        traitConfig memory _traitConfig,
        bytes[] memory _defaultPropValues
    ) external;

    function init() external;
}

/**
 * @dev This factory is used to create new traits (perks) in a community
 */
abstract contract GenericTraitFactory is Ownable, BlackHolePrevention, IGenericVersionable, NewProxy {

    using Strings for uint32;

    bytes32     public constant     TRAIT_REGISTRY_ADMIN = keccak256("TRAIT_REGISTRY_ADMIN");
    bytes32     public constant     TRAIT_CONSUMER       = keccak256("TRAIT_CONSUMER");
    CommunityRegistry thisCommunityRegistry;

    struct factoryInfo {
        string  _REGISTRY_KEY;
        uint8   _TRAIT_TYPE;
        uint256 _baseVersion;
        uint256 _version;
    }

    function baseVersion() public pure returns (uint256) {
        return 2024040401;
    }

    constructor(address _galaxisRegistry) NewProxy(_galaxisRegistry) {

    }

    function version() public pure virtual returns (uint256) {
        return 2024040401;
    }

    function TRAIT_TYPE() public pure virtual returns (uint8) {
        return 0;
    }

    function REGISTRY_KEY_FACTORY() public pure virtual returns (string memory) {
        return "TRAIT_TYPE_GENERIC_FACTORY";
    }

    function GOLDEN_KEY() public pure virtual returns (string memory) {
        return "GOLDEN_TRAIT_TYPE_GENERIC";
    }

    function tellEverything() external pure returns (factoryInfo memory) {
        return factoryInfo(
            REGISTRY_KEY_FACTORY(),
            TRAIT_TYPE(),
            baseVersion(),
            version()
        );
    }

    struct inputTraitStruct {
        uint32  communityId;    // Community ID
        uint256 start;          // Validity start period of the trait
        uint256 end;            // Validity start period of the trait
        bool    enabled;        // Can be locked
        string  ipfsHash;       // The desriptor file hash on IPFS
        string  name;           // Name of the trait (perk)
        uint32  tokenNum;       // The serial number of the token contract to use (under key TOKEN_xx where xx = tokenNum )
        bytes[] defaults;
    }

    // Errors
    error TraitFactoryNotCurrent(address);
    error TraitFactoryInvalidCommunityId(uint32);
    error TraitFactoryUnauthorized();
    error TraitFactoryTraitRegistryNotInstalled();
    error TraitFactoryTokenNotInstalled();

    /**
     * @dev addTrait() is called from the UTC to create a new trait (perk) in a community for a specific token
     * note Tokens are marked in the Community registry with keys TOKEN_xx (where xx = 1,2,...)
     *      For each token the corresponding Trait Registry can be found under keys TRAIT_REGISTRY_xx
     *      In the input structure, tokenNum designates which community token - and thus which corresponding
     *      Trait registry should be used.
     *      This contract must have COMMUNITY_REGISTRY_ADMIN on RoleManagerInstance - so it can update keys in
     *      any Community registry
     *      It creates one storage contract per trait and one (singleton) logic controller for the trait type.
     *      It grants access to the controller in order to be able to write into the trait storage
     *      It validates that this is the current factory according to the keys in the Galaxis Registry
     */
    function addTrait(
        inputTraitStruct calldata _inputTrait,
        traitConfig calldata _traitConfig
    ) external returns (uint16 traitId) {
        // Validate if this contract is the current version to be used. Else fail
        if (galaxisRegistry.getRegistryAddress(REGISTRY_KEY_FACTORY()) != address(this)) {
            revert TraitFactoryNotCurrent(address(this));
        }

        // Get the community_list contract
        CommunityList COMMUNITY_LIST = CommunityList(
            galaxisRegistry.getRegistryAddress("COMMUNITY_LIST")
        );

        // Get the community data
        (, address crAddr, ) = COMMUNITY_LIST.communities(_inputTrait.communityId);
        
        if (crAddr == address(0)) {
            revert TraitFactoryInvalidCommunityId(_inputTrait.communityId);
        }

        // Get community registry
        thisCommunityRegistry = CommunityRegistry(crAddr);

        // Get trait registry
        GTRegistry traitRegistry = GTRegistry(
            thisCommunityRegistry.getRegistryAddress(
                string(
                    abi.encodePacked(
                        "TRAIT_REGISTRY_",
                        _inputTrait.tokenNum.toString()
                    )
                )
            )
        );

        // Trait registry must exist!
        if (address(traitRegistry) == address(0)) {
            revert TraitFactoryTraitRegistryNotInstalled();
        }

        // Check if caller is TRAIT_REGISTRY_ADMIN
        bool isUserCommunityAdmin = thisCommunityRegistry.isUserCommunityAdmin(TRAIT_REGISTRY_ADMIN, msg.sender);
        bool traitRegistryIsAllowed = traitRegistry.isAllowed(TRAIT_REGISTRY_ADMIN, msg.sender);
        if (!isUserCommunityAdmin && !traitRegistryIsAllowed) {
            revert TraitFactoryUnauthorized();
        }

        // Get next available ID for the new trait
        traitId = traitRegistry.traitCount();

        // Get the NFT address
        address ERC721 = thisCommunityRegistry.getRegistryAddress(
            string(abi.encodePacked("TOKEN_", _inputTrait.tokenNum.toString()))
        );

        // NFT must exist!
        if (ERC721 == address(0)) {
            revert TraitFactoryTokenNotInstalled();
        }

        // Add role for this factory to write into TraitRegistry
        if (!thisCommunityRegistry.hasRole(TRAIT_REGISTRY_ADMIN, address(this))) {
            thisCommunityRegistry.grantRole(
                TRAIT_REGISTRY_ADMIN,
                address(this)
            );
        }

        (address controllerCtrAddress, address storageCtrAddress) = deploy(
            address(traitRegistry),
            traitId,
            _traitConfig,
            _inputTrait.defaults
        );

        // Add the trait to the trait registry
        GTRegistry.traitStruct[] memory traits = new GTRegistry.traitStruct[](
            1
        );
        traits[0] = GTRegistry.traitStruct(
            traitId,
            TRAIT_TYPE(),
            _inputTrait.start,
            _inputTrait.end,
            _inputTrait.enabled,
            storageCtrAddress,
            _inputTrait.ipfsHash,
            _inputTrait.name
        );
        traitRegistry.addTrait(traits);

        if (controllerCtrAddress != address(0)) {
            // Grant access to the Controller for this trait
            traitRegistry.setTraitControllerAccess(
                controllerCtrAddress,
                traitId,
                true
            );
        }

    }

    function deploy(
        address traitRegistryAddress,
        uint16 traitId,
        traitConfig memory _traitConfig,
        bytes[] memory traitDefaults
    )
        internal
        virtual
        returns (address controllerCtrAddress, address storageCtrAddress);

}

// SPDX-License-Identifier: UNLICENCED
pragma solidity 0.8.25;

import "../Generic/GenericTrait.sol";

contract DigitalRedeem is GenericTrait {

    uint256 public vaultID;
    uint256 public redeemMode;

    function version() public pure override returns (uint256) {
        return 2023082701;
    }

    function TRAIT_TYPE() public pure override returns (uint16) {
        return 6;
    }

    function APP() public pure override returns (bytes32) {
        return "digitalredeem";
    }

    constructor(address _galaxisRegistry) GenericTrait(_galaxisRegistry) {
        
    }


    function init() virtual override public {
        _initStandardProps();

        addStoredProperty(bytes32("vault_id"),                  FieldTypes.STORED_UINT_256);
        addStoredProperty(bytes32("tokens_amount"),             FieldTypes.STORED_UINT_256);
        addStoredProperty(bytes32("pseudo_random_interval"),    FieldTypes.STORED_UINT_256);
        addStoredProperty(bytes32("coin_token_address"),        FieldTypes.STORED_ADDRESS);
        addStoredProperty(bytes32("luck"),                      FieldTypes.STORED_UINT_8);
        addStoredProperty(bytes32("redeem_mode"),               FieldTypes.STORED_UINT_8);

        afterInit();

        vaultID = uint256(bytes32(getProperty("vault_id", 0)));
        redeemMode = uint256(bytes32(getProperty("redeem_mode", 0)));
    }
    
}

File 33 of 38 : GenericTrait.sol
// SPDX-License-Identifier: UNLICENCED
pragma solidity 0.8.25;

import "../../../@galaxis/registries/contracts/CommunityRegistry.sol";
import "../../../@galaxis/registries/contracts/UsesGalaxisRegistry.sol";

import "../../../PaymentMatrix/IPaymentMatrix.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";

interface IGTRegistry {
    function addressCanModifyTrait(address, uint16) external view returns (bool);
    function getTraitControllerAccessData(address) external view returns (uint8[] memory);
    function myCommunityRegistry() external view returns (CommunityRegistry);
    function tokenNumber() external view returns (uint32);
    function TOKEN_KEY() external view returns (string memory);
}

enum FieldTypes {
    NONE,
    STORED_BOOL,
    STORED_UINT_8,
    STORED_UINT_16,
    STORED_UINT_32,
    STORED_UINT_64,
    STORED_UINT_128,
    STORED_UINT_256,       
    STORED_BYTES_32,       // bytes32 fixed
    STORED_STRING,         // bytes array
    STORED_BYTES,          // bytes array
    STORED_ADDRESS,
    LOGIC_BOOL,
    LOGIC_UINT_8,
    LOGIC_UINT_32,
    LOGIC_UINT_64,
    LOGIC_UINT_128,
    LOGIC_UINT_256,
    LOGIC_BYTES_32,
    LOGIC_ADDRESS
}

struct traitProperty {
    bytes32     _name;
    FieldTypes  _type;
    bytes4      _selector;
    bytes       _default;
    bool        _limited;
    uint256     _min;
    uint256     _max;
    bool        _reset_on_owner_change;
}

struct traitInfo {
    uint16 _id;
    uint16 _type;
    address _registry;
    uint256 _baseVersion;
    uint256 _version;
    traitProperty[] _schema;
    uint8   _propertyCount;
    bytes32 _app;
    traitConfig _traitConfig; 
}

struct traitConfig {
    bool inverted;
}

enum BitType {
    NONE,
    EXISTS,
    INITIALIZED
}

enum TraitStatus {
    NONE,
    // NOT_INITIALIZED,
    ACTIVE,
    DORMANT,
    SPENT
}

enum MovementPermission {
    NONE,
    OPEN,
    LOCKED,
    SOULBOUND,
    SOULBURN
}

enum ModifierMode {
    NONE,
    ADD,
    SET
}


contract GenericTrait is UsesGalaxisRegistry  {

    uint16      public     traitId;
    IGTRegistry public     GTRegistry;
    event tokenTraitChangeEvent(uint32 indexed _tokenId);

    function baseVersion() public pure returns (uint256) {
        return 2024052201;
    }

    function version() public pure virtual returns (uint256) {
        return baseVersion();
    }
    
    function TRAIT_TYPE() public pure virtual returns (uint16) {
        return 0;   // Physical redemption
    }

    function APP() public pure virtual returns (bytes32) {
        return "generic-trait";   // Physical redemption
    }

    constructor(address _galaxisRegistry) UsesGalaxisRegistry(_galaxisRegistry) {
        
    }


    function tellEverything() external view returns(traitInfo memory) {
        return traitInfo(
            traitId,
            TRAIT_TYPE(),
            address(GTRegistry),
            baseVersion(),
            version(),
            getSchema(),
            propertyCount,
            APP(),
            thisTraitConfig
        );
    }

    // constructor(
    //     address _registry,
    //     uint16 _traitId,
    //     bytes[] memory _defaultPropValues
    // ) {
    //     traitId = _traitId;
    //     GTRegistry = IGTRegistry(_registry);
    //     for(uint8 i = 0; i < _defaultPropValues.length; i++) {
    //         defaultPropValues[i] = _defaultPropValues[i];
    //     }
    // }

    // cannot store as bytes unless we only allow simple types, no string / array 

    /*
        Set Properties
        Name	            type	defaults	description
        Expiration  date	date	-	        Trait can't be used after expiration date passes
        Counter	            int	    -	        Trait can only be used this many times
        Cooldown	        int	    -	        current date + cooldonw = Activation Date
        Activation Date	    date	-	        If set, trait can't be used before this date
        Modifier Lock	    bool	FALSE	    if True, Value Modifier Traits can't modify limiters
        Burn If Spent	    bool	FALSE	    If trait's status ever becomes "spent", it gets burned.
        Movement Permission	status	OPEN	    See "movement permission"
        Royalty ID	        ID	    -	        ID of the entity who is entitled to the Usage Royalty
        Royalty Amount	    int	    0	        Royalty amount in GLX


        Discount Trait Properties
        Name	        type	defaults	    Description
        Discount Type	status	PERCENTAGE	    It can be either PERCENTAGE or a fix GLX AMOUNT
        Discount Amount	int	    -	            Either 0-100 or a GLX amount
        Acceptor Type	status	MARKETPLACE	    Acceptor Type, can't be blank. Check Discounts for list.
        Max	            int	    -	            max value possible (value modifier can't go beyond)
        Modifier Lock	bool	FALSE	        If true, Value Modifier Traits have no effect


        Digital Redeemable Trait Properties
        Name	        Type	defaults	description
        Vault	        ID	    -	        The target vault of the redeemable. Can not be empty.
        Luck	        0-100	0	        If greater than zero, the Luck Process is invoked.
        Redeem Mode	    ID	    RR	        See "Redeem Modes" in the Vault page.
        Modifier Lock	bool	FALSE	    If True, Value Modifiers can't apply to this trait.


        Physical Redeemable Trait Properties
        name	    type	description
        item name	ID	    name of the item that can be redeemed


        Value Modifier Trait Properties
        name	    type	defaults	description
        Trait Type	ID	    -	        What type of trait to modify (Digital Redeemable, etc)
        Property	ID	    -	        What property of that trait to modify
        Mode	    ID	    ADD	        ADD or SET
        Value	    int	    -	        By how much

    */

    bool public initialized = false;
    traitConfig thisTraitConfig;

    mapping(uint8 => traitProperty) property;
    uint8 propertyCount = 0;
    mapping(bytes32 => uint8) propertyNameToId;
    mapping(uint8 => uint8) propertyStorageMap;

    //      propId  => tokenId => ( index => value )
    mapping(uint8 => mapping( uint32 => bytes ) ) storageMapArray;
    //      tokenId => data ( except bytes / string which go into storageMapArray )
    mapping(uint32 => bytes ) storageData;

    //      propId  => tokenId => ( index => value )
    mapping(uint8 => bytes ) storageMapArrayDEFAULT;
    //      tokenId => data ( except bytes / string which go into storageMapArrayDEFAULT )

    bytes tokenDataDEFAULT;
    mapping(uint8 => bytes ) defaultPropValues;

    // we need an efficient way to activate traits at mint or by using dropper
    // to achieve this we set 1 bit per tokenId
    // 

    mapping(uint32 => uint8 )    public existsData;
    mapping(uint32 => uint8 )    initializedData;

    // indexed props
    bool    public modifier_lock;
    uint8   public movement_permission;

    bytes32 constant constant_royalty_id_key = hex"726f79616c74795f696400000000000000000000000000000000000000000000";
    bytes32 constant constant_royalty_amount_key = hex"726f79616c74795f616d6f756e74000000000000000000000000000000000000";
    bytes32 constant constant_owner_stored_key = hex"6f776e65725f73746f7265640000000000000000000000000000000000000000";

    // constructor() {
    //     init();
    // }

    function isLogicFieldType(FieldTypes _type) internal pure returns (bool) {
        if(_type == FieldTypes.LOGIC_BOOL) {
            return true;
        }
        if(_type == FieldTypes.LOGIC_UINT_8) {
            return true;
        }
        if(_type == FieldTypes.LOGIC_UINT_32) {
            return true;
        }
        if(_type == FieldTypes.LOGIC_UINT_64) {
            return true;
        }
        if(_type == FieldTypes.LOGIC_UINT_128) {
            return true;
        }
        if(_type == FieldTypes.LOGIC_UINT_256) {
            return true;
        }
        if(_type == FieldTypes.LOGIC_BYTES_32) {
            return true;
        }
        if(_type == FieldTypes.LOGIC_ADDRESS) {
            return true;
        }
        return false;
    }

    function _addProperty(bytes32 _name, FieldTypes _type, bytes4 _selector) internal {
        uint8 thisId = propertyCount;

        if(propertyNameToId[_name] > 0) {
            // no duplicates
            revert();
        } else {
            propertyNameToId[_name]     = thisId;
            traitProperty storage prop = property[thisId];
            prop._name = _name;
            prop._type = _type;
            prop._selector = _selector;
            prop._default = defaultPropValues[thisId]; // _default;
            propertyCount++;
        }
    }

    function addStoredProperty(bytes32 _name, FieldTypes _type) internal {
        _addProperty(_name, _type, bytes4(0));
    }

    function addLogicProperty(bytes32 _name, FieldTypes _type, bytes4 _selector) internal {
        _addProperty(_name, _type, _selector);
    }

    function addPropertyLimits(bytes32 _name, uint256 _min, uint256 _max) internal {
        uint8 _id = propertyNameToId[_name];
        traitProperty storage thisProp = property[_id];
        require(thisProp._selector == bytes4(hex"00000000"), "Trait: Cannot set limits on Logic property");
        thisProp._limited = true;
        thisProp._min = _min;
        thisProp._max = _max;
    }

    function setPropertyResetOnOwnerChange(bytes32 _name) internal {
        uint8 _id = propertyNameToId[_name];
        traitProperty storage thisProp = property[_id];
        thisProp._reset_on_owner_change = true;
    }

    function _initStandardProps() internal {
        require(!initialized, "Trait: already initialized!");

        addLogicProperty( bytes32("exists"),              FieldTypes.LOGIC_BOOL,        bytes4(keccak256("hasTrait(uint32)")));
        addLogicProperty( bytes32("initialized"),         FieldTypes.LOGIC_BOOL,        bytes4(keccak256("isInitialized(uint32)")));

        // required for soulbound
        addStoredProperty(bytes32("owner_stored"),        FieldTypes.STORED_ADDRESS);
        addLogicProperty( bytes32("owner_current"),       FieldTypes.LOGIC_ADDRESS,     bytes4(keccak256("currentTokenOwnerAddress(uint32)")));


        // if true, Value Modifier Traits can't modify limiters
        addStoredProperty(bytes32("modifier_lock"),       FieldTypes.STORED_BOOL);
        addStoredProperty(bytes32("movement_permission"), FieldTypes.STORED_UINT_8);
        addStoredProperty(bytes32("activation"),          FieldTypes.STORED_UINT_256);
        addStoredProperty(bytes32("cooldown"),            FieldTypes.STORED_UINT_256);
        addStoredProperty(bytes32("expiration"),          FieldTypes.STORED_UINT_256);
        addStoredProperty(bytes32("counter"),             FieldTypes.STORED_UINT_8);

        addStoredProperty(bytes32("royalty_id"),          FieldTypes.STORED_UINT_256);
        addStoredProperty(bytes32("royalty_amount"),      FieldTypes.STORED_UINT_256);

        addLogicProperty( bytes32("status"),              FieldTypes.LOGIC_UINT_8,      bytes4(keccak256("status(uint32)")));



        // setPropertySoulbound()
            // owner_stored
            // if(_name == hex"6f776e65725f73746f7265640000000000000000000000000000000000000000") {
            //     prop._soulbound = true;
            // }


        // status change on owner_current change
        // if movement_permission == MovementPermission.SOULBOUND
        // on addTrait / setProperty / setData set owner_stored
        // 
        

        // prop reset on owner_stored
        // _reset_on_owner_change
        // addStoredProperty(bytes32("points"),              FieldTypes.STORED_UINT_256);
        // setPropertyResetOnOwnerChange(bytes32("points"));
        // addStoredProperty(bytes32("points"),              FieldTypes.STORED_UINT_256);

        // addPropertyLimits(bytes32("cooldown"),      0,      3600 * 24);
        // addPropertyLimits(bytes32("counter"),       0,      100);
    }

    function setup(
        address _registry,
        uint16 _traitId,
        traitConfig memory _traitConfig,
        bytes[] memory _defaultPropValues
    ) virtual public {
        require(!initialized, "Trait: already initialized!");
        GTRegistry = IGTRegistry(_registry);
        traitId = _traitId;
        thisTraitConfig = _traitConfig;
        for(uint8 i = 0; i < _defaultPropValues.length; i++) {
            defaultPropValues[i] = _defaultPropValues[i];
        }        
    }

    

    function init() virtual public {
        _initStandardProps();
        // custom props
        afterInit();
    }

    function getRoyaltiesForThisTraitType() internal view returns (uint256, uint256) {
        IPaymentMatrix PaymentMatrix = IPaymentMatrix(
            galaxisRegistry.getRegistryAddress("PAYMENT_MATRIX")
        ); 
        
        require(address(PaymentMatrix) != address(0), "Trait: PAYMENT_MATRIX address cannot be 0");

        // if(initialized){} 
        return PaymentMatrix.getDevIDAndAmountForTraitType(TRAIT_TYPE());
    }

    function afterInit() internal {

        // overwrite royalty_id / royalty_amount
        (uint256 royalty_id, uint256 royalty_amount) = getRoyaltiesForThisTraitType();
        for(uint8 _id = 0; _id < propertyCount; _id++) {
            traitProperty memory thisProp = property[_id];
            if(thisProp._name == constant_royalty_id_key || thisProp._name == constant_royalty_amount_key) {
                bytes memory value;
                if(thisProp._name == constant_royalty_id_key) {
                    value = abi.encode(royalty_id);
                } else if(thisProp._name == constant_royalty_amount_key) {
                    value = abi.encode(royalty_amount);
                }
                defaultPropValues[_id] = value;
                property[_id]._default = value;
            } 

            // reset default owner in case deployer wrote a different address here
            if(thisProp._name == constant_owner_stored_key ) {
                property[_id]._default = abi.encode(address(0));
            }
        }

        // index for cheaper internal logic
        modifier_lock = (uint256(bytes32(getProperty("modifier_lock", 0))) > 0 );
        movement_permission = abi.decode(getProperty("movement_permission", 0), (uint8));
        // set defaults
        tokenDataDEFAULT = getDefaultTokenDataOutput();

        initialized = true;
    }


    function getSchema() public view returns (traitProperty[] memory) {
        traitProperty[] memory myProps = new traitProperty[](propertyCount);
        for(uint8 i = 0; i < propertyCount; i++) {
            myProps[i] = property[i];
        }
        return myProps;
    }

    // function _getFieldTypeByteLenght(uint8 _id) public view returns (uint16) {
    //     traitProperty storage thisProp = property[_id];
    //     if(thisProp._type == FieldTypes.LOGIC_BOOL || thisProp._type == FieldTypes.STORED_BOOL) {
    //         return 1;
    //     }
    //     else if(thisProp._type == FieldTypes.STORED_UINT_8) {
    //         return 1;
    //     }
    //     else if(thisProp._type == FieldTypes.STORED_UINT_16) {
    //         return 2;
    //     }
    //     else if(thisProp._type == FieldTypes.STORED_UINT_32) {
    //         return 4;
    //     }
    //     else if(thisProp._type == FieldTypes.STORED_UINT_64) {
    //         return 8;
    //     }
    //     else if(thisProp._type == FieldTypes.STORED_UINT_128) {
    //         return 16;
    //     }
    //     else if(thisProp._type == FieldTypes.STORED_UINT_256) {
    //         return 32;
    //     }
    //     else if(thisProp._type == FieldTypes.STORED_STRING || thisProp._type == FieldTypes.STORED_BYTES) {
    //         // array length for strings / bytes limited to uint16.
    //         return 2;
    //     }

    //     revert("Trait: FieldType Not Implemented");
    // }

    function getOutputBufferLength(uint32 _tokenId) public view returns(uint16, uint16) {
        // abi.encode style 32 byte blocks
        // with memory pointer at location for complex types
        // pointer to length followed by records
        uint16 propCount = propertyCount;
        uint16 _length = 32 * propCount;
        uint16 complexDataOutputPtr = _length;
        bytes memory tokenData = bytes(storageData[_tokenId]);
        
        for(uint8 _id = 0; _id < propertyCount; _id++) {
            FieldTypes thisPropType = property[_id]._type;
            if(thisPropType == FieldTypes.STORED_STRING || thisPropType == FieldTypes.STORED_BYTES) {
                uint16 offset = uint16(_id) * 32;
                // console.log("getOutputBufferLength", _id, offset);
                bytes memory arrayLenB = new bytes(2);
                if(tokenData.length > 0) {
                    arrayLenB[0] = bytes1(tokenData[offset + 30]);
                    arrayLenB[1] = bytes1(tokenData[offset + 31]);
                    // each complex type adds another 32 for length 
                    // and data 32 * ceil(length/32)
                    _length+= 32 + 32 + ( 32 * ( uint16(bytes2(arrayLenB)) / 32 ) );

                } else {
                    arrayLenB[0] = 0;
                    arrayLenB[1] = 0;
                    _length+= 32;
                }
            }
        }
        return (_length, complexDataOutputPtr);
    }

    function getData(uint32[] memory _tokenIds) public view returns(bytes[] memory) {
        bytes[] memory outputs = new bytes[](_tokenIds.length);
        for(uint32 i = 0; i < _tokenIds.length; i++) {
            outputs[i] = getData(_tokenIds[i]);
        }
        return outputs;
    }

    function getDefaultTokenDataOutput() public view returns(bytes memory) {
        uint32 _tokenId = 0;
        ( uint16 _length, uint16 complexDataOutputPtr) = getOutputBufferLength(_tokenId);
        bytes memory outputBuffer = new bytes(_length);
        uint256 outputPtr;
        uint256 complexDataOutputRealPtr;
        uint256 _start = 0;

        assembly {
            // jump over length 32 byte block
            outputPtr := add(outputBuffer, 32)
            complexDataOutputRealPtr := add(outputPtr, complexDataOutputPtr)
        }

        for(uint8 _id = 0; _id < propertyCount; _id++) {
            _start+=32;

            FieldTypes thisPropType = property[_id]._type;
            if(thisPropType == FieldTypes.STORED_STRING || thisPropType == FieldTypes.STORED_BYTES) {
                bytes memory value = storageMapArrayDEFAULT[_id];
                assembly {
                    // let readptr := add(tokenData, _start)
                    // store location of data in place
                    mstore(outputPtr, complexDataOutputPtr)

                    complexDataOutputPtr := add(complexDataOutputPtr, 32)
                    let byteLength := mload(value)
                    let itemBlocks := div(byteLength, 32)
                    if lt(mul(itemBlocks, 32), byteLength ) {
                        itemBlocks := add(itemBlocks, 1)
                    }
                    // store array length
                    mstore(complexDataOutputRealPtr, byteLength)
                    complexDataOutputRealPtr:= add(complexDataOutputRealPtr, 32)
                    for { let n := 0 } lt(n, itemBlocks) { n := add(n, 1) } {
                        // store array 32 byte blocks
                        mstore(
                            complexDataOutputRealPtr, 
                            mload(
                                add(value, mul(add(n,1), 32) ) 
                            )
                        )
                        complexDataOutputRealPtr:= add(complexDataOutputRealPtr, 32)
                    }
                    complexDataOutputPtr := add(complexDataOutputPtr, mul(itemBlocks, 32))
                }

            }
            else {
                bytes32 value = bytes32(property[_id]._default);
                assembly {
                    // store empty value in place
                    mstore(outputPtr, value)
                }
            }

            assembly {
                outputPtr := add(outputPtr, 32)
            }
        }
        return outputBuffer;

    }

    function getData(uint32 _tokenId) public view returns(bytes memory) {
        uint16 _length = 0;
        uint16 complexDataOutputPtr;
        ( _length, complexDataOutputPtr) = getOutputBufferLength(_tokenId);
        bytes memory outputBuffer = new bytes(_length);
        bytes memory tokenData = storageData[_tokenId];

        if(!isInitialized(_tokenId)) {
            tokenData = tokenDataDEFAULT;
        }

        // 32 byte block contains bytes array size / length
        if(tokenData.length == 0) {
            // could simply return empty outputBuffer here..;
            tokenData = new bytes(
                uint16(propertyCount) * 32
            );
        }

        uint256 outputPtr;
        uint256 complexDataOutputRealPtr;
        uint256 _start = 0;

        assembly {
            // jump over length 32 byte block
            outputPtr := add(outputBuffer, 32)
            complexDataOutputRealPtr := add(outputPtr, complexDataOutputPtr)
        }

        for(uint8 _id = 0; _id < propertyCount; _id++) {
            _start+=32;

            FieldTypes thisPropType = property[_id]._type;
            if(thisPropType == FieldTypes.STORED_STRING || thisPropType == FieldTypes.STORED_BYTES) {
                bytes memory value = storageMapArray[_id][_tokenId];
                assembly {
                    // let readptr := add(tokenData, _start)
                    // store location of data in place
                    mstore(outputPtr, complexDataOutputPtr)

                    complexDataOutputPtr := add(complexDataOutputPtr, 32)
                    let byteLength := mload(value)
                    let itemBlocks := div(byteLength, 32)
                    if lt(mul(itemBlocks, 32), byteLength ) {
                        itemBlocks := add(itemBlocks, 1)
                    }
                    // store array length
                    mstore(complexDataOutputRealPtr, byteLength)
                    complexDataOutputRealPtr:= add(complexDataOutputRealPtr, 32)
                    for { let n := 0 } lt(n, itemBlocks) { n := add(n, 1) } {
                        // store array 32 byte blocks
                        mstore(
                            complexDataOutputRealPtr, 
                            mload(
                                add(value, mul(add(n,1), 32) ) 
                            )
                        )
                        complexDataOutputRealPtr:= add(complexDataOutputRealPtr, 32)
                    }
                    complexDataOutputPtr := add(complexDataOutputPtr, mul(itemBlocks, 32))
                }

            }
            else if(isLogicFieldType(thisPropType)) {

                callMethodAndCopyToOutputPointer(
                    property[_id]._selector, 
                    _tokenId,
                    outputPtr
                );

            } else {
                assembly {
                    // store value in place
                    mstore(outputPtr, mload(
                        add(tokenData, _start)
                    ))
                }
            }

            assembly {
                outputPtr := add(outputPtr, 32)
            }
        }
        return outputBuffer;
    }

    function callMethodAndCopyToOutputPointer(bytes4 _selector, uint32 _tokenId, uint256 outputPtr ) internal view {
        (bool success, bytes memory callResult) = address(this).staticcall(
            abi.encodeWithSelector(_selector, _tokenId)
        );
        require(success, "Trait: internal method call failed");
        // console.logBytes(callResult);
        assembly {
            // store value in place  // shift by 32 so we just get the value
            mstore(outputPtr, mload(add(callResult, 32)))
        }
    }

    /*
        should remove, gives too much power
    */
    function setData(uint32 _tokenId, bytes memory _bytesData) public onlyAllowed {
        _setData(_tokenId, _bytesData);
        
        //
        _updateCurrentOwnerInStorage(_tokenId);
    }

    function _setData(uint32 _tokenId, bytes memory _bytesData) internal {
        
        if(!hasTrait(_tokenId)) {
            // if the trait does not exist
            setTraitExistance(_tokenId, true);
        }

        if(!isInitialized(_tokenId)) {
            // if the trait is not initialized
            _tokenSetBit(_tokenId, BitType.INITIALIZED, true);
        }

        uint16 _length = uint16(propertyCount) * 32;
        if(_bytesData.length < _length) {
            revert("Trait: Message not long enough");
        }

        bytes memory newTokenData = new bytes(_length);
        uint256 newTokenDataPtr;
        uint256 readPtr;
        assembly {
            // jump over length 32 byte block
            newTokenDataPtr := add(newTokenData, 32)
            readPtr := add(_bytesData, 32)
        }

        for(uint8 _id = 0; _id < propertyCount; _id++) {
            FieldTypes thisPropType = property[_id]._type;
            bytes32 fieldValue;
            assembly {
                fieldValue:= mload(readPtr)
            }

            if(thisPropType == FieldTypes.STORED_STRING || thisPropType == FieldTypes.STORED_BYTES) {
                // read length from offset stored in fieldValue
                bytes32 byteLength;
                uint256 complexDataPtr;
                assembly {
                    complexDataPtr:= add(
                        add(_bytesData, 32),
                        fieldValue
                    )

                    byteLength:= mload(complexDataPtr)
                    // store length
                    mstore(newTokenDataPtr, byteLength)
                }

                bytes memory propValue = new bytes(uint256(byteLength));

                assembly {
                
                    let propValuePtr := add(propValue, 32)
                    let itemBlocks := div(byteLength, 32)
                    if lt(mul(itemBlocks, 32), byteLength ) {
                        itemBlocks := add(itemBlocks, 1)
                    }

                    // store array 32 byte blocks
                    for { let n := 0 } lt(n, itemBlocks) { n := add(n, 1) } {
                        complexDataPtr:= add(complexDataPtr, 32)
                        mstore(
                            propValuePtr, 
                            mload(complexDataPtr)
                        )                        
                        propValuePtr:= add(propValuePtr, 32)
                    }

                }
                storageMapArray[_id][_tokenId] = propValue;
            
            } else if(isLogicFieldType(thisPropType)) {
                // do nothing
            } else {
                // just store fieldValue in newTokenData
                assembly {
                    mstore(newTokenDataPtr, fieldValue)
                }
            }

            assembly {
                newTokenDataPtr := add(newTokenDataPtr, 32)
                readPtr := add(readPtr, 32)
            }
        }
        storageData[_tokenId] = newTokenData;
        emit tokenTraitChangeEvent(_tokenId);
    }

    // function getPropertyOutputBufferLength(uint8 _id, FieldTypes _thisPropType, uint32 _tokenId) public view returns(uint16) {
    //     uint16 _length = 32;
    //     bytes memory tokenData = bytes(storageData[_tokenId]);
    //     if(_thisPropType == FieldTypes.STORED_STRING || _thisPropType == FieldTypes.STORED_BYTES) {
    //         uint16 offset = _id * 32;
    //         bytes memory arrayLenB = new bytes(2);
    //         if(tokenData.length > 0) {
    //             arrayLenB[0] = bytes1(tokenData[offset + 30]);
    //             arrayLenB[1] = bytes1(tokenData[offset +31]);
    //             // each complex type adds another 32 for length 
    //             // and data 32 * ceil(length/32)
    //             _length+= 32 + 32 + ( 32 * ( uint16(bytes2(arrayLenB)) / 32 ) );
    //         } else {
    //             arrayLenB[0] = 0;
    //             arrayLenB[1] = 0;
    //         }
    //     }
        
    //     return _length;
    // }

    function getProperties(uint32 _tokenId, bytes32[] memory _names) public  view returns(bytes[] memory) {
        bytes[] memory outputs = new bytes[](_names.length);
        for(uint32 i = 0; i < _names.length; i++) {
            outputs[i] = getProperty(_names[i], _tokenId);
        }
        return outputs;
    }

    function getProperty(bytes32 _name, uint32 _tokenId) public view returns (bytes memory) {
        uint8 _id = propertyNameToId[_name];
        FieldTypes thisPropType = property[_id]._type;
        if(!isInitialized(_tokenId) && !isLogicFieldType(thisPropType)) {
            // if the trait has not been initialized, and is not a method return, we return default stored data
            return property[_id]._default;
        } else {
            return _getProperty(_id, _tokenId);
        }
    }

    function _getProperty(uint8 _id, uint32 _tokenId) internal view returns (bytes memory) {
        FieldTypes thisPropType = property[_id]._type;
        bytes memory output = new bytes(32);
        uint256 outputPtr;
        assembly {
            outputPtr := add(output, 32)
        }
        if(thisPropType == FieldTypes.STORED_STRING || thisPropType == FieldTypes.STORED_BYTES) {
            output = storageMapArray[_id][_tokenId];
        }
        else if(isLogicFieldType(thisPropType)) {
            callMethodAndCopyToOutputPointer(
                property[_id]._selector, 
                _tokenId,
                outputPtr
            );
        }
        else {
            bytes memory tokenData = bytes(storageData[_tokenId]);
            // first 32 is tokenData length
            uint256 _start = 32 + 32 * uint16(_id);
            assembly {
                outputPtr := add(output, 32)
                // store value in place
                mstore(outputPtr, mload(
                        add(tokenData, _start)
                    )
                )
            }
        }
        return output; 
    }

    // function canUpdateTo(bytes32 _name, bytes memory newValue) public view returns (bool) {
    //     return true;

    //     uint8 _id = propertyNameToId[_name];
    //     traitProperty memory thisProp = property[_id];
        
    //     thisProp._limited;

    //     if(modifier_lock) {
    //         // if()
    //         return false;
    //     }
    //     return false;
    //     // 
    // }

    function setProperties(uint32 _tokenId, bytes32[] memory _names, bytes[] memory inputs) public onlyAllowed {
        _updateCurrentOwnerInStorage(_tokenId);

        for(uint8 i = 0; i < _names.length; i++) {
            bytes32 name = _names[i];
            if(name == constant_owner_stored_key) {
                revert("Trait: dissalowed! Cannot set owner_stored value!");
            }
            _setProperty(name, _tokenId, inputs[i]);
        }
    }


    function setProperty(bytes32 _name, uint32 _tokenId, bytes memory input) public onlyAllowed {
        if(_name == constant_owner_stored_key) {
            revert("Trait: dissalowed! Cannot set owner_stored value!");
        }
        _updateCurrentOwnerInStorage(_tokenId);
        _setProperty(_name, _tokenId, input);
    }

    function _updateCurrentOwnerInStorage(uint32 _tokenId) internal {
        if(movement_permission == uint8(MovementPermission.SOULBOUND)) {
            // if default address 0 value, then do the update
            if(
                // decoded stored value
                abi.decode(getProperty(constant_owner_stored_key, _tokenId), (address)) 
                == address(0)
            ) {
                _setProperty(
                    constant_owner_stored_key,
                    _tokenId, 
                    // abi encodePacked left shifts everything, but ethers.js cannot decode that properly!
                    abi.encode(currentTokenOwnerAddress(_tokenId))
                );
            }
            // else do nothing
        } else {
            _setProperty(
                constant_owner_stored_key,
                _tokenId, 
                // abi encodePacked left shifts everything, but ethers.js cannot decode that properly!
                abi.encode(currentTokenOwnerAddress(_tokenId))
            );
        }

    }

    function _setProperty(bytes32 _name, uint32 _tokenId, bytes memory input) internal {
        // if(!canUpdateTo(_name, input)) {
        //     revert("Trait: Cannot update values because modifier lock is true");
        // }

        if(!hasTrait(_tokenId)) {
            // if the trait does not exist
            setTraitExistance(_tokenId, true);
        }

        if(!isInitialized(_tokenId)) {
            // if the trait is not initialized
            _tokenSetBit(_tokenId, BitType.INITIALIZED, true);
            _setData(_tokenId, tokenDataDEFAULT);
        }

        uint8 _id = propertyNameToId[_name];
        FieldTypes thisPropType = property[_id]._type;

        if(isLogicFieldType(thisPropType)) {
            revert("Trait: Cannot set logic value!");
        } else {

            uint16 _length = uint16(propertyCount) * 32;
            bytes memory tokenData = bytes(storageData[_tokenId]);
            if(tokenData.length == 0) {
                tokenData = new bytes(_length);
                // init default tokenData.. empty for now
            }

            uint256 valuePtr;
            if(thisPropType == FieldTypes.STORED_STRING || thisPropType == FieldTypes.STORED_BYTES) {
                assembly {
                    valuePtr := input
                }
                storageMapArray[_id][_tokenId] = input;

            } else {
                assembly {
                    // load from pointer location
                    valuePtr := add(input, 32)
                }
            }

            assembly {
                // store incomming length value into value slot
                mstore(
                    add(
                        add(tokenData, 32),
                        mul(_id, 32) 
                    ),
                    mload(valuePtr)
                )
            }
            storageData[_tokenId] = tokenData;
        }
        
        emit tokenTraitChangeEvent(_tokenId);
    }

    function getByteAndBit(uint32 _offset) public pure returns (uint32 _byte, uint8 _bit) {
        // find byte storig our bit
        _byte = uint32(_offset / 8);
        _bit = uint8(_offset - _byte * 8);
    }

    function hasTrait(uint32 _tokenId) public view returns (bool result) {
        bool _hasTrait = _tokenHasBit(_tokenId, BitType.EXISTS);
        if(thisTraitConfig.inverted) {
            return !_hasTrait;
        }
        return _hasTrait;
    }

    function isInitialized(uint32 _tokenId) public view returns (bool result) {
        return _tokenHasBit(_tokenId, BitType.INITIALIZED);
    }

    function _tokenHasBit(uint32 _tokenId, BitType _bitType) internal view returns (bool result) {
        uint8 bitType = uint8(_bitType);
        (uint32 byteNum, uint8 bitPos) = getByteAndBit(_tokenId);
        if(bitType == 1) {
            return existsData[byteNum] & (0x01 * 2**bitPos) != 0;
        } else if(bitType == 2) {
            return initializedData[byteNum] & (0x01 * 2**bitPos) != 0;
        }
    }

    function status(uint32 _tokenId) public view returns ( uint8 ) {
        TraitStatus statusValue = TraitStatus.NONE;
        if(hasTrait(_tokenId)) {
            uint256 activation  = uint256(bytes32(getProperty("activation", _tokenId)));
            uint256 expiration  = uint256(bytes32(getProperty("expiration", _tokenId)));
            uint256 counter     = uint256(bytes32(getProperty("counter",    _tokenId)));

            if(expiration == 0) {
                // expiration 0 means never
                expiration = block.timestamp + 3600;
            }

            if(counter > 0) {
                if(activation <= block.timestamp && block.timestamp <= expiration) {

                    // SOULBOUND Check
                    if(movement_permission == uint8(MovementPermission.SOULBOUND)) {

                        address storedOwnerValue = abi.decode(getProperty(constant_owner_stored_key, _tokenId), (address));
                        address currentOwnerValue = currentTokenOwnerAddress(_tokenId);
                        
                        if(storedOwnerValue == currentOwnerValue) {
                            statusValue = TraitStatus.ACTIVE;
                        } else {
                            statusValue = TraitStatus.DORMANT;
                        }

                    } else {
                        statusValue = TraitStatus.ACTIVE;
                    }

                } else {
                    statusValue = TraitStatus.DORMANT;
                }
            } else {
                statusValue = TraitStatus.SPENT;
            }
        }
        return uint8(statusValue);
    }

    // marks token as having the trait
    function addTrait(uint32[] memory _tokenIds) public onlyAllowed {
        for(uint16 _id = 0; _id < _tokenIds.length; _id++) {
            if(!hasTrait(_tokenIds[_id])) {
                // if trait is soulbound we have to initialize it.. 
                if(movement_permission == uint8(MovementPermission.SOULBOUND)) {
                    _updateCurrentOwnerInStorage(_tokenIds[_id]);     
                } else {
                    setTraitExistance(_tokenIds[_id], true);
                    emit tokenTraitChangeEvent(_tokenIds[_id]);
                }
            } else {
                revert("Trait: Token already has trait!");
            }
        }
    }

    function setTraitExistance(uint32 _tokenId, bool _value) internal {
        if(thisTraitConfig.inverted) {
            _value = !_value;
        }
        _tokenSetBit(_tokenId, BitType.EXISTS, _value);
    }

    // util, sets bit in item in map at position as true / false
    function _tokenSetBit(uint32 _tokenId, BitType _bitType, bool _value) internal {
        (uint32 byteNum, uint8 bitPos) = getByteAndBit(_tokenId);
        if(_bitType == BitType.EXISTS) {
            if(_value) {
                existsData[byteNum] = uint8(existsData[byteNum] | 2**bitPos);
            } else {
                existsData[byteNum] = uint8(existsData[byteNum] & ~(2**bitPos));
            }
        } else if(_bitType == BitType.INITIALIZED) {
            if(_value) {
                initializedData[byteNum] = uint8(initializedData[byteNum] | 2**bitPos);
            } else {
                initializedData[byteNum] = uint8(initializedData[byteNum] & ~(2**bitPos));
            }
        }
    }

    function _removeTrait(uint32 _tokenId) internal returns (bool) {
        require(hasTrait(_tokenId), "Trait: Token does not have trait!");

        delete storageData[_tokenId];
        for(uint8 _id = 0; _id < propertyCount; _id++) {
            FieldTypes thisPropType = property[_id]._type;
            if(thisPropType == FieldTypes.STORED_STRING || thisPropType == FieldTypes.STORED_BYTES) {
                delete storageMapArray[_id][_tokenId];
            }
        }

        setTraitExistance(_tokenId, false);
        _tokenSetBit(_tokenId, BitType.INITIALIZED, false);

        emit tokenTraitChangeEvent(_tokenId);
        return true;
    }

    function removeTrait(uint32[] memory _tokenIds) public onlyAllowed returns (bool) {
        for(uint8 i = 0; i < _tokenIds.length; i++) {
            _removeTrait(_tokenIds[i]);
        }
        return true;
    }

    function incrementCounter(uint32 _tokenId) public onlyAllowed {
        uint256 counter     = uint256(bytes32(getProperty("counter", _tokenId))) + 1;
        require(counter < 256, "GenericTrait: counter exceeds max (255)");
        setProperty("counter", _tokenId, abi.encodePacked(counter));
    }

    function decrementCounter(uint32 _tokenId) public onlyAllowed {
        uint256 counter     = uint256(bytes32(getProperty("counter", _tokenId)));
        require(counter > 0, "GenericTrait: attempt to decrement zero counter");
        uint256 cooldown    = uint256(bytes32(getProperty("cooldown", _tokenId)));
        setProperty("counter", _tokenId, abi.encodePacked(counter - 1));
        setProperty("activation", _tokenId, abi.encodePacked(block.timestamp + cooldown));
    }


    function currentTokenOwnerAddress(uint32 _tokenId) public view returns (address) {
        return IERC721(
            (GTRegistry.myCommunityRegistry()).getRegistryAddress(
                GTRegistry.TOKEN_KEY()
            )
        ).ownerOf(_tokenId);
    }

    modifier onlyAllowed() {
        require(
            GTRegistry.addressCanModifyTrait(msg.sender, traitId) ||
            galaxisRegistry.getRegistryAddress("ACTION_HUB") == msg.sender, "Trait: Not authorized.");
        _;
    }

}

// SPDX-License-Identifier: UNLICENCED
pragma solidity 0.8.25;

interface IECRegistry {
    function addTrait(traitStruct[] memory) external; 
    function getImplementer(uint16 traitID) external view returns (address);
    function addressCanModifyTrait(address, uint16) external view returns (bool);
    function addressCanModifyTraits(address, uint16[] memory) external view returns (bool);
    function hasTrait(uint16 traitID, uint16 tokenID) external view returns (bool);
    function setTrait(uint16 traitID, uint16 tokenID, bool) external returns (bool);
    function setTraitUnchecked(uint16 traitID, uint16 tokenId, bool _value) external;
    function setTraitOnMultiple(uint16 traitID, uint16[] memory tokenIds, bool _value) external returns(uint16 changes);
    function setTraitOnMultipleUnchecked(uint16 traitID, uint16[] memory tokenIds, bool[] memory _value) external;
    function getTrait(uint16 id) external view returns (traitStruct memory);
    function getTraits() external view returns (traitStruct[] memory);
    function owner() external view returns (address);
    function contractController(address) external view returns (bool);
    function getDefaultTraitControllerByType(uint8) external view returns (address);
    function setDefaultTraitControllerType(address, uint8) external;
    function setTraitControllerAccess(address, uint16, bool) external;
    function traitCount() external view returns (uint16);

    struct traitStruct {
        uint16  id;
        uint8   traitType;              // 0 normal (1bit), 1 range, 2 inverted range, >=3 with storageImplementer
        uint16  start;
        uint16  end;
        bool    enabled;
        address storageImplementer;     // address of the smart contract that will implement the storage for the trait
        string  ipfsHash;
        string  name;
    }
}

// SPDX-License-Identifier: UNLICENCED
pragma solidity 0.8.25;

import "../../@galaxis/registries/contracts/CommunityList.sol";
import "../../@galaxis/registries/contracts/UsesGalaxisRegistry.sol";
import "../../@galaxis/registries/contracts/CommunityRegistry.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/utils/Strings.sol";

contract GTRegistry is UsesGalaxisRegistry {

    function version() public pure virtual returns (uint256) {
        return 2024040401;
    }

    bytes32                 public constant TRAIT_REGISTRY_ADMIN    = keccak256("TRAIT_REGISTRY_ADMIN");
    bytes32                 public constant TRAIT_DROP_ADMIN        = keccak256("TRAIT_DROP_ADMIN");
    bytes32                 public constant GLOBAL_TRAIT_DATA_ADMIN = keccak256("GLOBAL_TRAIT_DATA_ADMIN");

    CommunityRegistry       public          myCommunityRegistry;
    uint32                  public          tokenNumber;
    string                  public          TOKEN_KEY;
    bool                                    initialised;

    struct traitStruct {
        uint16  id;
        uint8   traitType;              
        
        // 0 normal (1bit), 1 range, 2 inverted range, >=3 with storageImplementer
        
        // internal 
        // - 0 for normal
        // - 1 for inverted
        // - 2 for inverted range
        // external 
        // - 3 Physical redeemables
        // - 4 Appointment
        // - 5 Autograph
        // 
        // - 100 uint8 values,
        // - 101 uint256 values
        // - 102 bytes32,
        // - 103 string
        // - 104 visual traits implementer

        uint256 start;                  // Range start for type 1/2 traits               
        uint256 end;                    // Range end for type 1/2 traits               
        bool    enabled;                // Frontend is responsible to hide disabled traits
        address storageImplementer;     // address of the smart contract that will implement the storage for the trait
        string  ipfsHash;               // IPFS address to store trait data (icon, etc.)
        string  name;
    }

    uint16 public traitCount;
    mapping(uint16 => traitStruct) public traits;


    // trait controller access designates sub contracts that can affect 1 or more traits
    mapping(uint16 => address ) public traitControllerById;
    mapping(address => uint16 ) public traitControllerByAddress;
    uint16 public traitControllerCount = 0;
    mapping(address => mapping(uint8 => uint8) ) public traitControllerAccess;
    mapping( uint8 => address ) public defaultTraitControllerAddressByType;

    /*
    *   Events
    */
    event traitControllerEvent(address _address);

    // Traits master data change
    event newTraitMasterEvent(uint16 indexed _id, string _name, address _address, uint8 _traitType, uint256 _start, uint256 _end);
    event updateTraitMasterEvent(uint16 indexed _id, string _name, address _address, uint8 _traitType, uint256 _start, uint256 _end);

    constructor (address _galaxisRegistry) UsesGalaxisRegistry(_galaxisRegistry) {
        initialised = true;                 // GOLDEN protection
    }

    function init(uint32  _communityId, uint32  _tokenNum) external {
        _init(_communityId, _tokenNum);
    }

    function _init(uint32  _communityId, uint32  _tokenNum) internal virtual {
        require(!initialised,"TraitRegistry: Already initialised");
        initialised = true;

        // Get the community_list contract
        CommunityList COMMUNITY_LIST = CommunityList(galaxisRegistry.getRegistryAddress("COMMUNITY_LIST"));
        // Get the community data
        (,address crAddr,) = COMMUNITY_LIST.communities(_communityId);
        myCommunityRegistry = CommunityRegistry(crAddr);
        tokenNumber = _tokenNum;
        TOKEN_KEY = string(abi.encodePacked("TOKEN_", Strings.toString(tokenNumber)));


        // Only the GOLDEN version can exist without valid community ID
        address GoldenECRegistryAddr = galaxisRegistry.getRegistryAddress("GOLDEN_TRAIT_REGISTRY");
        if( GoldenECRegistryAddr != address(this) ) {
            require(crAddr != address(0), "TraitRegistry: Invalid community ID");
        }
    }

    function getTrait(uint16 id) public view returns (traitStruct memory) {
        return traits[id];
    }

    function getTraits() public view returns (traitStruct[] memory) {
        traitStruct[] memory retval = new traitStruct[](traitCount);
        for(uint16 i = 0; i < traitCount; i++) {
            retval[i] = traits[i];
        }
        return retval;
    }

    function addTrait(
        traitStruct[] calldata _newTraits
    ) public onlyAllowed(TRAIT_REGISTRY_ADMIN) {

        for (uint8 i = 0; i < _newTraits.length; i++) {

            uint16 newTraitId = traitCount++;
            traitStruct storage newT = traits[newTraitId];
            newT.id =           newTraitId;
            newT.name =         _newTraits[i].name;
            newT.traitType =    _newTraits[i].traitType;
            newT.start =        _newTraits[i].start;
            newT.end =          _newTraits[i].end;
            newT.enabled =      _newTraits[i].enabled;
            newT.ipfsHash =     _newTraits[i].ipfsHash;
            newT.storageImplementer = _newTraits[i].storageImplementer;

            emit newTraitMasterEvent(newTraitId, newT.name, newT.storageImplementer, newT.traitType, newT.start, newT.end );
        }
    }

    function updateTrait(
        uint16 _index,
        string memory _name,
        address _storageImplementer,
        uint8   _traitType,
        uint256 _start,
        uint256 _end,
        bool    _enabled,
        string memory _ipfsHash
    ) public onlyAllowed(TRAIT_REGISTRY_ADMIN) {
        require(_storageImplementer != address(0),"TraitRegistry: Invalid StorageImplementer");
        traits[_index].name = _name;
        traits[_index].storageImplementer = _storageImplementer;
        traits[_index].ipfsHash = _ipfsHash;
        traits[_index].enabled = _enabled;
        traits[_index].traitType = _traitType;
        traits[_index].start = _start;
        traits[_index].end = _end;

        emit updateTraitMasterEvent(traits[_index].id, _name, _storageImplementer, _traitType, _start, _end);
    }

    function getTraitControllerAccessData(address _addr) public view returns (uint8[] memory) {
        uint16 _returnCount = getByteCountToStoreTraitData();
        uint8[] memory retValues = new uint8[](_returnCount);
        for(uint8 i = 0; i < _returnCount; i++) {
            retValues[i] = traitControllerAccess[_addr][i];
        }
        return retValues;
    }

    function getByteCountToStoreTraitData() internal view returns (uint16) {
        uint16 _returnCount = traitCount/8;
        if(_returnCount * 8 < traitCount) {
            _returnCount++;
        }
        return _returnCount;
    }

    function getByteAndBit(uint16 _offset) public pure returns (uint16 _byte, uint8 _bit)
    {
        // find byte storig our bit
        _byte = uint16(_offset / 8);
        _bit = uint8(_offset - _byte * 8);
    }

    function getImplementer(uint16 traitID) public view returns (address implementer)
    {
        return traits[traitID].storageImplementer;
    }


    /*
    *   Admin Stuff
    */

    function setDefaultTraitControllerType(address _addr, uint8 _traitType) external onlyAllowed(TRAIT_REGISTRY_ADMIN) {
        defaultTraitControllerAddressByType[_traitType] = _addr;
        emit traitControllerEvent(_addr);
    }

    function getDefaultTraitControllerByType(uint8 _traitType) external view returns (address) {
        return defaultTraitControllerAddressByType[_traitType];
    }

    /*
    *   Trait Controllers
    */

    function indexTraitController(address _addr) internal {
        if(traitControllerByAddress[_addr] == 0) {
            uint16 controllerId = ++traitControllerCount;
            traitControllerByAddress[_addr] = controllerId;
            traitControllerById[controllerId] = _addr;
        }
    }

    function setTraitControllerAccessData(address _addr, uint8[] calldata _data) public onlyAllowed(TRAIT_REGISTRY_ADMIN) {
        indexTraitController(_addr);
        for (uint8 i = 0; i < _data.length; i++) {
            traitControllerAccess[_addr][i] = _data[i];
        }
        emit traitControllerEvent(_addr);
    }

    function setTraitControllerAccess(address _addr, uint16 traitID, bool _value) public onlyAllowed(TRAIT_REGISTRY_ADMIN) {
        indexTraitController(_addr);
        if(_addr != address(0)) {
            (uint16 byteNum, uint8 bitPos) = getByteAndBit(traitID);
            if(_value) {
                traitControllerAccess[_addr][uint8(byteNum)] = uint8(traitControllerAccess[_addr][uint8(byteNum)] | 2**bitPos);
            } else {
                traitControllerAccess[_addr][uint8(byteNum)] = uint8(traitControllerAccess[_addr][uint8(byteNum)] & ~(2**bitPos));
            }
        }
        emit traitControllerEvent(_addr);
    }
 
    function addressCanModifyTrait(address _addr, uint16 traitID) public view returns (bool result) {
        (uint16 byteNum, uint8 bitPos) = getByteAndBit(traitID);
        return 
            traitControllerAccess[_addr][uint8(byteNum)] & (0x01 * 2**bitPos) != 0 ||
            hasRole(TRAIT_DROP_ADMIN, _addr) || 
            myCommunityRegistry.isUserCommunityAdmin(GLOBAL_TRAIT_DATA_ADMIN,_addr);
    }

    function addressCanModifyTraits(address _addr, uint16[] memory traitIDs) public view returns (bool result) {
        for(uint16 i = 0; i < traitIDs.length; i++) {
            if(!addressCanModifyTrait(_addr, traitIDs[i])) {
                return false;
            }
        }
        return true;
    }

    modifier onlyAllowed(bytes32 role) { 
        require(isAllowed(role, msg.sender), "TraitRegistry: Unauthorised");
        _;
    }

    function isAllowed(bytes32 role, address user) public view returns (bool) {
        return( hasRole(role, user));
    }

    function hasRole(bytes32 key, address user) public view returns (bool) {
        return myCommunityRegistry.hasRole(key, user);
    }

    modifier onlyTraitController(uint16 traitID) {
        require(
            addressCanModifyTrait(msg.sender, traitID),
            "TraitRegistry: Not Authorised"
        );
        _;
    }

}

// SPDX-License-Identifier: UNLICENCED
pragma solidity 0.8.25;

import "../../@galaxis/registries/contracts/Versionable/IVersionable.sol";
import "./IGenericVault.sol";
import "./INFTVault.sol";

/**
 * @title ICommunityVaultsRegistry
 * @dev Interface that represents a registry for community vaults
 */
interface ICommunityVaultsRegistry is IVersionable {
    /**
     * @dev Enum representing the different types of vaults
     */
    enum VaultTypes {
        NFTVault,
        CoinsVault
    }

    /**
     * @dev Base structure for holding basic information about vaults
     */
    struct BaseVaultInfo {
        address vaultAddr;
        VaultTypes vaultType;
        uint256 vaultTypeNonce;
        string vaultName;
    }

    /**
     * @dev Structure for holding detailed information about vault including buy NFT settings
     */
    struct VaultInfo {
        BaseVaultInfo baseVaultInfo;
        IGenericVault.BuySettingsInfo buySettingsInfo;
    }

    /**
     * @dev Emitted when a new vault is created
     * @param vaultId The ID of the created vault
     * @param vaultAddr The address of the created vault
     * @param vaultType The type of the created vault
     * @param vaultTypeNonce The nonce of the vault
     */
    event VaultCreated(
        uint256 vaultId,
        address vaultAddr,
        VaultTypes vaultType,
        uint256 vaultTypeNonce
    );

    /**
     * @dev Emitted when a new vault is created
     * @param vaultId The ID of the created vault
     */
    event VaultNameUpdated(
        uint256 vaultId
    );

    /*
     * @dev Indicates that the provided vault name is empty
     */
    error CommunityVaultsRegistryInvalidVaultName();

    /*
     * @dev Indicates that the caller does not have the required permissions for the operation
     */
    error CommunityVaultsRegistryUnauthorized();

    /*
     * @dev Indicates that there are zero golden vaults
     */
    error CommunityVaultsRegistryZeroVaultsGolden();

    /*
     * @dev Indicates a failure during the creation of a vault
     */
    error CommunityVaultsRegistryVaultCreationFailed();

    /*
     * @dev Indicates a failure while getting random provider
     */
    error CommunityVaultsRegistryRandomProviderNotRegistred();

    /*
     * @dev Indicates that the provided community ID doesn't exists
     */
    error CommunityVaultsRegistryInvalidCommunityId(uint32 communityId);

    /*
     * @dev Indicates that the provided vault ID doesn't exists
     */
    error CommunityVaultsRegistryInvalidVaultId(uint256 vaultId);

    /*
     * @dev Indicates that the update message was not received from the vault
     */
    error CommunityVaultsRegistryInvalidMsgSender();


    /**
     * @dev Creates a new NFT vault
     * @param vaultName_ Name of the vault
     * @return Address of the newly created NFT vault
     */
    function createNFTVault(
        string calldata vaultName_,
        IGenericVault.GenericVaultInitParams calldata initParams_
    ) external returns (address);

    /**
     * @dev Creates a new coins vault
     * @param vaultName_ Name of the vault
     * @return Address of the newly created coins vault
     */
    function createCoinsVault(
        string calldata vaultName_,
        IGenericVault.GenericVaultInitParams calldata initParams_
    ) external returns (address);

    /**
     * @dev Retrieves the address of a vault by its type and nonce
     * @param vaultType_ Type of the vault
     * @param vaultTypeNonce_ Nonce of the vault
     * @return Address of the vault
     */
    function getVaultAddress(
        VaultTypes vaultType_,
        uint256 vaultTypeNonce_
    ) external view returns (address);

    /**
     * @dev Retrieves the address of a vault by its implementation, type, and nonce
     * @param implementation_ Address of the implementation
     * @param vaultType_ Type of the vault
     * @param vaultTypeNonce_ Nonce of the vault
     * @return Address of the vault
     */
    function getVaultAddress(
        address implementation_,
        VaultTypes vaultType_,
        uint256 vaultTypeNonce_
    ) external view returns (address);

    /**
     * @dev Retrieves the address of a vault by its ID
     * @param vaultId_ ID of the vault
     * @return Address of the vault
     */
    function getVaultAddressById(
        uint256 vaultId_
    ) external view returns (address);

    /**
     * @dev Retrieves detailed information about multiple vaults by their IDs.
     * @param vaultIds_ List of vault IDs
     * @return resultArr_ Array of vault information
     */
    function getVaultsInfo(
        uint256[] calldata vaultIds_
    ) external view returns (VaultInfo[] memory resultArr_);

    /**
     * @dev Checks if an address has admin permissions for the vaults registry
     * @param userAddr_ Address to check
     * @return True if the address has admin permissions, false otherwise
     */
    function hasVaultsRegistryAdminRole(
        address userAddr_
    ) external view returns (bool);

    /**
     * @dev Updates the name of an existing vault
     * @param vaultId_ Id of the vault
     * @param newVaultName_ New name of the vault
     */
    function updateVaultName(
        uint256 vaultId_,
        string calldata newVaultName_
    ) external;
}

// SPDX-License-Identifier: UNLICENCED
pragma solidity 0.8.25;

import {CommunityRegistry} from "../../@galaxis/registries/contracts/CommunityRegistry.sol";
import {DigitalRedeem} from "../../Traits/Implementers/DigitalRedeem/DigitalRedeem.sol";
import {ICommunityVaultsRegistry} from "./ICommunityVaultsRegistry.sol";
import {IGenericVersionable} from "../../@galaxis/registries/contracts/Versionable/IGenericVersionable.sol";

/**
 * @title IGenericVault
 * @dev Interface for generic vault operations
 */
interface IGenericVault is IGenericVersionable {
    /**
     * @dev Enum representing the different types of tokens supported by the vault
     */
    enum TokenTypes {
        ERC20,
        ERC721,
        ERC1155
    }

    /**
     * @dev Enum representing the different redeem modes supported by the vault
     */
    enum RedeemModes {
        RANDOM_REDEEM,
        SEQUENTIAL_REDEEM,
        DIRECT_SELECT,
        DET_PSEUDO_RANDOM,
        COINS_REDEEM
    }

    enum BuyTypes {
        NATIVE,
        VAULT_ERC20_PAYMENT_TOKEN,
        ERC1155
    }

    struct BuyTypeData {
        address tokenAddr;
        uint256 tokenId;
        uint256 tokensAmount;
        bool isBuyable;
    }

    struct BuySettings {
        BaseBuySettings baseBuySettings;
        mapping(BuyTypes => BuyTypeData) buyTypesData;
    }

    struct BaseBuySettings {
        RedeemModes redeemMode;
        bytes specialRedeemData;
    }

    struct BuyTypeInfo {
        BuyTypes buyType;
        BuyTypeData buyTypeData;
    }

    struct BuySettingsInfo {
        BaseBuySettings baseBuySettings;
        BuyTypeInfo[] buyTypeInfoArr;
    }

    /**
     * @dev Structure for whitelisting receivable tokens
     */
    struct ReceivablesWhitelistEntry {
        address tokenAddr;
        TokenTypes tokenType;
        bool isAdding;
    }

    /**
     * @dev Structure for updating supported redeem modes
     */
    struct RedeemModesUpdateEntry {
        RedeemModes redeemMode;
        bool isAdding;
    }

    /**
     * @dev Structure holding info about whitelisted tokens
     */
    struct WhitelistedTokenInfo {
        address tokenAddr;
        TokenTypes tokenType;
    }

    struct GenericVaultInitParams {
        ReceivablesWhitelistEntry[] whitelistEntries;
        RedeemModesUpdateEntry[] redeemModesUpdateEntries;
        BuySettingsInfo buySettingsInfo;
        bool initialState;
    }

    /**
     * @dev Parameters required for withdrawal of tokens
     */
    struct WithdrawParams {
        address tokenAddr;
        address tokenRecipient;
        uint256 tokenId;
        uint256 tokensAmount;
        TokenTypes tokenType;
    }

    /**
     * @dev Parameters required for withdrawal of traits
     */
    struct TraitWithdrawParams {
        DigitalRedeem trait;
        uint32 tokenId;
        bytes redeemData;
    }

    error GenericVaultInvalidNativeCurrencyAmount();

    error GenericVaultFailedToTransferNativeCurrency(
        address recipient,
        uint256 transferAmount
    );

    error GenericVaultUnsupportedBuyType(BuyTypes buyType);

    error GenericVaultUnableToBuyNFTs(BuyTypes buyType);

    error GenericVaultNotEnoughTokensToBuy(
        BuyTypes buyType,
        uint256 userBalance,
        uint256 nftPrice
    );

    /**
     * @dev Thrown when the special redeem data is not valid for the redeem mode
     */
    error GenericVaultInvalidSpecialRedeemData(RedeemModes, bytes);

    /**
     * @dev Raised when provided token is not valid for receivables whitelist
     */
    error GenericVaultInvalidReceivablesWhitelistToken(address tokenAddr);

    /**
     * @dev Raised when a provided redeem mode is unsupported
     */
    error GenericVaultUnsupportedRedeemMode(RedeemModes redeemMode);

    /**
     * @dev Raised when a trait is inactive
     */
    error GenericVaultInactiveTrait(address trait, uint32 tokenId);

    /**
     * @dev Raised when an invalid type is used for withdrawal
     */
    error GenericVaultInvalidWithdrawType();

    /**
     * @dev Raised when a token is not present in the receivables whitelist
     */
    error GenericVaultNotInAReceivablesWhitelist(address tokenAddr);

    /**
     * @dev Raised when provided token type is invalid for the vault type
     */
    error GenericVaultInvalidTokenType(
        ICommunityVaultsRegistry.VaultTypes vaultType,
        TokenTypes tokenType
    );

    /**
     * @dev Raised when an unsupported interface is used
     */
    error GenericVaultUnsupportedInterface(
        bytes4 interfaceId,
        address tokenAddr
    );

    /**
     * @dev Raised when a user is unauthorized for a particular role
     */
    error GenericVaultUnauthorized(bytes32 role, address userAddr);

    /**
     * @dev Raised when a vault is disabled
     */
    error GenericVaultDisabled();

    /**
     * @notice Updates the whitelist for receivable tokens
     * @param entriesToUpdate_ List of tokens to be updated
     */
    function updateReceivablesWhitelist(
        ReceivablesWhitelistEntry[] calldata entriesToUpdate_
    ) external;

    /**
     * @notice Updates the supported redeem modes for the vault
     * @param entriesToUpdate_ List of redeem modes to be updated
     */
    function updateSupportedRedeemModes(
        RedeemModesUpdateEntry[] calldata entriesToUpdate_
    ) external;

    function updateBuySettings(
        BuySettingsInfo calldata newBuySettingsInfo_
    ) external;

    function updateBaseBuySettings(
        BaseBuySettings calldata newBaseBuySettings_
    ) external;

    function updateBuyTypesData(
        BuyTypeInfo[] calldata buyTypeInfoArr_
    ) external;

    /**
     * @notice Allows the withdrawal of tokens from the vault
     * @param withdrawParams_ Parameters required for withdrawal
     */
    function withdraw(WithdrawParams memory withdrawParams_) external;

    /**
     * @notice Allows batch withdrawal of tokens from the vault
     * @param withdrawParamsArr_ Array of parameters required for withdrawals
     */
    function withdrawBatch(WithdrawParams[] memory withdrawParamsArr_) external;

    /**
     * @notice Allows withdrawal by traits from the vault
     * @param traitWithdrawParams_ Parameters required for trait withdrawal
     */
    function traitWithdraw(
        TraitWithdrawParams memory traitWithdrawParams_
    ) external;

    function buyFromVault(
        BuyTypes buyType_,
        bytes calldata userData_
    ) external payable;

    function VAULT_NATIVE_BUYING_FLAG() external view returns (string memory);

    /**
     * @notice Fetches information about the vault
     * @return communityId_ ID of the community associated with the vault
     * @return vaultType_ Type of the vault
     * @return vaultTypeNonce_ Nonce of the vault
     * @return state Vault state
     */
    function getVaultInfo()
        external
        view
        returns (
            uint32 communityId_,
            uint8 vaultType_,
            uint256 vaultTypeNonce_,
            bool state
        );

    /**
     * @notice Fetches the whitelist of receivable tokens
     * @return An array of addresses representing the whitelist
     */
    function getReceivablesWhitelist() external view returns (address[] memory);

    /**
     * @notice Fetches the supported redeem modes
     * @return An array of supported redeem modes
     */
    function getSupportedRedeemModes()
        external
        view
        returns (RedeemModes[] memory);

    /**
     * @notice Fetches information about whitelisted tokens
     * @return An array of WhitelistedTokenInfo structures
     */
    function getReceivablesWhitelistInfo()
        external
        view
        returns (WhitelistedTokenInfo[] memory);

    /**
     * @notice Fetches the type of a whitelisted token
     * @param whitelistedToken_ The address of the whitelisted token
     * @return The type of the whitelisted token
     */
    function getWhitelistedTokenType(
        address whitelistedToken_
    ) external view returns (TokenTypes);

    function getBaseBuySettings()
        external
        view
        returns (BaseBuySettings memory);

    function getBuySettingsInfo(
        BuyTypes[] calldata buyTypesArr_
    ) external view returns (BuySettingsInfo memory);

    function getBuyTypeInfo(
        BuyTypes[] calldata buyTypesArr_
    ) external view returns (BuyTypeInfo[] memory);

    function getBuyTypeData(
        BuyTypes buyType_
    ) external view returns (BuyTypeData memory buyTypeData_);

    /**
     * @notice Checks if a token is in the receivables whitelist
     * @param tokenAddr_ The address of the token to check
     * @return True if the token is in the whitelist, false otherwise
     */
    function isInReceivablesWhitelist(
        address tokenAddr_
    ) external view returns (bool);

    /**
     * @notice Checks if a redeem mode is supported by the vault
     * @param redeemMode_ The redeem mode to check
     * @return True if the redeem mode is supported, false otherwise
     */
    function isRedeemModeSupported(
        RedeemModes redeemMode_
    ) external view returns (bool);

    function isBuyable(BuyTypes buyType_) external view returns (bool);

    /**
     * @notice Enable or disable a vault
     * @param newState_ The new state
     */
    function updateVaultState(bool newState_) external;
}

// SPDX-License-Identifier: UNLICENCED
pragma solidity 0.8.25;

import "../../@galaxis/registries/contracts/CommunityRegistry.sol";
import "../../Traits/Implementers/Generic/GenericTrait.sol";
import "./IGenericVault.sol";

/**
 * @title INFTVault
 * @dev Interface defining operations and data structures for the NFTVault
 */
interface INFTVault is IGenericVault {
    /**
     * @dev Contains details about a token
     */
    struct TokenInfo {
        address tokenAddr; // Address of the token
        uint256 tokenId; // ID of the token
        TokenTypes tokenType; // Type of the token
    }

    /**
     * @dev Contains data for random redeem
     */
    struct RandomRedeemData {
        address recipientAddr; // Recipient address
        TokenInfo tokenInfo; // Information about the token
        uint256 randomNumber; // Generated random number
        uint8 luck; // Luck metric in persent
    }

    /**
     * @dev Contains data for direct selection of tokens
     */
    struct DirectSelectData {
        address recipient; // Recipient address
        TokenInfo tokenInfo; // Information about the token is wanted to be selected
    }

    /**
     * @dev Thrown when provided NFT buy data is invalid
     */
    error NFTVaultInvalidNFTBuyData(address nftAddr, uint256 tokenId);

    /**
     * @dev Thrown when either the payment token address is invalid or the sender address is zero
     */
    error NFTVaultInvalidPaymentTokenOrSender(address tokenAddr);

    error NFTVaultCallerNotABuyERC1155Addr(address tokenAddr);

    /**
     * @dev Thrown when the user balance is lower than NFT price
     */
    error NFTVaultNotEnoughTokensToBuy(uint256 userBalance, uint256 tokenPrice);

    /**
     * @dev Thrown when the request ID is not exists
     */
    error NFTVaultInvalidRequestId(uint256 requestId);

    /**
     * @dev Thrown when the request ID has already been processed
     */
    error NFTVaultRequestIdHasAlreadyBeenProcessed(uint256 requestId);

    /**
     * @dev Triggered when the total NFT supply amount is not enough
     */
    error NFTVaultInvalidTotalNFTSupplyAmount();

    /**
     * @dev Triggered when NFTs is not buyable
     */
    error NFTVaultUnableToBuyNFTs();

    /**
     * @dev Triggered when an address used is the zero address
     */
    error NFTVaultZeroAddress();

    /**
     * @dev Triggered when the pseudo-random equals to 0
     */
    error NFTVaultInvalidPseudoRandomInterval();

    /**
     * @dev Triggered when there's an issue with the sequential data used
     */
    error NFTVaultInvalidSequentialData();

    /**
     * @dev Emitted when an NFT has been successfully sold
     */
    event NFTSold(
        address nftRecipient,
        address indexed nftAddr,
        uint256 tokenId,
        uint256 paymentTokensAmount
    );

    /**
     * @dev Initializes the NFTVault with necessary settings and configurations
     * @param communityRegistry_ The address of the community registry
     */
    function __NFTVault_init(
        CommunityRegistry communityRegistry_,
        GenericVaultInitParams calldata initParams_
    ) external;

    /**
     * @dev Returns the total supply amount of the NFTVault
     * @return Total NFT supply amount
     */
    function totalNFTVaultSupplyAmount() external view returns (uint256);

    /**
     * @dev Gets the number of pending NFTs (for random withdraw)
     * @return Amount of pending NFTs
     */
    function pendingNFTsAmount() external view returns (uint256);

    /**
     * @dev Retrieves the random redeem data associated with a specific request ID
     * @param requestId_ The ID of the request to fetch data for
     * @return RandomRedeemData structure containing details of the redeem request associated with the given ID
     */
    function getRandomRedeemData(
        uint256 requestId_
    ) external view returns (RandomRedeemData memory);

    /**
     * @dev Fetches the last random request ID for a specific trait and token ID
     * @param trait_ Address of the given trait
     * @param tokenId_ The community token ID
     * @return Last random request ID
     */
    function getLastRandomRequestIdForTrait(
        GenericTrait trait_,
        uint32 tokenId_
    ) external view returns (uint256);

    /**
     * @dev Fetches the last random request ID associated with a user address (for buy)
     * @param userAddr_ Address of the user
     * @return Last random request ID
     */
    function getLastRandomRequestIdForUser(
        address userAddr_
    ) external view returns (uint256);

    /**
     * @dev Fetches all random request IDs associated with a specific trait and community token ID
     * @param trait_ The given trait
     * @param tokenId_ The token ID
     * @return Array containing all random request IDs for the trait and community token ID
     */
    function getAllRandomRequestIdsForTrait(
        GenericTrait trait_,
        uint32 tokenId_
    ) external view returns (uint256[] memory);

    /**
     * @dev Retrieves all random request IDs associated with a user address
     * @param userAddr_ Address of the user
     * @return Array containing all random request IDs for the user address
     */
    function getAllRandomRequestIdsForUser(
        address userAddr_
    ) external view returns (uint256[] memory);

    /**
     * @dev Obtains token information for a pseudo-random process based on a trait and token ID
     * @param trait_ The given trait
     * @param tokenId_ Specific token ID
     * @return TokenInfo structure containing details of the token for the trait and token ID
     */
    function getTokenInfoForPseudoRandomForTrait(
        GenericTrait trait_,
        uint32 tokenId_
    ) external view returns (TokenInfo memory);

    /**
     * @dev Retrieves token information for a pseudo-random process based on a buyer's address
     * @param buyer_ Address of the buyer
     * @return TokenInfo structure containing details of the token for the buyer
     */
    function getTokenInfoForPseudoRandomForBuy(
        address buyer_
    ) external view returns (TokenInfo memory);

    /**
     * @dev Obtains token information based on a given random number
     * @param randomNumber_ The random number to search by
     * @return tokenInfo_ TokenInfo structure related to the provided random number
     */
    function getTokenInfoByRandomNumber(
        uint256 randomNumber_
    ) external view returns (TokenInfo memory tokenInfo_);

    /**
     * @dev Determines the amount of NFTs that are available (without pending one)
     * @return Amount of free NFTs available
     */
    function getFreeNFTSupplyAmount() external view returns (uint256);

    /**
     * @dev Determines the account key based on a trait and token ID
     * @param trait_ Address of the given trait
     * @param tokenId_ Specific token ID
     * @return Account key derived from trait and token ID
     */
    function getTraitAccountKey(
        address trait_,
        uint32 tokenId_
    ) external view returns (bytes32);

    /**
     * @dev Determines the account key for a specific user address
     * @param userAddr_ Address of the user
     * @return Account key for the user
     */
    function getAccountKey(address userAddr_) external view returns (bytes32);
}

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

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"_galaxisRegistry","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"FailedCreateClone","type":"error"},{"inputs":[{"internalType":"uint32","name":"","type":"uint32"}],"name":"TraitFactoryInvalidCommunityId","type":"error"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"TraitFactoryNotCurrent","type":"error"},{"inputs":[],"name":"TraitFactoryTokenNotInstalled","type":"error"},{"inputs":[],"name":"TraitFactoryTraitRegistryNotInstalled","type":"error"},{"inputs":[],"name":"TraitFactoryUnauthorized","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"inputs":[],"name":"GOLDEN_KEY","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"RANDOM_CONSUMER","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"REGISTRY_KEY_FACTORY","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"TRAIT_CONSUMER","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"TRAIT_REGISTRY_ADMIN","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"TRAIT_TYPE","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"pure","type":"function"},{"inputs":[{"components":[{"internalType":"uint32","name":"communityId","type":"uint32"},{"internalType":"uint256","name":"start","type":"uint256"},{"internalType":"uint256","name":"end","type":"uint256"},{"internalType":"bool","name":"enabled","type":"bool"},{"internalType":"string","name":"ipfsHash","type":"string"},{"internalType":"string","name":"name","type":"string"},{"internalType":"uint32","name":"tokenNum","type":"uint32"},{"internalType":"bytes[]","name":"defaults","type":"bytes[]"}],"internalType":"struct GenericTraitFactory.inputTraitStruct","name":"_inputTrait","type":"tuple"},{"components":[{"internalType":"bool","name":"inverted","type":"bool"}],"internalType":"struct traitConfig","name":"_traitConfig","type":"tuple"}],"name":"addTrait","outputs":[{"internalType":"uint16","name":"traitId","type":"uint16"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"baseVersion","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"galaxisRegistry","outputs":[{"internalType":"contract IRegistry","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"golden","type":"string"}],"name":"newProxy","outputs":[{"internalType":"address","name":"result","type":"address"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_tracker","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"}],"name":"retrieve721","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_tracker","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"retrieveERC20","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"retrieveETH","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"tellEverything","outputs":[{"components":[{"internalType":"string","name":"_REGISTRY_KEY","type":"string"},{"internalType":"uint8","name":"_TRAIT_TYPE","type":"uint8"},{"internalType":"uint256","name":"_baseVersion","type":"uint256"},{"internalType":"uint256","name":"_version","type":"uint256"}],"internalType":"struct GenericTraitFactory.factoryInfo","name":"","type":"tuple"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"version","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"pure","type":"function"}]

60a060405234801561001057600080fd5b50604051612d0b380380612d0b83398101604081905261002f916100a0565b80808061003b33610050565b6001600160a01b0316608052506100d0915050565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6000602082840312156100b257600080fd5b81516001600160a01b03811681146100c957600080fd5b9392505050565b608051612c046101076000396000818161026c0152818161051a0152818161061101528181610e4701526112650152612c046000f3fe6080604052600436106101095760003560e01c80638da5cb5b11610095578063b90b865a11610064578063b90b865a1461031d578063ba3f711614610350578063d5b014c314610363578063e7a2c06014610378578063f2fde38b1461038d57600080fd5b80638da5cb5b146102a657806396393e07146102c4578063a5b3abfb146102e6578063b2ae54b81461030657600080fd5b806352aeec22116100dc57806352aeec22146101b557806354fd4d50146101e9578063680da49914610200578063715018a6146102455780637671114d1461025a57600080fd5b806303ed8f791461010e57806317fd1e2f146101555780632a65a22d146101775780632f151b7614610193575b600080fd5b34801561011a57600080fd5b506101427f5f44850a3058956c58278b0f5308763773e794b8d861b6e80ae34a8e09a15b8c81565b6040519081526020015b60405180910390f35b34801561016157600080fd5b50610175610170366004611690565b6103ad565b005b34801561018357600080fd5b506040516006815260200161014c565b34801561019f57600080fd5b506101a861042b565b60405161014c919061170c565b3480156101c157600080fd5b506101427fb55ee8fa278d4d711a66e8ddff0365a4333380c8c6dbcdf8c74675b71e0e765981565b3480156101f557600080fd5b506378a52ea5610142565b34801561020c57600080fd5b5060408051808201909152601381527223a7a62222a72faa2920a4aa2faa2ca822af9b60691b60208201525b60405161014c9190611755565b34801561025157600080fd5b5061017561048f565b34801561026657600080fd5b5061028e7f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b03909116815260200161014c565b3480156102b257600080fd5b506000546001600160a01b031661028e565b3480156102d057600080fd5b50610142600080516020612baf83398151915281565b3480156102f257600080fd5b50610175610301366004611690565b6104a3565b34801561031257600080fd5b506378a467d1610142565b34801561032957600080fd5b5061033d61033836600461176f565b610515565b60405161ffff909116815260200161014c565b61028e61035e36600461187c565b610e42565b34801561036f57600080fd5b50610175610f4e565b34801561038457600080fd5b50610238610f85565b34801561039957600080fd5b506101756103a83660046118c5565b610fb3565b6103b5611029565b60405163a9059cbb60e01b8152336004820152602481018290526001600160a01b0383169063a9059cbb906044016020604051808303816000875af1158015610402573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061042691906118f0565b505050565b610459604051806080016040528060608152602001600060ff16815260200160008152602001600081525090565b604051806080016040528061046c610f85565b8152600660208201526378a467d160408201526378a52ea5606090910152919050565b610497611029565b6104a16000611083565b565b6104ab611029565b6040516323b872dd60e01b8152306004820152336024820152604481018290526001600160a01b038316906323b872dd90606401600060405180830381600087803b1580156104f957600080fd5b505af115801561050d573d6000803e3d6000fd5b505050505050565b6000307f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166374b9982c61054f610f85565b6040518263ffffffff1660e01b815260040161056b9190611755565b602060405180830381865afa158015610588573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105ac919061190d565b6001600160a01b0316146105da57604051634dcce05960e01b81523060048201526024015b60405180910390fd5b604051631d2e660b60e21b815260206004820152600e60248201526d10d3d353555392551657d31254d560921b60448201526000907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906374b9982c90606401602060405180830381865afa158015610660573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610684919061190d565b905060006001600160a01b03821663d0f4a5376106a4602088018861193c565b6040516001600160e01b031960e084901b16815263ffffffff919091166004820152602401600060405180830381865afa1580156106e6573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261070e9190810190611959565b509150506001600160a01b03811661074f5761072d602086018661193c565b6040516323b46b2360e11b815263ffffffff90911660048201526024016105d1565b600180546001600160a01b0319166001600160a01b0383169081179091556000906374b9982c61079361078860e08a0160c08b0161193c565b63ffffffff166110d3565b6040516020016107a391906119fa565b6040516020818303038152906040526040518263ffffffff1660e01b81526004016107ce9190611755565b602060405180830381865afa1580156107eb573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061080f919061190d565b90506001600160a01b038116610838576040516391ab78e560e01b815260040160405180910390fd5b600154604051631092dd0160e11b8152600080516020612baf83398151915260048201523360248201526000916001600160a01b031690632125ba0290604401602060405180830381865afa158015610895573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108b991906118f0565b6040516382027b6d60e01b8152600080516020612baf83398151915260048201523360248201529091506000906001600160a01b038416906382027b6d90604401602060405180830381865afa158015610917573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061093b91906118f0565b905081158015610949575080155b156109675760405163ac1cb3af60e01b815260040160405180910390fd5b826001600160a01b031663988556926040518163ffffffff1660e01b8152600401602060405180830381865afa1580156109a5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109c99190611a31565b6001549096506000906001600160a01b03166374b9982c6109f361078860e08d0160c08e0161193c565b604051602001610a039190611a55565b6040516020818303038152906040526040518263ffffffff1660e01b8152600401610a2e9190611755565b602060405180830381865afa158015610a4b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a6f919061190d565b90506001600160a01b038116610a9857604051633220103360e01b815260040160405180910390fd5b600154604051632474521560e21b8152600080516020612baf83398151915260048201523060248201526001600160a01b03909116906391d1485490604401602060405180830381865afa158015610af4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b1891906118f0565b610b8e57600154604051632f2ff15d60e01b8152600080516020612baf83398151915260048201523060248201526001600160a01b0390911690632f2ff15d90604401600060405180830381600087803b158015610b7557600080fd5b505af1158015610b89573d6000803e3d6000fd5b505050505b600080610bc3868a610ba5368e90038e018e611a83565b8e8060e00190610bb59190611acf565b610bbe91611b20565b6111dc565b60408051600180825281830190925292945090925060009190816020015b610c3b604051806101000160405280600061ffff168152602001600060ff168152602001600081526020016000815260200160001515815260200160006001600160a01b0316815260200160608152602001606081525090565b815260200190600190039081610be15790505090506040518061010001604052808b61ffff168152602001610c6e600690565b60ff1681526020018d6020013581526020018d6040013581526020018d6060016020810190610c9d9190611bba565b151581526001600160a01b0384166020820152604001610cc060808f018f611bd7565b8080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250505090825250602001610d0760a08f018f611bd7565b8080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201829052509390945250508351849250610d4e57610d4e611c1e565b602090810291909101015260405163498f781560e01b81526001600160a01b0388169063498f781590610d85908490600401611c34565b600060405180830381600087803b158015610d9f57600080fd5b505af1158015610db3573d6000803e3d6000fd5b505050506001600160a01b03831615610e335760405163839ae78760e01b81526001600160a01b03848116600483015261ffff8c1660248301526001604483015288169063839ae78790606401600060405180830381600087803b158015610e1a57600080fd5b505af1158015610e2e573d6000803e3d6000fd5b505050505b50505050505050505092915050565b6000807f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166374b9982c846040518263ffffffff1660e01b8152600401610e919190611755565b602060405180830381865afa158015610eae573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ed2919061190d565b905060008160601b9050604051733d602d80600a3d3981f3363d3d373d3d3d363d7360601b81528160148201526e5af43d82803e903d91602b57fd5bf360881b60288201526037816000f09350506001600160a01b038316610f475760405163173392a560e21b815260040160405180910390fd5b5050919050565b610f56611029565b60405133904780156108fc02916000818181858888f19350505050158015610f82573d6000803e3d6000fd5b50565b60408051808201909152601481527354524149545f545950455f365f464143544f525960601b602082015290565b610fbb611029565b6001600160a01b0381166110205760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b60648201526084016105d1565b610f8281611083565b6000546001600160a01b031633146104a15760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016105d1565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6060816000036110fa5750506040805180820190915260018152600360fc1b602082015290565b8160005b8115611124578061110e81611d27565b915061111d9050600a83611d56565b91506110fe565b60008167ffffffffffffffff81111561113f5761113f6117cf565b6040519080825280601f01601f191660200182016040528015611169576020820181803683370190505b5090505b84156111d45761117e600183611d6a565b915061118b600a86611d83565b611196906030611d97565b60f81b8183815181106111ab576111ab611c1e565b60200101906001600160f81b031916908160001a9053506111cd600a86611d56565b945061116d565b949350505050565b600080806001600160a01b0387166304a59f0560066040516001600160e01b031960e084901b16815260ff9091166004820152602401602060405180830381865afa15801561122f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611253919061190d565b90506001600160a01b03811661156e577f00000000000000000000000000000000000000000000000000000000000000006040516112909061166e565b6001600160a01b039091168152602001604051809103906000f0801580156112bc573d6000803e3d6000fd5b5090506001600160a01b038716634ff8ed928260066040516001600160e01b031960e085901b1681526001600160a01b03909216600483015260ff166024820152604401600060405180830381600087803b15801561131a57600080fd5b505af115801561132e573d6000803e3d6000fd5b5050600154604051632474521560e21b81527f5f44850a3058956c58278b0f5308763773e794b8d861b6e80ae34a8e09a15b8c60048201526001600160a01b03858116602483015290911692506391d148549150604401602060405180830381865afa1580156113a2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113c691906118f0565b61145057600154604051632f2ff15d60e01b81527f5f44850a3058956c58278b0f5308763773e794b8d861b6e80ae34a8e09a15b8c60048201526001600160a01b03838116602483015290911690632f2ff15d90604401600060405180830381600087803b15801561143757600080fd5b505af115801561144b573d6000803e3d6000fd5b505050505b600154604051632474521560e21b81527fb55ee8fa278d4d711a66e8ddff0365a4333380c8c6dbcdf8c74675b71e0e765960048201526001600160a01b038381166024830152909116906391d1485490604401602060405180830381865afa1580156114c0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114e491906118f0565b61156e57600154604051632f2ff15d60e01b81527fb55ee8fa278d4d711a66e8ddff0365a4333380c8c6dbcdf8c74675b71e0e765960048201526001600160a01b03838116602483015290911690632f2ff15d90604401600060405180830381600087803b15801561155557600080fd5b505af1158015611569573d6000803e3d6000fd5b505050505b60006115a361035e60408051808201909152601381527223a7a62222a72faa2920a4aa2faa2ca822af9b60691b602082015290565b604051631f1ab80d60e11b815290915081906001600160a01b03821690633e35701a906115da908c908c908c908c90600401611daa565b600060405180830381600087803b1580156115f457600080fd5b505af1158015611608573d6000803e3d6000fd5b50505050806001600160a01b031663e1c7392a6040518163ffffffff1660e01b8152600401600060405180830381600087803b15801561164757600080fd5b505af115801561165b573d6000803e3d6000fd5b50949b929a509198505050505050505050565b610d7b80611e3483390190565b6001600160a01b0381168114610f8257600080fd5b600080604083850312156116a357600080fd5b82356116ae8161167b565b946020939093013593505050565b60005b838110156116d75781810151838201526020016116bf565b50506000910152565b600081518084526116f88160208601602086016116bc565b601f01601f19169290920160200192915050565b60208152600082516080602084015261172860a08401826116e0565b905060ff602085015116604084015260408401516060840152606084015160808401528091505092915050565b60208152600061176860208301846116e0565b9392505050565b600080828403604081121561178357600080fd5b833567ffffffffffffffff81111561179a57600080fd5b840161010081870312156117ad57600080fd5b92506020601f19820112156117c157600080fd5b506020830190509250929050565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff8111828210171561180e5761180e6117cf565b604052919050565b600067ffffffffffffffff821115611830576118306117cf565b50601f01601f191660200190565b600061185161184c84611816565b6117e5565b905082815283838301111561186557600080fd5b828260208301376000602084830101529392505050565b60006020828403121561188e57600080fd5b813567ffffffffffffffff8111156118a557600080fd5b8201601f810184136118b657600080fd5b6111d48482356020840161183e565b6000602082840312156118d757600080fd5b81356117688161167b565b8015158114610f8257600080fd5b60006020828403121561190257600080fd5b8151611768816118e2565b60006020828403121561191f57600080fd5b81516117688161167b565b63ffffffff81168114610f8257600080fd5b60006020828403121561194e57600080fd5b81356117688161192a565b60008060006060848603121561196e57600080fd5b835167ffffffffffffffff81111561198557600080fd5b8401601f8101861361199657600080fd5b80516119a461184c82611816565b8181528760208385010111156119b957600080fd5b6119ca8260208301602086016116bc565b80955050505060208401516119de8161167b565b60408501519092506119ef8161192a565b809150509250925092565b6e54524149545f52454749535452595f60881b815260008251611a2481600f8501602087016116bc565b91909101600f0192915050565b600060208284031215611a4357600080fd5b815161ffff8116811461176857600080fd5b65544f4b454e5f60d01b815260008251611a768160068501602087016116bc565b9190910160060192915050565b600060208284031215611a9557600080fd5b6040516020810181811067ffffffffffffffff82111715611ab857611ab86117cf565b6040528235611ac6816118e2565b81529392505050565b6000808335601e19843603018112611ae657600080fd5b83018035915067ffffffffffffffff821115611b0157600080fd5b6020019150600581901b3603821315611b1957600080fd5b9250929050565b600067ffffffffffffffff80841115611b3b57611b3b6117cf565b8360051b6020611b4d602083016117e5565b86815291850191602081019036841115611b6657600080fd5b865b84811015611bae57803586811115611b805760008081fd5b880136601f820112611b925760008081fd5b611ba036823587840161183e565b845250918301918301611b68565b50979650505050505050565b600060208284031215611bcc57600080fd5b8135611768816118e2565b6000808335601e19843603018112611bee57600080fd5b83018035915067ffffffffffffffff821115611c0957600080fd5b602001915036819003821315611b1957600080fd5b634e487b7160e01b600052603260045260246000fd5b600060208083018184528085518083526040925060408601915060408160051b87010184880160005b83811015611d0357603f198984030185528151805161ffff1684528781015160ff168885015286810151878501526060808201519085015260808082015115159085015260a0808201516001600160a01b03169085015260c0808201516101008287018190529190611cd1838801826116e0565b9250505060e08083015192508582038187015250611cef81836116e0565b968901969450505090860190600101611c5d565b509098975050505050505050565b634e487b7160e01b600052601160045260246000fd5b600060018201611d3957611d39611d11565b5060010190565b634e487b7160e01b600052601260045260246000fd5b600082611d6557611d65611d40565b500490565b81810381811115611d7d57611d7d611d11565b92915050565b600082611d9257611d92611d40565b500690565b80820180821115611d7d57611d7d611d11565b60006080820160018060a01b0387168352602061ffff871660208501528551151560408501526080606085015281855180845260a08601915060a08160051b87010193506020870160005b82811015611e2357609f19888703018452611e118683516116e0565b95509284019290840190600101611df5565b50939a995050505050505050505056fe60a0604052348015600f57600080fd5b50604051610d7b380380610d7b833981016040819052602c916041565b6001600160a01b03166080526001600055606f565b600060208284031215605257600080fd5b81516001600160a01b0381168114606857600080fd5b9392505050565b608051610cec61008f60003960008181606f015260f80152610cec6000f3fe608060405234801561001057600080fd5b506004361061004c5760003560e01c806354fd4d50146100515780637671114d1461006a578063b2ae54b8146100a9578063c97feff8146100b3575b600080fd5b6378a467d15b6040519081526020015b60405180910390f35b6100917f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b039091168152602001610061565b637895f0b1610057565b6100c66100c136600461090e565b6100c8565b005b604051631d2e660b60e21b815260206004820152600a60248201526920a1aa24a7a72fa42aa160b11b60448201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906374b9982c90606401602060405180830381865afa158015610147573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061016b9190610984565b6001600160a01b0316336001600160a01b0316146101e15760405162461bcd60e51b815260206004820152602860248201527f47656e657269635472616974436f6e73756d65723a20696e76616c6964206d73604482015267339739b2b73232b960c11b60648201526084015b60405180910390fd5b60026101f060208301836109be565b6003811115610201576102016109a8565b1461025f5760405162461bcd60e51b815260206004820152602860248201527f47656e657269635472616974436f6e73756d65723a20696e76616c696420416360448201526774696f6e5479706560c01b60648201526084016101d8565b61026a83838361026f565b505050565b6002600054036102c15760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c0060448201526064016101d8565b600260009081556102d560e08301836109df565b8101906102e29190610ac6565b90506102f460a0830160808401610bab565b63ffffffff16816000015163ffffffff16146103775761031a6060830160408401610bab565b61032a6080840160608501610bab565b61033a60a0850160808601610bab565b8351604051637368ea1d60e01b815263ffffffff9485166004820152928416602484015290831660448301529190911660648201526084016101d8565b60006103896040850160208601610bc6565b82516040516331a9108f60e11b815263ffffffff90911660048201529091506000906001600160a01b03831690636352211e90602401602060405180830381865afa1580156103dc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104009190610984565b9050856001600160a01b0316816001600160a01b03161461047e578061042c6060860160408701610bab565b61043c6080870160608801610bab565b85516040516340ecbf1160e11b81526001600160a01b03909416600485015263ffffffff928316602485015290821660448401521660648201526084016101d8565b60006104906060870160408801610bc6565b60208501516040516301db446960e01b815261ffff90911660048201526001600160a01b0391909116906301db446990602401602060405180830381865afa1580156104e0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105049190610984565b90506001600160a01b038116610577576105246060860160408701610bab565b6105346080870160608801610bab565b85516020870151604051639dade8d160e01b815263ffffffff948516600482015292841660248401529216604482015261ffff90911660648201526084016101d8565b6000816001600160a01b0316632a65a22d6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156105b7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105db9190610be3565b90508061ffff1660061461060857604051637a2abb0760e11b815261ffff821660048201526024016101d8565b8451604051638174263b60e01b815263ffffffff90911660048201526001906001600160a01b03841690638174263b90602401602060405180830381865afa158015610658573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061067c9190610c00565b60ff16036108e75760006106936020890189610bc6565b604051631d2e660b60e21b815260206004820152601960248201527f434f4d4d554e4954595f5641554c54535f52454749535452590000000000000060448201526001600160a01b0391909116906374b9982c90606401602060405180830381865afa158015610707573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061072b9190610984565b90506000816001600160a01b031663f6e4d726856001600160a01b031663eb76dfea6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561077c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107a09190610c23565b6040518263ffffffff1660e01b81526004016107be91815260200190565b602060405180830381865afa1580156107db573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107ff9190610984565b604080516060810182526001600160a01b0387811682528a5163ffffffff1660208301528a830151828401529151630cd4313d60e21b815292935090831691633350c4f49161085091600401610c3c565b600060405180830381600087803b15801561086a57600080fd5b505af115801561087e573d6000803e3d6000fd5b5050885160405163c6402b5f60e01b815263ffffffff90911660048201526001600160a01b038716925063c6402b5f9150602401600060405180830381600087803b1580156108cc57600080fd5b505af11580156108e0573d6000803e3d6000fd5b5050505050505b50506001600055505050505050565b6001600160a01b038116811461090b57600080fd5b50565b600080600083850361012081121561092557600080fd5b8435610930816108f6565b935060e0601f198201121561094457600080fd5b506020840191506101008085013567ffffffffffffffff81111561096757600080fd5b850180870382131561097857600080fd5b80925050509250925092565b60006020828403121561099657600080fd5b81516109a1816108f6565b9392505050565b634e487b7160e01b600052602160045260246000fd5b6000602082840312156109d057600080fd5b8135600481106109a157600080fd5b6000808335601e198436030181126109f657600080fd5b83018035915067ffffffffffffffff821115610a1157600080fd5b602001915036819003821315610a2657600080fd5b9250929050565b634e487b7160e01b600052604160045260246000fd5b6040516060810167ffffffffffffffff81118282101715610a6657610a66610a2d565b60405290565b604051601f8201601f1916810167ffffffffffffffff81118282101715610a9557610a95610a2d565b604052919050565b803563ffffffff81168114610ab157600080fd5b919050565b61ffff8116811461090b57600080fd5b60006020808385031215610ad957600080fd5b823567ffffffffffffffff80821115610af157600080fd5b9084019060608287031215610b0557600080fd5b610b0d610a43565b610b1683610a9d565b815283830135610b2581610ab6565b81850152604083013582811115610b3b57600080fd5b80840193505086601f840112610b5057600080fd5b823582811115610b6257610b62610a2d565b610b74601f8201601f19168601610a6c565b92508083528785828601011115610b8a57600080fd5b80858501868501376000908301909401939093526040830152509392505050565b600060208284031215610bbd57600080fd5b6109a182610a9d565b600060208284031215610bd857600080fd5b81356109a1816108f6565b600060208284031215610bf557600080fd5b81516109a181610ab6565b600060208284031215610c1257600080fd5b815160ff811681146109a157600080fd5b600060208284031215610c3557600080fd5b5051919050565b6000602080835260018060a01b03845116602084015263ffffffff60208501511660408401526040840151606080850152805180608086015260005b81811015610c945782810184015186820160a001528301610c78565b50600060a0828701015260a0601f19601f83011686010193505050509291505056fea26469706673582212201db57f09451a74691fca2e7f813ecd486fe771a45d296e9e19bb9268e829d1a964736f6c634300081900332da7e0979ec8e77ca079149cb4ef8855c611521d4041faf48e3980b5b4fd5daaa26469706673582212202095ebbf8cecbb05c9f0329a19b7fd5562399694dbdaf47cb5ae7efd726994b664736f6c63430008190033000000000000000000000000dbd9608fbca959828c1615d29aeb3dc872d40ae2

Deployed Bytecode

0x6080604052600436106101095760003560e01c80638da5cb5b11610095578063b90b865a11610064578063b90b865a1461031d578063ba3f711614610350578063d5b014c314610363578063e7a2c06014610378578063f2fde38b1461038d57600080fd5b80638da5cb5b146102a657806396393e07146102c4578063a5b3abfb146102e6578063b2ae54b81461030657600080fd5b806352aeec22116100dc57806352aeec22146101b557806354fd4d50146101e9578063680da49914610200578063715018a6146102455780637671114d1461025a57600080fd5b806303ed8f791461010e57806317fd1e2f146101555780632a65a22d146101775780632f151b7614610193575b600080fd5b34801561011a57600080fd5b506101427f5f44850a3058956c58278b0f5308763773e794b8d861b6e80ae34a8e09a15b8c81565b6040519081526020015b60405180910390f35b34801561016157600080fd5b50610175610170366004611690565b6103ad565b005b34801561018357600080fd5b506040516006815260200161014c565b34801561019f57600080fd5b506101a861042b565b60405161014c919061170c565b3480156101c157600080fd5b506101427fb55ee8fa278d4d711a66e8ddff0365a4333380c8c6dbcdf8c74675b71e0e765981565b3480156101f557600080fd5b506378a52ea5610142565b34801561020c57600080fd5b5060408051808201909152601381527223a7a62222a72faa2920a4aa2faa2ca822af9b60691b60208201525b60405161014c9190611755565b34801561025157600080fd5b5061017561048f565b34801561026657600080fd5b5061028e7f000000000000000000000000dbd9608fbca959828c1615d29aeb3dc872d40ae281565b6040516001600160a01b03909116815260200161014c565b3480156102b257600080fd5b506000546001600160a01b031661028e565b3480156102d057600080fd5b50610142600080516020612baf83398151915281565b3480156102f257600080fd5b50610175610301366004611690565b6104a3565b34801561031257600080fd5b506378a467d1610142565b34801561032957600080fd5b5061033d61033836600461176f565b610515565b60405161ffff909116815260200161014c565b61028e61035e36600461187c565b610e42565b34801561036f57600080fd5b50610175610f4e565b34801561038457600080fd5b50610238610f85565b34801561039957600080fd5b506101756103a83660046118c5565b610fb3565b6103b5611029565b60405163a9059cbb60e01b8152336004820152602481018290526001600160a01b0383169063a9059cbb906044016020604051808303816000875af1158015610402573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061042691906118f0565b505050565b610459604051806080016040528060608152602001600060ff16815260200160008152602001600081525090565b604051806080016040528061046c610f85565b8152600660208201526378a467d160408201526378a52ea5606090910152919050565b610497611029565b6104a16000611083565b565b6104ab611029565b6040516323b872dd60e01b8152306004820152336024820152604481018290526001600160a01b038316906323b872dd90606401600060405180830381600087803b1580156104f957600080fd5b505af115801561050d573d6000803e3d6000fd5b505050505050565b6000307f000000000000000000000000dbd9608fbca959828c1615d29aeb3dc872d40ae26001600160a01b03166374b9982c61054f610f85565b6040518263ffffffff1660e01b815260040161056b9190611755565b602060405180830381865afa158015610588573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105ac919061190d565b6001600160a01b0316146105da57604051634dcce05960e01b81523060048201526024015b60405180910390fd5b604051631d2e660b60e21b815260206004820152600e60248201526d10d3d353555392551657d31254d560921b60448201526000907f000000000000000000000000dbd9608fbca959828c1615d29aeb3dc872d40ae26001600160a01b0316906374b9982c90606401602060405180830381865afa158015610660573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610684919061190d565b905060006001600160a01b03821663d0f4a5376106a4602088018861193c565b6040516001600160e01b031960e084901b16815263ffffffff919091166004820152602401600060405180830381865afa1580156106e6573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261070e9190810190611959565b509150506001600160a01b03811661074f5761072d602086018661193c565b6040516323b46b2360e11b815263ffffffff90911660048201526024016105d1565b600180546001600160a01b0319166001600160a01b0383169081179091556000906374b9982c61079361078860e08a0160c08b0161193c565b63ffffffff166110d3565b6040516020016107a391906119fa565b6040516020818303038152906040526040518263ffffffff1660e01b81526004016107ce9190611755565b602060405180830381865afa1580156107eb573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061080f919061190d565b90506001600160a01b038116610838576040516391ab78e560e01b815260040160405180910390fd5b600154604051631092dd0160e11b8152600080516020612baf83398151915260048201523360248201526000916001600160a01b031690632125ba0290604401602060405180830381865afa158015610895573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108b991906118f0565b6040516382027b6d60e01b8152600080516020612baf83398151915260048201523360248201529091506000906001600160a01b038416906382027b6d90604401602060405180830381865afa158015610917573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061093b91906118f0565b905081158015610949575080155b156109675760405163ac1cb3af60e01b815260040160405180910390fd5b826001600160a01b031663988556926040518163ffffffff1660e01b8152600401602060405180830381865afa1580156109a5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109c99190611a31565b6001549096506000906001600160a01b03166374b9982c6109f361078860e08d0160c08e0161193c565b604051602001610a039190611a55565b6040516020818303038152906040526040518263ffffffff1660e01b8152600401610a2e9190611755565b602060405180830381865afa158015610a4b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a6f919061190d565b90506001600160a01b038116610a9857604051633220103360e01b815260040160405180910390fd5b600154604051632474521560e21b8152600080516020612baf83398151915260048201523060248201526001600160a01b03909116906391d1485490604401602060405180830381865afa158015610af4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b1891906118f0565b610b8e57600154604051632f2ff15d60e01b8152600080516020612baf83398151915260048201523060248201526001600160a01b0390911690632f2ff15d90604401600060405180830381600087803b158015610b7557600080fd5b505af1158015610b89573d6000803e3d6000fd5b505050505b600080610bc3868a610ba5368e90038e018e611a83565b8e8060e00190610bb59190611acf565b610bbe91611b20565b6111dc565b60408051600180825281830190925292945090925060009190816020015b610c3b604051806101000160405280600061ffff168152602001600060ff168152602001600081526020016000815260200160001515815260200160006001600160a01b0316815260200160608152602001606081525090565b815260200190600190039081610be15790505090506040518061010001604052808b61ffff168152602001610c6e600690565b60ff1681526020018d6020013581526020018d6040013581526020018d6060016020810190610c9d9190611bba565b151581526001600160a01b0384166020820152604001610cc060808f018f611bd7565b8080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250505090825250602001610d0760a08f018f611bd7565b8080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201829052509390945250508351849250610d4e57610d4e611c1e565b602090810291909101015260405163498f781560e01b81526001600160a01b0388169063498f781590610d85908490600401611c34565b600060405180830381600087803b158015610d9f57600080fd5b505af1158015610db3573d6000803e3d6000fd5b505050506001600160a01b03831615610e335760405163839ae78760e01b81526001600160a01b03848116600483015261ffff8c1660248301526001604483015288169063839ae78790606401600060405180830381600087803b158015610e1a57600080fd5b505af1158015610e2e573d6000803e3d6000fd5b505050505b50505050505050505092915050565b6000807f000000000000000000000000dbd9608fbca959828c1615d29aeb3dc872d40ae26001600160a01b03166374b9982c846040518263ffffffff1660e01b8152600401610e919190611755565b602060405180830381865afa158015610eae573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ed2919061190d565b905060008160601b9050604051733d602d80600a3d3981f3363d3d373d3d3d363d7360601b81528160148201526e5af43d82803e903d91602b57fd5bf360881b60288201526037816000f09350506001600160a01b038316610f475760405163173392a560e21b815260040160405180910390fd5b5050919050565b610f56611029565b60405133904780156108fc02916000818181858888f19350505050158015610f82573d6000803e3d6000fd5b50565b60408051808201909152601481527354524149545f545950455f365f464143544f525960601b602082015290565b610fbb611029565b6001600160a01b0381166110205760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b60648201526084016105d1565b610f8281611083565b6000546001600160a01b031633146104a15760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016105d1565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6060816000036110fa5750506040805180820190915260018152600360fc1b602082015290565b8160005b8115611124578061110e81611d27565b915061111d9050600a83611d56565b91506110fe565b60008167ffffffffffffffff81111561113f5761113f6117cf565b6040519080825280601f01601f191660200182016040528015611169576020820181803683370190505b5090505b84156111d45761117e600183611d6a565b915061118b600a86611d83565b611196906030611d97565b60f81b8183815181106111ab576111ab611c1e565b60200101906001600160f81b031916908160001a9053506111cd600a86611d56565b945061116d565b949350505050565b600080806001600160a01b0387166304a59f0560066040516001600160e01b031960e084901b16815260ff9091166004820152602401602060405180830381865afa15801561122f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611253919061190d565b90506001600160a01b03811661156e577f000000000000000000000000dbd9608fbca959828c1615d29aeb3dc872d40ae26040516112909061166e565b6001600160a01b039091168152602001604051809103906000f0801580156112bc573d6000803e3d6000fd5b5090506001600160a01b038716634ff8ed928260066040516001600160e01b031960e085901b1681526001600160a01b03909216600483015260ff166024820152604401600060405180830381600087803b15801561131a57600080fd5b505af115801561132e573d6000803e3d6000fd5b5050600154604051632474521560e21b81527f5f44850a3058956c58278b0f5308763773e794b8d861b6e80ae34a8e09a15b8c60048201526001600160a01b03858116602483015290911692506391d148549150604401602060405180830381865afa1580156113a2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113c691906118f0565b61145057600154604051632f2ff15d60e01b81527f5f44850a3058956c58278b0f5308763773e794b8d861b6e80ae34a8e09a15b8c60048201526001600160a01b03838116602483015290911690632f2ff15d90604401600060405180830381600087803b15801561143757600080fd5b505af115801561144b573d6000803e3d6000fd5b505050505b600154604051632474521560e21b81527fb55ee8fa278d4d711a66e8ddff0365a4333380c8c6dbcdf8c74675b71e0e765960048201526001600160a01b038381166024830152909116906391d1485490604401602060405180830381865afa1580156114c0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114e491906118f0565b61156e57600154604051632f2ff15d60e01b81527fb55ee8fa278d4d711a66e8ddff0365a4333380c8c6dbcdf8c74675b71e0e765960048201526001600160a01b03838116602483015290911690632f2ff15d90604401600060405180830381600087803b15801561155557600080fd5b505af1158015611569573d6000803e3d6000fd5b505050505b60006115a361035e60408051808201909152601381527223a7a62222a72faa2920a4aa2faa2ca822af9b60691b602082015290565b604051631f1ab80d60e11b815290915081906001600160a01b03821690633e35701a906115da908c908c908c908c90600401611daa565b600060405180830381600087803b1580156115f457600080fd5b505af1158015611608573d6000803e3d6000fd5b50505050806001600160a01b031663e1c7392a6040518163ffffffff1660e01b8152600401600060405180830381600087803b15801561164757600080fd5b505af115801561165b573d6000803e3d6000fd5b50949b929a509198505050505050505050565b610d7b80611e3483390190565b6001600160a01b0381168114610f8257600080fd5b600080604083850312156116a357600080fd5b82356116ae8161167b565b946020939093013593505050565b60005b838110156116d75781810151838201526020016116bf565b50506000910152565b600081518084526116f88160208601602086016116bc565b601f01601f19169290920160200192915050565b60208152600082516080602084015261172860a08401826116e0565b905060ff602085015116604084015260408401516060840152606084015160808401528091505092915050565b60208152600061176860208301846116e0565b9392505050565b600080828403604081121561178357600080fd5b833567ffffffffffffffff81111561179a57600080fd5b840161010081870312156117ad57600080fd5b92506020601f19820112156117c157600080fd5b506020830190509250929050565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff8111828210171561180e5761180e6117cf565b604052919050565b600067ffffffffffffffff821115611830576118306117cf565b50601f01601f191660200190565b600061185161184c84611816565b6117e5565b905082815283838301111561186557600080fd5b828260208301376000602084830101529392505050565b60006020828403121561188e57600080fd5b813567ffffffffffffffff8111156118a557600080fd5b8201601f810184136118b657600080fd5b6111d48482356020840161183e565b6000602082840312156118d757600080fd5b81356117688161167b565b8015158114610f8257600080fd5b60006020828403121561190257600080fd5b8151611768816118e2565b60006020828403121561191f57600080fd5b81516117688161167b565b63ffffffff81168114610f8257600080fd5b60006020828403121561194e57600080fd5b81356117688161192a565b60008060006060848603121561196e57600080fd5b835167ffffffffffffffff81111561198557600080fd5b8401601f8101861361199657600080fd5b80516119a461184c82611816565b8181528760208385010111156119b957600080fd5b6119ca8260208301602086016116bc565b80955050505060208401516119de8161167b565b60408501519092506119ef8161192a565b809150509250925092565b6e54524149545f52454749535452595f60881b815260008251611a2481600f8501602087016116bc565b91909101600f0192915050565b600060208284031215611a4357600080fd5b815161ffff8116811461176857600080fd5b65544f4b454e5f60d01b815260008251611a768160068501602087016116bc565b9190910160060192915050565b600060208284031215611a9557600080fd5b6040516020810181811067ffffffffffffffff82111715611ab857611ab86117cf565b6040528235611ac6816118e2565b81529392505050565b6000808335601e19843603018112611ae657600080fd5b83018035915067ffffffffffffffff821115611b0157600080fd5b6020019150600581901b3603821315611b1957600080fd5b9250929050565b600067ffffffffffffffff80841115611b3b57611b3b6117cf565b8360051b6020611b4d602083016117e5565b86815291850191602081019036841115611b6657600080fd5b865b84811015611bae57803586811115611b805760008081fd5b880136601f820112611b925760008081fd5b611ba036823587840161183e565b845250918301918301611b68565b50979650505050505050565b600060208284031215611bcc57600080fd5b8135611768816118e2565b6000808335601e19843603018112611bee57600080fd5b83018035915067ffffffffffffffff821115611c0957600080fd5b602001915036819003821315611b1957600080fd5b634e487b7160e01b600052603260045260246000fd5b600060208083018184528085518083526040925060408601915060408160051b87010184880160005b83811015611d0357603f198984030185528151805161ffff1684528781015160ff168885015286810151878501526060808201519085015260808082015115159085015260a0808201516001600160a01b03169085015260c0808201516101008287018190529190611cd1838801826116e0565b9250505060e08083015192508582038187015250611cef81836116e0565b968901969450505090860190600101611c5d565b509098975050505050505050565b634e487b7160e01b600052601160045260246000fd5b600060018201611d3957611d39611d11565b5060010190565b634e487b7160e01b600052601260045260246000fd5b600082611d6557611d65611d40565b500490565b81810381811115611d7d57611d7d611d11565b92915050565b600082611d9257611d92611d40565b500690565b80820180821115611d7d57611d7d611d11565b60006080820160018060a01b0387168352602061ffff871660208501528551151560408501526080606085015281855180845260a08601915060a08160051b87010193506020870160005b82811015611e2357609f19888703018452611e118683516116e0565b95509284019290840190600101611df5565b50939a995050505050505050505056fe60a0604052348015600f57600080fd5b50604051610d7b380380610d7b833981016040819052602c916041565b6001600160a01b03166080526001600055606f565b600060208284031215605257600080fd5b81516001600160a01b0381168114606857600080fd5b9392505050565b608051610cec61008f60003960008181606f015260f80152610cec6000f3fe608060405234801561001057600080fd5b506004361061004c5760003560e01c806354fd4d50146100515780637671114d1461006a578063b2ae54b8146100a9578063c97feff8146100b3575b600080fd5b6378a467d15b6040519081526020015b60405180910390f35b6100917f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b039091168152602001610061565b637895f0b1610057565b6100c66100c136600461090e565b6100c8565b005b604051631d2e660b60e21b815260206004820152600a60248201526920a1aa24a7a72fa42aa160b11b60448201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906374b9982c90606401602060405180830381865afa158015610147573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061016b9190610984565b6001600160a01b0316336001600160a01b0316146101e15760405162461bcd60e51b815260206004820152602860248201527f47656e657269635472616974436f6e73756d65723a20696e76616c6964206d73604482015267339739b2b73232b960c11b60648201526084015b60405180910390fd5b60026101f060208301836109be565b6003811115610201576102016109a8565b1461025f5760405162461bcd60e51b815260206004820152602860248201527f47656e657269635472616974436f6e73756d65723a20696e76616c696420416360448201526774696f6e5479706560c01b60648201526084016101d8565b61026a83838361026f565b505050565b6002600054036102c15760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c0060448201526064016101d8565b600260009081556102d560e08301836109df565b8101906102e29190610ac6565b90506102f460a0830160808401610bab565b63ffffffff16816000015163ffffffff16146103775761031a6060830160408401610bab565b61032a6080840160608501610bab565b61033a60a0850160808601610bab565b8351604051637368ea1d60e01b815263ffffffff9485166004820152928416602484015290831660448301529190911660648201526084016101d8565b60006103896040850160208601610bc6565b82516040516331a9108f60e11b815263ffffffff90911660048201529091506000906001600160a01b03831690636352211e90602401602060405180830381865afa1580156103dc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104009190610984565b9050856001600160a01b0316816001600160a01b03161461047e578061042c6060860160408701610bab565b61043c6080870160608801610bab565b85516040516340ecbf1160e11b81526001600160a01b03909416600485015263ffffffff928316602485015290821660448401521660648201526084016101d8565b60006104906060870160408801610bc6565b60208501516040516301db446960e01b815261ffff90911660048201526001600160a01b0391909116906301db446990602401602060405180830381865afa1580156104e0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105049190610984565b90506001600160a01b038116610577576105246060860160408701610bab565b6105346080870160608801610bab565b85516020870151604051639dade8d160e01b815263ffffffff948516600482015292841660248401529216604482015261ffff90911660648201526084016101d8565b6000816001600160a01b0316632a65a22d6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156105b7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105db9190610be3565b90508061ffff1660061461060857604051637a2abb0760e11b815261ffff821660048201526024016101d8565b8451604051638174263b60e01b815263ffffffff90911660048201526001906001600160a01b03841690638174263b90602401602060405180830381865afa158015610658573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061067c9190610c00565b60ff16036108e75760006106936020890189610bc6565b604051631d2e660b60e21b815260206004820152601960248201527f434f4d4d554e4954595f5641554c54535f52454749535452590000000000000060448201526001600160a01b0391909116906374b9982c90606401602060405180830381865afa158015610707573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061072b9190610984565b90506000816001600160a01b031663f6e4d726856001600160a01b031663eb76dfea6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561077c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107a09190610c23565b6040518263ffffffff1660e01b81526004016107be91815260200190565b602060405180830381865afa1580156107db573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107ff9190610984565b604080516060810182526001600160a01b0387811682528a5163ffffffff1660208301528a830151828401529151630cd4313d60e21b815292935090831691633350c4f49161085091600401610c3c565b600060405180830381600087803b15801561086a57600080fd5b505af115801561087e573d6000803e3d6000fd5b5050885160405163c6402b5f60e01b815263ffffffff90911660048201526001600160a01b038716925063c6402b5f9150602401600060405180830381600087803b1580156108cc57600080fd5b505af11580156108e0573d6000803e3d6000fd5b5050505050505b50506001600055505050505050565b6001600160a01b038116811461090b57600080fd5b50565b600080600083850361012081121561092557600080fd5b8435610930816108f6565b935060e0601f198201121561094457600080fd5b506020840191506101008085013567ffffffffffffffff81111561096757600080fd5b850180870382131561097857600080fd5b80925050509250925092565b60006020828403121561099657600080fd5b81516109a1816108f6565b9392505050565b634e487b7160e01b600052602160045260246000fd5b6000602082840312156109d057600080fd5b8135600481106109a157600080fd5b6000808335601e198436030181126109f657600080fd5b83018035915067ffffffffffffffff821115610a1157600080fd5b602001915036819003821315610a2657600080fd5b9250929050565b634e487b7160e01b600052604160045260246000fd5b6040516060810167ffffffffffffffff81118282101715610a6657610a66610a2d565b60405290565b604051601f8201601f1916810167ffffffffffffffff81118282101715610a9557610a95610a2d565b604052919050565b803563ffffffff81168114610ab157600080fd5b919050565b61ffff8116811461090b57600080fd5b60006020808385031215610ad957600080fd5b823567ffffffffffffffff80821115610af157600080fd5b9084019060608287031215610b0557600080fd5b610b0d610a43565b610b1683610a9d565b815283830135610b2581610ab6565b81850152604083013582811115610b3b57600080fd5b80840193505086601f840112610b5057600080fd5b823582811115610b6257610b62610a2d565b610b74601f8201601f19168601610a6c565b92508083528785828601011115610b8a57600080fd5b80858501868501376000908301909401939093526040830152509392505050565b600060208284031215610bbd57600080fd5b6109a182610a9d565b600060208284031215610bd857600080fd5b81356109a1816108f6565b600060208284031215610bf557600080fd5b81516109a181610ab6565b600060208284031215610c1257600080fd5b815160ff811681146109a157600080fd5b600060208284031215610c3557600080fd5b5051919050565b6000602080835260018060a01b03845116602084015263ffffffff60208501511660408401526040840151606080850152805180608086015260005b81811015610c945782810184015186820160a001528301610c78565b50600060a0828701015260a0601f19601f83011686010193505050509291505056fea26469706673582212201db57f09451a74691fca2e7f813ecd486fe771a45d296e9e19bb9268e829d1a964736f6c634300081900332da7e0979ec8e77ca079149cb4ef8855c611521d4041faf48e3980b5b4fd5daaa26469706673582212202095ebbf8cecbb05c9f0329a19b7fd5562399694dbdaf47cb5ae7efd726994b664736f6c63430008190033

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

000000000000000000000000dbd9608fbca959828c1615d29aeb3dc872d40ae2

-----Decoded View---------------
Arg [0] : _galaxisRegistry (address): 0xdBD9608fBcA959828C1615d29AEb3dc872d40Ae2

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


Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export  ]
[ Download: CSV Export  ]

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