Skip to content

Instantly share code, notes, and snippets.

@AndreiCalazans
Last active May 11, 2022 15:28
Show Gist options
  • Save AndreiCalazans/af920a01b3d721cbd0cb4dbd1631811b to your computer and use it in GitHub Desktop.
Save AndreiCalazans/af920a01b3d721cbd0cb4dbd1631811b to your computer and use it in GitHub Desktop.
WIP - GuessGame Solidity Smart Contract
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
// Start game with a passphrase & reward
// Contract creator needs to have funds?
// Each address can only guess once (use modifier for this)
// Once correct guess give reward
// Add a game over modifier
contract GuessGame {
uint public reward;
bytes32 private passphrase;
mapping(address => bool) private didAddressGuessAlready;
constructor(
string memory _passphrase
) payable {
reward = msg.value;
passphrase = keccak256(abi.encodePacked(_passphrase));
}
modifier isGameOver() {
if (reward == 0) revert("Reward was already won. Game over.");
_;
}
modifier onlyOneGuessPerAddress() {
if (didAddressGuessAlready[msg.sender] == false) {
didAddressGuessAlready[msg.sender] = true;
} else {
revert("Only one guess per address is allowed.");
}
_;
}
function guess(string memory _guess) external payable isGameOver onlyOneGuessPerAddress returns (bool) {
if (keccak256(abi.encodePacked(_guess)) != passphrase) {
return false;
}
payable(msg.sender).transfer(reward);
reward = 0;
return true;
}
}
@AndreiCalazans
Copy link
Author

Some learnings from this:

  • You can map an address via msg.sender "address from = msg.sender
  • Best way to store a list of addresses in via mapping (you want to avoid iteration as much as possible) reference
  • modifiers can only access arguments by callsite (calling it with args - see below)

Calling modifiers with arguments:

   modifier checkHello(string memory _what) {
        if (compareStrings(_what, "what") == false) {
            revert("Wrong guess");
        }
        _;
    }
    
    function sayHello(string memory what) external checkHello(what) pure returns (string memory) {
        return "hello world 2";
    }

    function compareStrings(string memory a, string memory b) public pure returns (bool) {
        return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment