Contract Source Code:
File 1 of 1 : Winpad
// File: @openzeppelin/contracts/utils/ReentrancyGuard.sol
// ___ ___ ___ ___ _____
// /__/\ ___ /__/\ / /\ / /\ / /::\
// _\_ \:\ / /\ \ \:\ / /::\ / /::\ / /:/\:\
// /__/\ \:\ / /:/ \ \:\ / /:/\:\ / /:/\:\ / /:/ \:\
// _\_ \:\ \:\ /__/::\ _____\__\:\ / /:/~/:/ / /:/~/::\ /__/:/ \__\:|
// /__/\ \:\ \:\ \__\/\:\__ /__/::::::::\ /__/:/ /:/ /__/:/ /:/\:\ \ \:\ / /:/
// \ \:\ \:\/:/ \ \:\/\ \ \:\~~\~~\/ \ \:\/:/ \ \:\/:/__\/ \ \:\ /:/
// \ \:\ \::/ \__\::/ \ \:\ ~~~ \ \::/ \ \::/ \ \:\/:/
// \ \:\/:/ /__/:/ \ \:\ \ \:\ \ \:\ \ \::/
// \ \::/ \__\/ \ \:\ \ \:\ \ \:\ \__\/
// \__\/ \__\/ \__\/ \__\/
// Official Contract of Winpad.
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @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 EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* 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;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
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() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
/**
* @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.
*
* The initial owner is set to the address provided by the deployer. 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;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @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 {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_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: @openzeppelin/contracts/utils/math/SafeMath.sol
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: contracts/Winpad.sol
pragma solidity ^0.8.26;
interface INft {
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
function balanceOf(address owner) external view returns (uint256);
function ownerOf(uint256 tokenId) external view returns (address);
}
contract Winpad is Ownable, ReentrancyGuard {
using SafeMath for uint256;
// Revenue distribution percentages
uint8 public constant FEE_PERCENT = 8;
uint8 public constant TREASURY_PERCENT = 72;
uint8 public constant OPERATIONS_PERCENT = 20;
// Revenue distribution addresses
address payable public feeAccount;
address payable public treasuryAccount;
address payable public operationsAccount;
// Entry tier structure
struct EntryTier {
uint256 apeCost;
uint256 baseEntries;
uint256 bonusEntries;
bool exists;
}
// Match structure
struct Match {
bytes32 id;
uint256[] allowedTiers;
address nftAddress;
uint256 nftId;
uint256 totalEntries;
uint256 endDate;
address winner;
bool isEnded;
bool exists;
}
// Participant tracking
struct Participation {
address participant;
uint256 tierId; // Add back tierId
uint256 entries;
}
// Storage
mapping(uint256 => EntryTier) public tiers;
uint256 public nextTierId = 1;
mapping(bytes32 => Match) public matches;
mapping(bytes32 => mapping(address => bool)) public hasUsedFreeEntry;
mapping(bytes32 => Participation[]) public participations;
bytes32[] public allMatchIds;
mapping(address => bool) public authorizedCallers;
// Free entry for those NFTs.
address[] public entryNFTs;
// Events
event MatchCreated(
bytes32 indexed matchId,
address nftAddress,
uint256 nftId,
uint256 endDate
);
event ParticipantEnrolled(
bytes32 indexed matchId,
address participant,
uint256 entries
);
event MatchCanceled(bytes32 indexed matchId, uint256 totalRefunded);
event MatchExtended(bytes32 indexed matchId, uint256 endDate);
event WinnerSelected(
bytes32 indexed matchId,
address winner,
uint256 entries
);
event FundsDistributed(
bytes32 indexed matchId,
uint256 totalAmount,
uint256 fee,
uint256 treasury,
uint256 operations
);
event TierUpdated(
uint256 indexed tierId,
uint256 apeCost,
uint256 baseEntries,
uint256 bonusEntries
);
event CallerUpdated(address indexed caller, bool status);
modifier onlyCaller() {
require(
owner() == msg.sender || authorizedCallers[msg.sender],
"Unauthorized"
);
_;
}
constructor(
address _initialOwner,
address payable _feeAccount,
address payable _treasuryAccount,
address payable _operationsAccount
) Ownable(_initialOwner) {
feeAccount = _feeAccount;
treasuryAccount = _treasuryAccount;
operationsAccount = _operationsAccount;
}
// Entry NFTs management
function addEntryNFT(address nft) external onlyOwner {
entryNFTs.push(nft);
}
function removeEntryNFT(uint256 index) external onlyOwner {
require(index < entryNFTs.length, "Index out of bounds");
entryNFTs[index] = entryNFTs[entryNFTs.length - 1];
entryNFTs.pop();
}
// Tier management
function addTier(
uint256 apeCost,
uint256 baseEntries,
uint256 bonusEntries
) external onlyOwner {
tiers[nextTierId] = EntryTier(apeCost, baseEntries, bonusEntries, true);
emit TierUpdated(nextTierId, apeCost, baseEntries, bonusEntries);
nextTierId++;
}
// Match creation
function createMatch(
uint256[] memory allowedTiers,
address nftAddress,
uint256 nftId,
uint256 duration
) external onlyOwner returns (bytes32 matchId) {
require(duration > 0, "Invalid duration");
require(
INft(nftAddress).ownerOf(nftId) == address(this),
"NFT not owned"
);
matchId = keccak256(
abi.encodePacked(block.timestamp, nftAddress, nftId, msg.sender)
);
matches[matchId] = Match({
id: matchId,
allowedTiers: allowedTiers,
nftAddress: nftAddress,
nftId: nftId,
totalEntries: 0,
endDate: block.timestamp + duration,
winner: address(0),
isEnded: false,
exists: true
});
allMatchIds.push(matchId);
emit MatchCreated(
matchId,
nftAddress,
nftId,
block.timestamp + duration
);
}
// Participant enrollment
function enroll(bytes32 matchId, uint256 tierId)
external
payable
nonReentrant
{
Match storage m = matches[matchId];
EntryTier memory tier = tiers[tierId];
require(m.exists, "Invalid match");
require(!m.isEnded, "Match ended");
require(block.timestamp < m.endDate, "Enrollment closed");
require(tier.exists, "Invalid tier");
require(contains(m.allowedTiers, tierId), "Tier not allowed");
require(msg.value == tier.apeCost, "Incorrect APE amount");
if (tier.apeCost == 0) {
require(
!hasUsedFreeEntry[matchId][msg.sender],
"Free entry already used"
);
bool hasEntryNFT = false;
for (uint256 i = 0; i < entryNFTs.length; i++) {
if (INft(entryNFTs[i]).balanceOf(msg.sender) > 0) {
hasEntryNFT = true;
break;
}
}
require(hasEntryNFT, "No qualifying NFT found");
hasUsedFreeEntry[matchId][msg.sender] = true;
}
uint256 totalEntries = tier.baseEntries + tier.bonusEntries;
participations[matchId].push(
Participation(msg.sender, tierId, totalEntries)
);
m.totalEntries += totalEntries;
emit ParticipantEnrolled(matchId, msg.sender, totalEntries);
}
// Match resolution
function pickWinner(bytes32 matchId, uint256 randomSeed)
external
onlyCaller
nonReentrant
{
Match storage m = matches[matchId];
require(!m.isEnded, "Match already ended");
uint256 randomNumber = uint256(
keccak256(abi.encodePacked(randomSeed, block.timestamp))
) % m.totalEntries;
uint256 cumulative;
address winner;
uint256 winnerEntries;
Participation[] memory parts = participations[matchId];
for (uint256 i = 0; i < parts.length; i++) {
Participation memory p = parts[i];
if (randomNumber < cumulative + p.entries) {
winner = p.participant;
winnerEntries = p.entries;
break;
}
cumulative += p.entries;
}
uint256 totalPrizePool = address(this).balance;
uint256 feeAmount = totalPrizePool.mul(FEE_PERCENT).div(100);
uint256 treasuryAmount = totalPrizePool.mul(TREASURY_PERCENT).div(100);
uint256 operationsAmount = totalPrizePool.sub(feeAmount).sub(
treasuryAmount
);
feeAccount.transfer(feeAmount);
treasuryAccount.transfer(treasuryAmount);
operationsAccount.transfer(operationsAmount);
require(
INft(m.nftAddress).ownerOf(m.nftId) == address(this),
"Contract does not own NFT"
);
INft(m.nftAddress).transferFrom(address(this), winner, m.nftId);
m.winner = winner;
m.isEnded = true;
emit FundsDistributed(
matchId,
totalPrizePool,
feeAmount,
treasuryAmount,
operationsAmount
);
emit WinnerSelected(matchId, winner, winnerEntries);
}
// Fix the cancellation logic
function cancelMatch(bytes32 matchId) external onlyCaller nonReentrant {
Match storage m = matches[matchId];
require(!m.isEnded, "Match already ended");
uint256 totalRefunded;
for (uint256 i = 0; i < participations[matchId].length; i++) {
Participation memory p = participations[matchId][i];
EntryTier memory tier = tiers[p.tierId]; // Now works
payable(p.participant).transfer(tier.apeCost);
totalRefunded += tier.apeCost;
}
INft(m.nftAddress).transferFrom(address(this), owner(), m.nftId);
m.isEnded = true;
emit MatchCanceled(matchId, totalRefunded);
}
// Extending match duration
function extendMatchEndDate(bytes32 matchId, uint256 additionalDuration)
external
onlyCaller
{
Match storage m = matches[matchId];
require(!m.isEnded, "Match already ended");
require(additionalDuration > 0, "Invalid duration");
m.endDate += additionalDuration;
emit MatchExtended(matchId, m.endDate);
}
// View functions
function getEntryTypes() public view returns (EntryTier[] memory) {
EntryTier[] memory types = new EntryTier[](nextTierId - 1);
for (uint256 i = 1; i < nextTierId; i++) {
types[i - 1] = tiers[i];
}
return types;
}
function getOngoingMatches() public view returns (Match[] memory) {
return _filterMatches(0);
}
function getMatchHistory() public view returns (Match[] memory) {
return _filterMatches(1);
}
function getReadyMatches() public view returns (Match[] memory) {
return _filterMatches(2);
}
function getAllEntryNFTs() public view returns (address[] memory) {
return entryNFTs;
}
function getParticipations(bytes32 matchId)
public
view
returns (Participation[] memory)
{
return participations[matchId];
}
// Internal helpers
function _filterMatches(uint8 filterType)
private
view
returns (Match[] memory)
{
Match[] memory result = new Match[](allMatchIds.length);
uint256 count = 0;
for (uint256 i = 0; i < allMatchIds.length; i++) {
bytes32 id = allMatchIds[i];
Match storage m = matches[id];
bool include;
if (filterType == 0) {
// Ongoing
include = !m.isEnded && block.timestamp < m.endDate;
} else if (filterType == 1) {
// History
include = m.isEnded;
} else if (filterType == 2) {
// Ready
include = !m.isEnded && (block.timestamp >= m.endDate);
}
if (include) {
result[count] = m;
count++;
}
}
Match[] memory trimmed = new Match[](count);
for (uint256 i = 0; i < count; i++) {
trimmed[i] = result[i];
}
return trimmed;
}
function contains(uint256[] memory arr, uint256 value)
private
pure
returns (bool)
{
for (uint256 i = 0; i < arr.length; i++) {
if (arr[i] == value) return true;
}
return false;
}
// Authorization management
function updateCaller(address caller, bool status) external onlyOwner {
authorizedCallers[caller] = status;
emit CallerUpdated(caller, status);
}
receive() external payable {}
}