creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "@openzeppelin/contracts/access/Ownable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\n\npragma solidity ^0.8.20;\n\nimport {Context} from \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * The initial owner is set to the address provided by the deployer. This can\n * later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n    address private _owner;\n\n    /**\n     * @dev The caller account is not authorized to perform an operation.\n     */\n    error OwnableUnauthorizedAccount(address account);\n\n    /**\n     * @dev The owner is not a valid owner account. (eg. `address(0)`)\n     */\n    error OwnableInvalidOwner(address owner);\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\n     */\n    constructor(address initialOwner) {\n        if (initialOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\n        _transferOwnership(initialOwner);\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        _checkOwner();\n        _;\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if the sender is not the owner.\n     */\n    function _checkOwner() internal view virtual {\n        if (owner() != _msgSender()) {\n            revert OwnableUnauthorizedAccount(_msgSender());\n        }\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby disabling any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        _transferOwnership(address(0));\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        if (newOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual {\n        address oldOwner = _owner;\n        _owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n}\n"
      },
      "@openzeppelin/contracts/token/ERC20/IERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the value of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the value of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves a `value` amount of tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 value) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n     * caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the\n     * allowance mechanism. `value` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address from, address to, uint256 value) external returns (bool);\n}\n"
      },
      "@openzeppelin/contracts/utils/Context.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n\n    function _contextSuffixLength() internal view virtual returns (uint256) {\n        return 0;\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/ReentrancyGuard.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot's contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler's defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction's gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant NOT_ENTERED = 1;\n    uint256 private constant ENTERED = 2;\n\n    uint256 private _status;\n\n    /**\n     * @dev Unauthorized reentrant call.\n     */\n    error ReentrancyGuardReentrantCall();\n\n    constructor() {\n        _status = NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and making it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        _nonReentrantBefore();\n        _;\n        _nonReentrantAfter();\n    }\n\n    function _nonReentrantBefore() private {\n        // On the first call to nonReentrant, _status will be NOT_ENTERED\n        if (_status == ENTERED) {\n            revert ReentrancyGuardReentrantCall();\n        }\n\n        // Any calls to nonReentrant after this point will fail\n        _status = ENTERED;\n    }\n\n    function _nonReentrantAfter() private {\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        _status = NOT_ENTERED;\n    }\n\n    /**\n     * @dev Returns true if the reentrancy guard is currently set to \"entered\", which indicates there is a\n     * `nonReentrant` function in the call stack.\n     */\n    function _reentrancyGuardEntered() internal view returns (bool) {\n        return _status == ENTERED;\n    }\n}\n"
      },
      "contracts/MetacadeTournament.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.23;\n\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"@openzeppelin/contracts/utils/ReentrancyGuard.sol\";\n\ninterface IERC20Extended is IERC20 {\n    function decimals() external view returns (uint8);\n}\n\ncontract MetacadeTournament is Ownable(msg.sender), ReentrancyGuard {\n    address public updater;\n    uint256 private constant CBR_SCALE_FACTOR = 10 ** 6;\n\n    constructor(address _updater) {\n        updater = _updater;\n    }\n\n    struct Tournament {\n        IERC20 paymentToken;\n        bool isActive;\n        uint256 gameId;\n        uint256 startedAtBlock;\n        uint256 creditBurnRate;\n        uint256 baseCreditCost;\n        Shareholder[] shareholders;\n        CreditPackageType creditPackages;\n    }\n\n    mapping(uint256 => Tournament) public tournaments;\n    mapping(address => mapping(uint256 => uint256))\n        public claimablePrizesForTournament;\n    mapping(uint256 => uint256) public prizePools;\n    mapping(uint256 => WinnerInfo[]) public tournamentWinners;\n\n    struct WinnerInfo {\n        address winner;\n        uint256 amount;\n    }\n    struct Shareholder {\n        address wallet;\n        uint256 share;\n    }\n    struct CreditPackageType {\n        uint256 tier1;\n        uint256 tier2;\n        uint256 tier3;\n    }\n\n    event TournamentCreated(\n        uint256 indexed tournamentId,\n        address paymentToken,\n        uint256 creditBurnRate,\n        uint256 baseCreditCost,\n        uint256 gameId\n    );\n    event PrizePoolFunded(\n        uint256 indexed tournamentId,\n        address funder,\n        uint256 amount\n    );\n    event TournamentStarted(uint256 indexed tournamentId, uint256 timestamp);\n    event TournamentEnded(uint256 indexed tournamentId, uint256 timestamp);\n    event CreditPurchased(\n        uint256 indexed tournamentId,\n        uint256 gameId,\n        address buyer,\n        address paymentToken,\n        uint256 amount\n    );\n    event Claimed(\n        uint256 indexed tournamentId,\n        address claimer,\n        uint256 amount,\n        address paymentToken\n    );\n    event WinnersUpdated(uint256 indexed tournamentId);\n\n    modifier onlyUpdater() {\n        require(msg.sender == updater, \"Not authorized\");\n        _;\n    }\n\n    function updateUpdater(address _updater) external onlyOwner {\n        updater = _updater;\n    }\n\n    function getTournamentWinners(\n        uint256 tournamentId\n    ) external view returns (WinnerInfo[] memory) {\n        return tournamentWinners[tournamentId];\n    }\n\n    function getTournamentShareholder(\n        uint256 tournamentId,\n        uint256 shareholderIndex\n    ) external view returns (address, uint256) {\n        Shareholder memory shareholder = tournaments[tournamentId].shareholders[\n            shareholderIndex\n        ];\n        return (shareholder.wallet, shareholder.share);\n    }\n\n    function getTournamentCreditPackageType(\n        uint256 tournamentId\n    ) external view returns (CreditPackageType memory) {\n        CreditPackageType memory creditPackages = tournaments[tournamentId]\n            .creditPackages;\n        return creditPackages;\n    }\n\n    function createTournament(\n        uint256 tournamentId,\n        uint256 gameId,\n        uint256 creditBurnRate,\n        uint256 baseCreditCost,\n        address paymentTokenAddress,\n        Shareholder[] memory _shareholders,\n        CreditPackageType memory _creditPackages\n    ) external onlyOwner {\n        require(\n            tournaments[tournamentId].paymentToken == IERC20(address(0)),\n            \"Tournament already exists\"\n        );\n        require(\n            creditBurnRate >= 0,\n            \"Credit Burn Rate should be greater than or equal to 0\"\n        );\n        require(\n            baseCreditCost >= 0,\n            \"Base Credit Cost should be greater than or equal to 0\"\n        );\n        require(\n            gameId > 0,\n            \"Tournament must be associated with a certain game identifier\"\n        );\n\n        uint256 totalShare = 0;\n        for (uint256 i = 0; i < _shareholders.length; i++) {\n            require(_shareholders[i].share > 0, \"Share must be greater than 0\");\n            totalShare += _shareholders[i].share;\n        }\n        require(totalShare == 100, \"Total share must be exactly 100\");\n\n        Shareholder[] storage allShareholders = tournaments[tournamentId]\n            .shareholders;\n        for (uint256 i = 0; i < _shareholders.length; i++) {\n            allShareholders.push(_shareholders[i]);\n        }\n        uint256 scaledCBR = creditBurnRate * CBR_SCALE_FACTOR;\n\n        IERC20 paymentToken = IERC20(paymentTokenAddress);\n        Tournament storage tournament = tournaments[tournamentId];\n        tournament.paymentToken = paymentToken;\n        tournament.baseCreditCost = baseCreditCost;\n        tournament.gameId = gameId;\n        tournament.isActive = false;\n        tournament.creditBurnRate = scaledCBR;\n        tournament.startedAtBlock = 0;\n        tournament.creditPackages = _creditPackages;\n\n        emit TournamentCreated(\n            tournamentId,\n            paymentTokenAddress,\n            creditBurnRate,\n            baseCreditCost,\n            gameId\n        );\n    }\n\n    function startTournament(uint256 tournamentId) external onlyOwner {\n        Tournament storage tournament = tournaments[tournamentId];\n        require(!tournament.isActive, \"Tournament already active\");\n        require(tournament.gameId > 0, \"Tournament does not exist\");\n\n        tournament.isActive = true;\n        tournament.startedAtBlock = block.number;\n\n        emit TournamentStarted(tournamentId, block.timestamp);\n    }\n\n    function fundPrizePool(\n        uint256 tournamentId,\n        uint256 tokenAmount\n    ) external payable {\n        Tournament storage tournament = tournaments[tournamentId];\n        require(tournament.isActive, \"Tournament is not active.\");\n\n        uint256 fundedAmount;\n\n        if (tournament.paymentToken == IERC20(address(0))) {\n            require(msg.value > 0, \"Ether amount must be greater than 0\");\n            prizePools[tournamentId] += msg.value;\n            fundedAmount = msg.value;\n        } else {\n            require(tokenAmount > 0, \"Token amount must be greater than 0\");\n            require(msg.value == 0, \"Do not send Ether for ERC20 funding\");\n            require(\n                tournament.paymentToken.transferFrom(\n                    msg.sender,\n                    address(this),\n                    tokenAmount\n                ),\n                \"Token transfer to contract failed\"\n            );\n            prizePools[tournamentId] += tokenAmount;\n            fundedAmount = tokenAmount;\n        }\n\n        emit PrizePoolFunded(tournamentId, msg.sender, fundedAmount);\n    }\n\n    function swapForCredits(\n        uint256 tournamentId,\n        uint256 gameId,\n        uint256 creditTier,\n        address beneficiary\n    ) external payable nonReentrant {\n        require(beneficiary != address(0), \"Invalid beneficiary address\");\n        Tournament storage tournament = tournaments[tournamentId];\n        require(tournament.isActive, \"Tournament is paused\");\n        require(gameId == tournament.gameId, \"Invalid game id\");\n\n        uint256 tokenAmount;\n        if (creditTier == 1) {\n            tokenAmount = tournament.creditPackages.tier1;\n        } else if (creditTier == 2) {\n            tokenAmount = tournament.creditPackages.tier2;\n        } else if (creditTier == 3) {\n            tokenAmount = tournament.creditPackages.tier3;\n        } else {\n            revert(\"Invalid credit tier\");\n        }\n\n        if (tournament.paymentToken == IERC20(address(0))) {\n            require(msg.value == tokenAmount, \"Incorrect Ether amount\");\n        } else {\n            require(msg.value == 0, \"This tournament does not accept Ether\");\n            require(\n                tournament.paymentToken.transferFrom(\n                    msg.sender,\n                    address(this),\n                    tokenAmount\n                ),\n                \"ERC20 token transfer failed\"\n            );\n        }\n\n        distributeTokens(tournamentId, tokenAmount);\n\n        emit CreditPurchased(\n            tournamentId,\n            gameId,\n            beneficiary,\n            address(tournament.paymentToken),\n            tokenAmount\n        );\n    }\n\n    function distributeTokens(\n        uint256 tournamentId,\n        uint256 tokenAmount\n    ) internal {\n        Tournament storage tournament = tournaments[tournamentId];\n\n        for (uint256 i = 0; i < tournament.shareholders.length; i++) {\n            Shareholder memory shareholder = tournament.shareholders[i];\n            uint256 shareholderAmount = (tokenAmount * shareholder.share) / 100;\n\n            if (tournament.paymentToken == IERC20(address(0))) {\n                if (shareholder.wallet == address(this)) {\n                    prizePools[tournamentId] += shareholderAmount;\n                } else {\n                    (bool sent, ) = shareholder.wallet.call{\n                        value: shareholderAmount\n                    }(\"\");\n                    require(sent, \"Failed to send Ether\");\n                }\n            } else {\n                if (shareholder.wallet == address(this)) {\n                    require(\n                        tournament.paymentToken.transfer(\n                            address(this),\n                            shareholderAmount\n                        ),\n                        \"Token transfer to contract failed\"\n                    );\n                    prizePools[tournamentId] += shareholderAmount;\n                } else {\n                    require(\n                        tournament.paymentToken.transfer(\n                            shareholder.wallet,\n                            shareholderAmount\n                        ),\n                        \"Token transfer to shareholder failed\"\n                    );\n                }\n            }\n        }\n    }\n\n    function updateWinners(\n        uint256 tournamentId,\n        address[] calldata winnerAddresses,\n        uint256[] calldata amountsInWei\n    ) external onlyUpdater {\n        require(\n            winnerAddresses.length == amountsInWei.length,\n            \"Address and amount arrays must match\"\n        );\n\n        Tournament storage tournament = tournaments[tournamentId];\n        require(!tournament.isActive, \"Tournament must be ended first\");\n\n        delete tournamentWinners[tournamentId];\n        uint256 totalAmount = 0;\n        for (uint256 i = 0; i < winnerAddresses.length; i++) {\n            tournamentWinners[tournamentId].push(\n                WinnerInfo({\n                    winner: winnerAddresses[i],\n                    amount: amountsInWei[i]\n                })\n            );\n            claimablePrizesForTournament[winnerAddresses[i]][\n                tournamentId\n            ] += amountsInWei[i];\n            totalAmount += amountsInWei[i];\n        }\n\n        // Ensure the total amount being claimed does not exceed the prize pool\n        require(\n            totalAmount <= prizePools[tournamentId],\n            \"Total amount exceeds prize pool\"\n        );\n\n        emit WinnersUpdated(tournamentId);\n    }\n\n    function endTournament(uint256 tournamentId) external onlyOwner {\n        Tournament storage tournament = tournaments[tournamentId];\n        require(tournament.isActive, \"Tournament has not started\");\n\n        tournament.isActive = false;\n        emit TournamentEnded(tournamentId, block.timestamp);\n    }\n\n    function withdrawToken(\n        address tokenAddress,\n        uint256 amount\n    ) external onlyOwner {\n        require(amount > 0, \"Amount must be greater than 0\");\n\n        if (tokenAddress == address(0)) {\n            require(\n                address(this).balance >= amount,\n                \"Insufficient Ether balance\"\n            );\n            (bool sent, ) = msg.sender.call{value: amount}(\"\");\n            require(sent, \"Failed to send Ether\");\n        } else {\n            // Withdrawal request for an ERC20 token\n            IERC20 token = IERC20(tokenAddress);\n            uint256 contractBalance = token.balanceOf(address(this));\n            require(contractBalance >= amount, \"Insufficient token balance\");\n            require(\n                token.transfer(msg.sender, amount),\n                \"Token transfer failed\"\n            );\n        }\n    }\n\n    function claim(uint256 tournamentId) external nonReentrant {\n        uint256 claimAmount = claimablePrizesForTournament[msg.sender][\n            tournamentId\n        ];\n\n        require(claimAmount > 0, \"No claimable amount\");\n        claimablePrizesForTournament[msg.sender][tournamentId] = 0;\n        Tournament storage tournament = tournaments[tournamentId];\n\n        if (address(tournament.paymentToken) == address(0)) {\n            (bool sent, ) = msg.sender.call{value: claimAmount}(\"\");\n            require(sent, \"Failed to send Ether\");\n        } else {\n            require(\n                tournament.paymentToken.transfer(msg.sender, claimAmount),\n                \"Token transfer failed\"\n            );\n        }\n\n        emit Claimed(\n            tournamentId,\n            msg.sender,\n            claimAmount,\n            address(tournament.paymentToken)\n        );\n    }\n}\n"
      }
    },
    "settings": {
      "optimizer": {
        "enabled": true,
        "runs": 200
      },
      "evmVersion": "london",
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "libraries": {}
    }
  }}