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) (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: Apache-2.0
pragma solidity ^0.8.0;
import "./EntropyStructs.sol";
interface EntropyEvents {
event Registered(EntropyStructs.ProviderInfo provider);
event Requested(EntropyStructs.Request request);
event RequestedWithCallback(
address indexed provider,
address indexed requestor,
uint64 indexed sequenceNumber,
bytes32 userRandomNumber,
EntropyStructs.Request request
);
event Revealed(
EntropyStructs.Request request,
bytes32 userRevelation,
bytes32 providerRevelation,
bytes32 blockHash,
bytes32 randomNumber
);
event RevealedWithCallback(
EntropyStructs.Request request,
bytes32 userRandomNumber,
bytes32 providerRevelation,
bytes32 randomNumber
);
event ProviderFeeUpdated(address provider, uint128 oldFee, uint128 newFee);
event ProviderUriUpdated(address provider, bytes oldUri, bytes newUri);
event ProviderFeeManagerUpdated(
address provider,
address oldFeeManager,
address newFeeManager
);
event Withdrawal(
address provider,
address recipient,
uint128 withdrawnAmount
);
}
// SPDX-License-Identifier: Apache 2
pragma solidity ^0.8.0;
contract EntropyStructs {
struct ProviderInfo {
uint128 feeInWei;
uint128 accruedFeesInWei;
// The commitment that the provider posted to the blockchain, and the sequence number
// where they committed to this. This value is not advanced after the provider commits,
// and instead is stored to help providers track where they are in the hash chain.
bytes32 originalCommitment;
uint64 originalCommitmentSequenceNumber;
// Metadata for the current commitment. Providers may optionally use this field to help
// manage rotations (i.e., to pick the sequence number from the correct hash chain).
bytes commitmentMetadata;
// Optional URI where clients can retrieve revelations for the provider.
// Client SDKs can use this field to automatically determine how to retrieve random values for each provider.
// TODO: specify the API that must be implemented at this URI
bytes uri;
// The first sequence number that is *not* included in the current commitment (i.e., an exclusive end index).
// The contract maintains the invariant that sequenceNumber <= endSequenceNumber.
// If sequenceNumber == endSequenceNumber, the provider must rotate their commitment to add additional random values.
uint64 endSequenceNumber;
// The sequence number that will be assigned to the next inbound user request.
uint64 sequenceNumber;
// The current commitment represents an index/value in the provider's hash chain.
// These values are used to verify requests for future sequence numbers. Note that
// currentCommitmentSequenceNumber < sequenceNumber.
//
// The currentCommitment advances forward through the provider's hash chain as values
// are revealed on-chain.
bytes32 currentCommitment;
uint64 currentCommitmentSequenceNumber;
// An address that is authorized to set / withdraw fees on behalf of this provider.
address feeManager;
}
struct Request {
// Storage slot 1 //
address provider;
uint64 sequenceNumber;
// The number of hashes required to verify the provider revelation.
uint32 numHashes;
// Storage slot 2 //
// The commitment is keccak256(userCommitment, providerCommitment). Storing the hash instead of both saves 20k gas by
// eliminating 1 store.
bytes32 commitment;
// Storage slot 3 //
// The number of the block where this request was created.
// Note that we're using a uint64 such that we have an additional space for an address and other fields in
// this storage slot. Although block.number returns a uint256, 64 bits should be plenty to index all of the
// blocks ever generated.
uint64 blockNumber;
// The address that requested this random number.
address requester;
// If true, incorporate the blockhash of blockNumber into the generated random value.
bool useBlockhash;
// If true, the requester will be called back with the generated random value.
bool isRequestWithCallback;
// There are 2 remaining bytes of free space in this slot.
}
}
// SPDX-License-Identifier: Apache 2
pragma solidity ^0.8.0;
import "./EntropyEvents.sol";
interface IEntropy is EntropyEvents {
// Register msg.sender as a randomness provider. The arguments are the provider's configuration parameters
// and initial commitment. Re-registering the same provider rotates the provider's commitment (and updates
// the feeInWei).
//
// chainLength is the number of values in the hash chain *including* the commitment, that is, chainLength >= 1.
function register(
uint128 feeInWei,
bytes32 commitment,
bytes calldata commitmentMetadata,
uint64 chainLength,
bytes calldata uri
) external;
// Withdraw a portion of the accumulated fees for the provider msg.sender.
// Calling this function will transfer `amount` wei to the caller (provided that they have accrued a sufficient
// balance of fees in the contract).
function withdraw(uint128 amount) external;
// Withdraw a portion of the accumulated fees for provider. The msg.sender must be the fee manager for this provider.
// Calling this function will transfer `amount` wei to the caller (provided that they have accrued a sufficient
// balance of fees in the contract).
function withdrawAsFeeManager(address provider, uint128 amount) external;
// As a user, request a random number from `provider`. Prior to calling this method, the user should
// generate a random number x and keep it secret. The user should then compute hash(x) and pass that
// as the userCommitment argument. (You may call the constructUserCommitment method to compute the hash.)
//
// This method returns a sequence number. The user should pass this sequence number to
// their chosen provider (the exact method for doing so will depend on the provider) to retrieve the provider's
// number. The user should then call fulfillRequest to construct the final random number.
//
// This method will revert unless the caller provides a sufficient fee (at least getFee(provider)) as msg.value.
// Note that excess value is *not* refunded to the caller.
function request(
address provider,
bytes32 userCommitment,
bool useBlockHash
) external payable returns (uint64 assignedSequenceNumber);
// Request a random number. The method expects the provider address and a secret random number
// in the arguments. It returns a sequence number.
//
// The address calling this function should be a contract that inherits from the IEntropyConsumer interface.
// The `entropyCallback` method on that interface will receive a callback with the generated random number.
//
// This method will revert unless the caller provides a sufficient fee (at least getFee(provider)) as msg.value.
// Note that excess value is *not* refunded to the caller.
function requestWithCallback(
address provider,
bytes32 userRandomNumber
) external payable returns (uint64 assignedSequenceNumber);
// Fulfill a request for a random number. This method validates the provided userRandomness and provider's proof
// against the corresponding commitments in the in-flight request. If both values are validated, this function returns
// the corresponding random number.
//
// Note that this function can only be called once per in-flight request. Calling this function deletes the stored
// request information (so that the contract doesn't use a linear amount of storage in the number of requests).
// If you need to use the returned random number more than once, you are responsible for storing it.
function reveal(
address provider,
uint64 sequenceNumber,
bytes32 userRevelation,
bytes32 providerRevelation
) external returns (bytes32 randomNumber);
// Fulfill a request for a random number. This method validates the provided userRandomness
// and provider's revelation against the corresponding commitment in the in-flight request. If both values are validated
// and the requestor address is a contract address, this function calls the requester's entropyCallback method with the
// sequence number, provider address and the random number as arguments. Else if the requestor is an EOA, it won't call it.
//
// Note that this function can only be called once per in-flight request. Calling this function deletes the stored
// request information (so that the contract doesn't use a linear amount of storage in the number of requests).
// If you need to use the returned random number more than once, you are responsible for storing it.
//
// Anyone can call this method to fulfill a request, but the callback will only be made to the original requester.
function revealWithCallback(
address provider,
uint64 sequenceNumber,
bytes32 userRandomNumber,
bytes32 providerRevelation
) external;
function getProviderInfo(
address provider
) external view returns (EntropyStructs.ProviderInfo memory info);
function getDefaultProvider() external view returns (address provider);
function getRequest(
address provider,
uint64 sequenceNumber
) external view returns (EntropyStructs.Request memory req);
function getFee(address provider) external view returns (uint128 feeAmount);
function getAccruedPythFees()
external
view
returns (uint128 accruedPythFeesInWei);
function setProviderFee(uint128 newFeeInWei) external;
function setProviderFeeAsFeeManager(
address provider,
uint128 newFeeInWei
) external;
function setProviderUri(bytes calldata newUri) external;
// Set manager as the fee manager for the provider msg.sender.
// After calling this function, manager will be able to set the provider's fees and withdraw them.
// Only one address can be the fee manager for a provider at a time -- calling this function again with a new value
// will override the previous value. Call this function with the all-zero address to disable the fee manager role.
function setFeeManager(address manager) external;
function constructUserCommitment(
bytes32 userRandomness
) external pure returns (bytes32 userCommitment);
function combineRandomValues(
bytes32 userRandomness,
bytes32 providerRandomness,
bytes32 blockHash
) external pure returns (bytes32 combinedRandomness);
}
// SPDX-License-Identifier: Apache 2
pragma solidity ^0.8.0;
abstract contract IEntropyConsumer {
// This method is called by Entropy to provide the random number to the consumer.
// It asserts that the msg.sender is the Entropy contract. It is not meant to be
// override by the consumer.
function _entropyCallback(
uint64 sequence,
address provider,
bytes32 randomNumber
) external {
address entropy = getEntropy();
require(entropy != address(0), "Entropy address not set");
require(msg.sender == entropy, "Only Entropy can call this function");
entropyCallback(sequence, provider, randomNumber);
}
// getEntropy returns Entropy contract address. The method is being used to check that the
// callback is indeed from Entropy contract. The consumer is expected to implement this method.
// Entropy address can be found here - https://docs.pyth.network/entropy/contract-addresses
function getEntropy() internal view virtual returns (address);
// This method is expected to be implemented by the consumer to handle the random number.
// It will be called by _entropyCallback after _entropyCallback ensures that the call is
// indeed from Entropy contract.
function entropyCallback(
uint64 sequence,
address provider,
bytes32 randomNumber
) internal virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@pythnetwork/entropy-sdk-solidity/IEntropy.sol";
import "@pythnetwork/entropy-sdk-solidity/IEntropyConsumer.sol";
error AstroSpin__NotEnoughEth();
error AstroSpin__TransferFailed();
error AstroSpin__NotOpen();
error AstroSpin__UpkeepNotNeeded(
uint256 currentBalance,
uint256 numPlayers,
uint256 astroSpinState
);
contract AstroSpin is IEntropyConsumer, Ownable, ReentrancyGuard {
// Entropy
IEntropy entropy;
address entropyProvider;
/* state variables */
uint256 public i_minEntranceFee;
address payable[] public s_players;
address payable public treasuryWallet;
bool public feeEnabled = true;
uint256 public feePool;
uint256 public astroSpinFee;
address payable[] public s_recentWinner;
mapping(address => bool) public isPlayerEntered;
uint256 public roundCount = 0;
mapping(address => uint256) public contributions;
address public caller;
/** Variables */
enum AstroSpinState {
OPEN,
CALCULATING
}
AstroSpinState private s_AstroSpinState;
uint256 private s_lastTimeStamp;
/* events */
event AstroSpinEnterRequest(uint64 sequenceNumber);
event AstroSpinEnterResult(uint64 sequenceNumber);
event AstroSpinEnter(address indexed player, uint256 amount);
event AstroSpinResult(uint64 sequenceNumber);
event RefundProcessed(address indexed player, uint256 amount);
event RefundCompleted(uint256 playerCount, uint256 totalAmount);
event RequestedAstroSpinWinner(uint256 indexed requestId);
event WinnerPicked(
address indexed winner,
uint256 prize,
uint256 contribution
);
event TreasuryChanged(address indexed newTreasury);
// Events for tracking refund status
event RefundIssued(address to, uint256 amount);
event RefundFailed(address to, uint256 amount);
event SpecialWalletPoolFilled(uint256 amount, uint256 newTotal);
/**
* @notice Constructor initializes the AstroSpin contract
* @param minEntranceFee The fee required to enter the game
* @param _treasuryWallet Address where treasury funds will be sent
* @param _entropy Address of the Entropy contract for randomness
* @param _entropyProvider Address of the entropy provider
*/
constructor(
uint256 minEntranceFee,
address payable _treasuryWallet,
address _entropy,
address _entropyProvider,
address _caller
) {
i_minEntranceFee = minEntranceFee;
s_AstroSpinState = AstroSpinState.OPEN;
treasuryWallet = _treasuryWallet;
entropy = IEntropy(_entropy);
entropyProvider = _entropyProvider;
caller = _caller;
}
modifier onlyCaller() {
require(
msg.sender == caller || msg.sender == owner(),
"Only the caller or owner can call this function"
);
_;
}
function setUpkeepCaller(address _newCaller) external onlyOwner {
require(_newCaller != address(0), "New caller cannot be zero address");
caller = _newCaller;
}
// This method is required by the IEntropyConsumer interface
function getEntropy() internal view override returns (address) {
return address(entropy);
}
function getFlipFee() public view returns (uint256 fee) {
fee = entropy.getFee(entropyProvider);
}
function getAstroSpinFee() public view returns (uint256 fee) {
fee = astroSpinFee;
}
function setFee(uint256 _feeMultiplier) public onlyOwner {
require(_feeMultiplier > 0, "Fee multiplier must be greater than zero");
uint256 flipFee = entropy.getFee(entropyProvider);
astroSpinFee = (flipFee * _feeMultiplier);
}
function toggleFee(bool _enabled) public onlyOwner {
feeEnabled = _enabled;
}
function enterAstroSpin() public payable {
require(s_AstroSpinState == AstroSpinState.OPEN, "AstroSpin__NotOpen");
uint256 fee = feeEnabled ? astroSpinFee : 0;
feePool += fee;
require(msg.value >= i_minEntranceFee, "AstroSpin__NotEnoughEth");
contributions[msg.sender] += msg.value - fee;
if (!isPlayerEntered[msg.sender]) {
s_players.push(payable(msg.sender));
isPlayerEntered[msg.sender] = true;
}
emit AstroSpinEnter(msg.sender, contributions[msg.sender]);
}
/**
* @notice Initiates the random winner selection process if conditions are met
* @dev Checks if game is open, has balance and minimum players before requesting entropy
* @param userRandomNumber Additional entropy input from user
*/
function performUpkeep(
bytes32 userRandomNumber
) external payable onlyCaller {
bool isOpen = AstroSpinState.OPEN == s_AstroSpinState;
bool hasBalance = address(this).balance > 0;
bool hasPlayers = s_players.length >= 2;
bool upkeepNeeded = (isOpen && hasBalance && hasPlayers);
if (!upkeepNeeded) {
revert AstroSpin__UpkeepNotNeeded(
address(this).balance,
s_players.length,
uint256(s_AstroSpinState)
);
}
s_AstroSpinState = AstroSpinState.CALCULATING;
uint256 fee = entropy.getFee(entropyProvider);
uint64 sequenceNumber = entropy.requestWithCallback{ value: fee }(
entropyProvider,
userRandomNumber
);
emit RequestedAstroSpinWinner(sequenceNumber);
emit AstroSpinEnterRequest(sequenceNumber);
}
/**
* @notice Callback function called by entropy provider with random number
* @dev Selects winner based on weighted contributions and distributes prizes
* @param sequenceNumber The sequence number of the entropy request
* @param randomNumber The random number provided by entropy source
*/
function entropyCallback(
uint64 sequenceNumber,
address,
bytes32 randomNumber
) internal override {
delete s_recentWinner;
uint256 totalContributions = 0;
for (uint256 i = 0; i < s_players.length; i++) {
totalContributions += contributions[s_players[i]];
}
require(totalContributions > 0, "Total contributions must be positive");
uint256 winningThreshold = uint256(randomNumber) % totalContributions;
uint256 cumulativeContribution = 0;
address payable recentWinner = payable(address(0));
for (uint256 i = 0; i < s_players.length; i++) {
cumulativeContribution += contributions[s_players[i]];
if (winningThreshold < cumulativeContribution) {
recentWinner = s_players[i];
break;
}
}
uint256 pool = address(this).balance - feePool;
uint256 prizes;
uint256 treasuryAmount;
// Check if winner's contribution is greater than potential prize
uint256 potentialPrize = (pool * 80) / 100;
if (contributions[recentWinner] > potentialPrize) {
// If winner would get less than their contribution, give them the full pool
prizes = pool;
treasuryAmount = 0;
} else {
// Otherwise proceed with normal 80/20 split
prizes = potentialPrize;
treasuryAmount = (pool * 20) / 100;
}
// Transfer prize directly to winner
(bool prizeSuccess, ) = recentWinner.call{ value: prizes }("");
require(prizeSuccess, "Prize transfer failed");
// Transfer treasury amount to treasury wallet if any
if (treasuryAmount > 0) {
(bool treasurySuccess, ) = treasuryWallet.call{
value: treasuryAmount
}("");
require(treasurySuccess, "Treasury transfer failed");
}
s_recentWinner.push(recentWinner);
emit WinnerPicked(recentWinner, prizes, contributions[recentWinner]);
emit AstroSpinResult(sequenceNumber);
// Reset for next AstroSpin
for (uint256 i = 0; i < s_players.length; i++) {
address player = s_players[i];
contributions[player] = 0;
isPlayerEntered[player] = false;
}
roundCount++;
s_AstroSpinState = AstroSpinState.OPEN;
s_players = new address payable[](0);
s_lastTimeStamp = block.timestamp;
}
function getContractBalance() public view returns (uint256) {
return address(this).balance;
}
function getBalanceWithoutPlatformFund() public view returns (uint256) {
if (feePool > address(this).balance) {
return 0;
}
uint256 totalDeductions = address(this).balance - feePool;
return totalDeductions;
}
function getAstroSpinState() public view returns (AstroSpinState) {
return s_AstroSpinState;
}
function getMinEntranceFee() public view returns (uint256) {
return i_minEntranceFee;
}
function getPlayer(uint256 index) public view returns (address) {
return s_players[index];
}
function getAllPlayers() public view returns (address payable[] memory) {
return s_players;
}
function getRecentWinners() public view returns (address payable[] memory) {
return s_recentWinner;
}
function getLastTimeStamp() public view returns (uint256) {
return s_lastTimeStamp;
}
function getNumberOfPlayers() public view returns (uint256) {
return s_players.length;
}
function getRoundCount() public view returns (uint256) {
return roundCount;
}
function getFeePool() public view returns (uint256) {
return feePool;
}
function transferFeeFunds(address payable _to) public onlyOwner {
require(_to != address(0), "Invalid address");
require(feePool > 0, "No funds to transfer");
uint256 amountToTransfer = feePool;
feePool = 0; // Reset before transfer to prevent reentrancy
(bool success, ) = _to.call{ value: amountToTransfer }("");
require(success, "Transfer failed");
}
function getPlayerContributionsPercentages()
public
view
returns (address[] memory, uint256[] memory, uint256[] memory)
{
address[] memory players = new address[](s_players.length);
uint256[] memory percentages = new uint256[](s_players.length);
uint256[] memory contributionsArray = new uint256[](s_players.length);
uint256 total = 0;
// Calculate total contributions
for (uint256 i = 0; i < s_players.length; i++) {
total += contributions[s_players[i]];
}
// Calculate each player's percentage of total contributions and get their contribution
for (uint256 i = 0; i < s_players.length; i++) {
players[i] = s_players[i];
contributionsArray[i] = contributions[s_players[i]]; // Store individual contributions
if (total > 0) {
percentages[i] = (contributions[s_players[i]] * 100) / total;
} else {
percentages[i] = 0;
}
}
return (players, percentages, contributionsArray);
}
// Function to update the entrance fee
function updateEntranceFee(uint256 _newMinEntranceFee) external onlyOwner {
i_minEntranceFee = _newMinEntranceFee;
}
function setTreasury(address payable _newTreasury) public onlyOwner {
require(
_newTreasury != address(0),
"New treasury cannot be the zero address"
);
treasuryWallet = _newTreasury;
emit TreasuryChanged(_newTreasury);
}
function refundAllParticipants() external onlyOwner nonReentrant {
require(s_players.length > 0, "No players to refund");
// Store length since we'll modify the array
uint256 playerCount = s_players.length;
// Track refund amount for validation
uint256 totalRefunded = 0;
// Process refunds
for (uint256 i = 0; i < playerCount; i++) {
address payable player = s_players[i];
uint256 playerContribution = contributions[player];
if (playerContribution > 0) {
// Update state before transfer to prevent reentrancy
uint256 amountToRefund = playerContribution;
contributions[player] = 0;
isPlayerEntered[player] = false;
// Process refund
(bool success, ) = player.call{ value: amountToRefund }("");
require(success, "Refund transfer failed");
totalRefunded += amountToRefund;
emit RefundProcessed(player, amountToRefund);
}
}
// Reset contract state
s_AstroSpinState = AstroSpinState.OPEN;
s_players = new address payable[](0);
emit RefundCompleted(playerCount, totalRefunded);
}
receive() external payable {}
}