How, for example, might you implement a simple "coin-flip" game as an on-chain Solana program?
The concept is that a player deposits a coin or token, and the onchain program generates a "win" or a "lose" with a 50/50 chance.
How, for example, might you implement a simple "coin-flip" game as an on-chain Solana program?
The concept is that a player deposits a coin or token, and the onchain program generates a "win" or a "lose" with a 50/50 chance.
Coin flip would be really difficult to implement as a smart contract because it traditionally requires a source of entropy in order to create a random(-ish) result. The problem is that introducing randomness means the program will no longer be deterministic and that makes it impossible for validators to replicate the results of the program and agree about the outcome. This is why the rand
crate is not available to on-chain programs.
Alternatively, you could take a non-traditional approach and implement a deterministic variant of coin-flip. However, since this result is calculable in a predictable manner it becomes very easy to cheat! Anyone can run the code themselves and only submit a coin to play when they know what the next result will be.
Another option would be to use an oracle or an off-chain resource that interacts with the on-chain contract after coins have been submitted.
Once you determine how to implement the actual "flip" mechanism, Paul wrote a very nice tutorial that illustrates how a smart contract might hold and later distribute tokens to a user.
Switchboard just recently carried out a Verifiable Random Function (VRF) workshop in their Discord, here are some links to help you.
Switchboard has an oracle that you can use to achieve randomness
https://docs.switchboard.xyz/randomness
They have an example using anchor
https://github.com/switchboard-xyz/vrf-cpi-example
As you pointed out yourself, the answer is "No, you cannot achieve randomness on-chain with Solana".
All validators need to get to the same new state after each transaction, so Solana is functioning in a deterministic manner.
Oracles are a possibility, but then you have to trust some off-chain generator to be truly random.
Most of the coin-flip
games you see use some form of off-chain
random
source (Oracle
is just someone pushing into the chain something generated outside).
There are ways to generate pseudo random numbers purely in solana
.
But the main issue is that you don't know their distribution and if you want to base a game on them, it can greatly affect it.