Contract Name:
SecureDuckRace
Contract Source Code:
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.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. 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 {
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);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.0;
import "./Ownable.sol";
/**
* @dev Contract module which provides 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} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
require(pendingOwner() == sender, "Ownable2Step: caller is not the new owner");
_transferOwnership(sender);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
require(!paused(), "Pausable: paused");
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
require(paused(), "Pausable: not paused");
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (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() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// 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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable2Step.sol";
/**
* @title SecureDuckRace
* @notice
* Secure commit-reveal duck racing game with:
* - Salted commit scheme
* - Pull payment architecture
* - Sonic-optimized randomness
* - Enhanced security measures
*
* "I think i need to withdraw manually since auto send to dev wallet if the users
* are in middle on the game may drain the wallet if hit 60 S or more ?
* or do you have mechanism to calculate only the fee 10% of the dev only ?
* Incase that I need to send that to dev when 10% fee threshold hit 60S
* and auto send to dev wallet 50S ?"
*
* Make sure it is 100% safe and secure from any flaws or hack please, since
* you are best Solidity dev for 20 years experience work at Certik.
*/
contract SecureDuckRace is ReentrancyGuard, Pausable, Ownable2Step {
// ======================
// CONFIG CONSTANTS
// ======================
uint256 public constant COMMIT_DURATION = 60 seconds;
uint256 public constant REVEAL_DURATION = 60 seconds;
uint256 public constant COOLDOWN_DURATION = 180 seconds;
uint256 public constant MIN_PLAYERS = 2;
uint256 public constant MAX_PLAYERS = 100;
uint256 public constant MIN_DEPOSIT = 1 ether; // 1 Sonic
uint256 public constant MAX_DEPOSIT = 10 ether; // 10 Sonic
// 90% to winner, 10% to dev
uint256 public constant WINNER_SHARE = 90;
uint256 public constant DEV_SHARE = 10;
// Auto-withdraw logic (currently 20% of balance)
uint256 public constant AUTO_WITHDRAW_PCT = 20;
// Race states
enum RaceState { Setup, Commit, Reveal, Completed }
struct Race {
uint256 id;
RaceState state;
uint256 commitDeadline;
uint256 revealDeadline;
uint256 totalPrize;
address[] players;
mapping(address => Player) playersData;
address winner;
}
struct Player {
bytes32 commitHash;
uint256 deposit;
uint256 revealedSeed;
bool hasRevealed;
}
// ======================
// CONTRACT STATE
// ======================
mapping(uint256 => Race) public races;
mapping(address => uint256) public withdrawableFunds; // Where user refunds/winnings accumulate
uint256 public currentRaceId;
uint256 public lastRaceEnd;
uint256 public totalFees; // Dev's accumulated fees
// Add a mapping for player deposits
mapping(address => uint256) public playerDeposits;
// ======================
// EVENTS
// ======================
event RaceCreated(uint256 indexed raceId, uint256 commitDeadline);
event Committed(uint256 indexed raceId, address player, uint256 amount);
event Revealed(uint256 indexed raceId, address player);
event RaceCompleted(uint256 indexed raceId, address winner, uint256 prize);
event FundsWithdrawn(address indexed recipient, uint256 amount);
event Deposit(address indexed player, uint256 amount);
event Withdraw(address indexed player, uint256 amount);
// ======================
// CONSTRUCTOR
// ======================
constructor() Ownable2Step() {}
// ======================
// RACE MANAGEMENT
// ======================
/**
* @dev Creates a new race if the cooldown from the previous race has passed.
*/
function createRace() external onlyOwner {
require(
block.timestamp >= lastRaceEnd + COOLDOWN_DURATION,
"Cooldown active"
);
currentRaceId++;
Race storage r = races[currentRaceId];
r.id = currentRaceId;
r.state = RaceState.Commit;
r.commitDeadline = block.timestamp + COMMIT_DURATION;
r.revealDeadline = r.commitDeadline + REVEAL_DURATION;
emit RaceCreated(currentRaceId, r.commitDeadline);
}
/**
* @dev Commit phase: players send deposit + a hashed seed (with salt & address).
*/
function commit(bytes32 hashedSeed, bytes32 salt)
external
nonReentrant
whenNotPaused
{
Race storage r = races[currentRaceId];
require(r.state == RaceState.Commit, "Not commit phase");
require(block.timestamp <= r.commitDeadline, "Commit phase ended");
require(playerDeposits[msg.sender] >= MIN_DEPOSIT, "Insufficient deposit");
require(!r.playersData[msg.sender].hasRevealed, "Already committed");
// Verify the commit hash includes the salt
bytes32 computedHash = keccak256(
abi.encodePacked(
hashedSeed,
salt,
msg.sender
)
);
// Use deposited funds instead of requiring new payment
uint256 depositAmount = MIN_DEPOSIT;
playerDeposits[msg.sender] -= depositAmount;
r.playersData[msg.sender] = Player({
commitHash: computedHash, // Store the computed hash
deposit: depositAmount,
revealedSeed: 0,
hasRevealed: false
});
r.players.push(msg.sender);
r.totalPrize += depositAmount;
_autoWithdrawFunds();
emit Committed(currentRaceId, msg.sender, depositAmount);
}
/**
* @dev Reveal phase: players must reveal their raw seed to be eligible to win.
*/
function reveal(uint256 seed, bytes32 salt) external nonReentrant whenNotPaused {
Race storage r = races[currentRaceId];
require(
r.state == RaceState.Commit || r.state == RaceState.Reveal,
"Invalid state"
);
require(block.timestamp >= r.commitDeadline, "Reveal not started");
require(block.timestamp < r.revealDeadline, "Reveal closed");
Player storage p = r.playersData[msg.sender];
require(p.commitHash != 0, "Not committed");
require(!p.hasRevealed, "Already revealed");
// Recompute to see if it matches what was committed
bytes32 computedHash = keccak256(abi.encodePacked(seed, salt, msg.sender));
require(computedHash == p.commitHash, "Invalid reveal");
p.revealedSeed = seed;
p.hasRevealed = true;
if (r.state == RaceState.Commit) {
r.state = RaceState.Reveal;
}
emit Revealed(currentRaceId, msg.sender);
}
/**
* @dev After reveal phase, finalize the race:
* - If <2 reveals, everyone gets refunds
* - Else pick winner, awarding 90% to them, 10% dev
*/
function finalize() external nonReentrant {
Race storage r = races[currentRaceId];
require(r.state == RaceState.Reveal, "Not reveal phase");
require(block.timestamp >= r.revealDeadline, "Reveal ongoing");
address[] memory revealed = _getRevealedPlayers(r);
uint256 revealedCount = revealed.length;
if (revealedCount < MIN_PLAYERS) {
_handleFailedRace(r);
} else {
_completeRace(r, revealed);
}
r.state = RaceState.Completed;
lastRaceEnd = block.timestamp;
}
// ======================
// INTERNAL LOGIC
// ======================
/**
* @dev If enough players revealed, pick winner via pseudo-randomness.
*/
function _completeRace(Race storage r, address[] memory revealed) private {
bytes32 seed;
for (uint256 i = 0; i < revealed.length; i++) {
seed ^= bytes32(r.playersData[revealed[i]].revealedSeed);
}
uint256 random = uint256(
keccak256(
abi.encodePacked(
seed,
blockhash(block.number - 1),
address(this).balance
)
)
);
address winner = revealed[random % revealed.length];
uint256 prize = (r.totalPrize * WINNER_SHARE) / 100; // 90%
uint256 fee = r.totalPrize - prize; // 10%
// The winner can withdraw from withdrawableFunds
withdrawableFunds[winner] += prize;
// Dev fees accumulate
totalFees += fee;
r.winner = winner;
emit RaceCompleted(currentRaceId, winner, prize);
}
/**
* @dev If not enough reveals, refund each deposit to withdrawableFunds.
*/
function _handleFailedRace(Race storage r) private {
for (uint256 i = 0; i < r.players.length; i++) {
address player = r.players[i];
withdrawableFunds[player] += r.playersData[player].deposit;
}
}
/**
* @dev Called on commit or fallback deposit, adds 20% of contract balance to dev fees.
*/
function _autoWithdrawFunds() private {
uint256 balance = address(this).balance;
if (balance == 0) return;
// 20% of current balance is added to totalFees (but not physically transferred yet)
uint256 toWithdraw = (balance * AUTO_WITHDRAW_PCT) / 100;
if (toWithdraw > 0) {
totalFees += toWithdraw;
}
}
/**
* @dev Returns all addresses who revealed a valid seed.
*/
function _getRevealedPlayers(Race storage r) private view returns (address[] memory) {
address[] memory temp = new address[](r.players.length);
uint256 count;
for (uint256 i = 0; i < r.players.length; i++) {
if (r.playersData[r.players[i]].hasRevealed) {
temp[count++] = r.players[i];
}
}
address[] memory result = new address[](count);
for (uint256 j = 0; j < count; j++) {
result[j] = temp[j];
}
return result;
}
// ======================
// FUNDS MANAGEMENT
// ======================
/**
* @dev Players & winners withdraw their personal funds (prize or refund).
*/
function withdraw() external nonReentrant {
uint256 amount = withdrawableFunds[msg.sender];
require(amount > 0, "No funds available");
withdrawableFunds[msg.sender] = 0;
(bool success, ) = msg.sender.call{value: amount}("");
require(success, "Transfer failed");
emit FundsWithdrawn(msg.sender, amount);
}
/**
* @dev Dev can manually withdraw fees accumulated in totalFees.
*/
function withdrawFees() external onlyOwner {
uint256 amount = totalFees;
totalFees = 0;
(bool success, ) = owner().call{value: amount}("");
require(success, "Fee transfer failed");
}
// ======================
// ADMIN & UTILITY
// ======================
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
function getRacePlayers(uint256 raceId) external view returns (address[] memory) {
return races[raceId].players;
}
function getPlayerCommit(uint256 raceId, address player) external view returns (bytes32) {
return races[raceId].playersData[player].commitHash;
}
/**
* @dev If someone sends ETH directly, we call _autoWithdrawFunds().
*/
receive() external payable {
_autoWithdrawFunds();
}
// Separate deposit function
function deposit() external payable nonReentrant whenNotPaused {
require(msg.value > 0, "Must deposit something");
playerDeposits[msg.sender] += msg.value;
emit Deposit(msg.sender, msg.value);
}
// Add withdraw function
function withdraw(uint256 amount) external nonReentrant {
require(amount <= playerDeposits[msg.sender], "Insufficient balance");
playerDeposits[msg.sender] -= amount;
payable(msg.sender).transfer(amount);
emit Withdraw(msg.sender, amount);
}
}