Coin Flip is a game built with the Anchor framework and uses Switchboard VRF for pseudo-randomness. In this game, players can set up their own accounts, place a bet on a coin flip, and win or lose SOL based on the outcome.
To participate in the game, a player needs to create a game state account which stores data including their current guess, the result of the coin flip, and the timestamp of the last game. The initialize
instruction initializes the game state account.
When a player decides to place a bet, they invoke the request_randomness
instruction. This instruction transfers a predefined amount of SOL from the player to the game's SOL vault. It also requests randomness from the Switchboard Oracle and updates the game state with the player's guess.
The consume_randomness
instruction is not invoked directly by the client, but rather by the Switchboard Oracle after fulfilling the randomness request. This instruction "consumes" the randomness result generated by the Switchboard Oracle, calculates the result of the game, and updates the game state account with the new result. If the player's guess matches the generated result, the player wins double the initial amount they placed as a bet.
The close
instruction is used to close the game state account. This can be used to reset the game state when testing since each player can only have one game state account. This restriction is due to the fact that the player's public key is used as a seed to derive the Program Derived Address (PDA) for their game state account.