Coin Flip Anchor Example

A simple coin flip game using feed FEED PROTOCOL RANDOM NUMBER GENERATOR PROGRAM with anchor framework

Implementing FEED PROTOCOL RANDOM NUMBER GENERATOR PROGRAM (FPRNG) to your program is very easy. You derive the needed accounts and pass into the instruction. And then in your program make a CPI to FPRNG. In these simple example program we will cover every step of the implamaentation. Lets say you want to build an on-chain coin flip game. First user chooses heads or tails and send this decision to your coinflip program. Your coin flip program calls FPRNG. FPRNG return a random number to your program. You compare the returned random number with the user's decision in coinflip program. Finally coin flip program logs a message according to result. THIS ALL HAPPENS IN ONE TRANSACTION. You can store the random number in an account in your program. You can also try coinflip program on Devnet and Testnet.

Now lets take a look at how we use FPRNG in coinflip game program.

Derivation of Accounts

FPRNG address(It is the same address for devnet, testnet and mainnet-beta)

1
const rngProgram = new anchor.web3.PublicKey('9uSwASSU59XvUS8d1UeU8EwrEzMGFdXZvQ4JSEAfcS7k');

Deriving a PDA that store the required feed accounts

1
2
3
4
const current_feeds_account = PublicKey.findProgramAddressSync(
   [Buffer.from("c"), Buffer.from([1])],
   rngProgram
);

Getting account_info from the blockchain

1
2
3
const currentFeedsAccountInfo = await connection.getAccountInfo(
  current_feeds_account[0]
);

Parsing required data from the account data

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  const currentFeedsAccountData = deserialize(
    CurrentFeedSchema,
    CurrentFeed,
    currentFeedsAccountInfo?.data!
  );

  const feedAccount1 = new PublicKey(
    bs58.encode(currentFeedsAccountData.account1).toString()
  );
  const feedAccount2 = new PublicKey(
    bs58.encode(currentFeedsAccountData.account2).toString()
  );
  const feedAccount3 = new PublicKey(
    bs58.encode(currentFeedsAccountData.account3).toString()
  );

  const fallbackAccount = new PublicKey(
    bs58.encode(currentFeedsAccountData.fallback_account).toString()
  );

Generating a keypair to use in FPRNG

1
const tempKeypair = anchor.web3.Keypair.generate();

Creating Instruction

Player's decision(head or tails) is serialized to pass as instruction data.

1
const playersDecision = { decision: new anchor.BN(decision) };

We create our instruction, then build it and finally send. Below account are necassary to CPI FPRNG. You can also include the accounts you want to use in your program. However, when you make cpi into FPRNG the order of these accounts and their properties should be as below

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  const tx = await program.methods
    .getRandom(playersDecision)
    .accounts({
      signer: player.publicKey,
      feedAccount1: feedAccount1,
      feedAccount2: feedAccount2,
      feedAccount3: feedAccount3,
      fallbackAccount: fallbackAccount,
      currentFeedsAccount: current_feeds_account[0],
      temp: tempKeypair.publicKey,
      rngProgram: rngProgram,
    })
    .signers([player, tempKeypair])
    .rpc();

Coin Flip Program

We get our accounts

1
2
3
4
5
6
7
8
9
10
let accounts_iter: &mut std::slice::Iter<', AccountInfo<'>> = &mut accounts.iter();
let payer: &AccountInfo<'_> = next_account_info(accounts_iter)?;
let price_feed_account_1: &AccountInfo<'_> = next_account_info(accounts_iter)?;
let price_feed_account_2: &AccountInfo<'_> = next_account_info(accounts_iter)?;
let price_feed_account_3: &AccountInfo<'_> = next_account_info(accounts_iter)?;
let fallback_account: &AccountInfo<'_> = next_account_info(accounts_iter)?;
let current_feed_accounts: &AccountInfo<'_> = next_account_info(accounts_iter)?;
let temp: &AccountInfo<'_> = next_account_info(accounts_iter)?;
let rng_program: &AccountInfo<'_> = next_account_info(accounts_iter)?;
let system_program: &AccountInfo<'_> = next_account_info(accounts_iter)?;

Creating account metas for CPI to FPRNG

1
2
3
4
5
6
7
8
let payer_meta = AccountMeta{ pubkey: *payer.key, is_signer: true, is_writable: true,};
let price_feed_account_1_meta = AccountMeta{ pubkey: *price_feed_account_1.key, is_signer: false,is_writable: false,};
let price_feed_account_2_meta = AccountMeta{ pubkey: *price_feed_account_2.key, is_signer: false,is_writable: false,};
let price_feed_account_3_meta = AccountMeta{ pubkey: *price_feed_account_3.key, is_signer: false,is_writable: false,};
let fallback_account_meta = AccountMeta{ pubkey: *fallback_account.key, is_signer: false, is_writable: false,};
let current_feed_accounts_meta = AccountMeta{ pubkey: *current_feed_accounts.key, is_signer: false, is_writable: true,};
let temp_meta = AccountMeta{ pubkey: *temp.key, is_signer: true, is_writable: true,};
let system_program_meta = AccountMeta{ pubkey: *system_program.key, is_signer: false, is_writable: false,};

CPI to FPRNG

1
2
3
4
5
6
7
8
9
10
11
invoke(&ix, 
  &[
    payer.clone(),
    price_feed_account_1.clone(),
    price_feed_account_2.clone(),
    price_feed_account_3.clone(),
    fallback_account.clone(),
    current_feed_accounts.clone(),
    temp.clone(),
    system_program.clone()
    ])?;

Checking players input - zero is head, one is tails

1
2
3
4
let players_decision: PlayersDecision = PlayersDecision::try_from_slice(&instruction_data)?;
if players_decision.decision != 0 && players_decision.decision != 1 {panic!()}

let returned_data:(Pubkey, Vec<u8>)= get_return_data().unwrap();

Random number is returned from the FPRNG

1
2
3
4
5
6
7
let random_number:RandomNumber;
if &returned_data.0 == rng_program.key{
  random_number = RandomNumber::try_from_slice(&returned_data.1)?;
  msg!("{}",random_number.random_number);
}else{
    panic!();
}

We get the mod 2 of the random number. It is either one or zero

1
let head_or_tails: u64 = random_number.random_number % 2;

Then we compare with the player's decision just log a message. you can put here your program logic

1
2
3
4
5
if head_or_tails != players_decision.decision {
    msg!("you lost");
}else{
    msg!("congragulations you win");
}
You can check the github repo for more details