> ## Documentation Index
> Fetch the complete documentation index at: https://solana.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> This page is part of the Solana developer documentation at https://solana.com/developers/docs. Append `.md` to any docs URL, or send `Accept: text/markdown`, to get the page as Markdown.
> Index of all pages: https://solana.com/llms.txt. Per-section indexes such as https://solana.com/developers/docs/payments/llms.txt are smaller; prefer them when working on one task.
> Coding agents: install the official Solana skill for current APIs and conventions with `npx skills add https://github.com/solana-foundation/solana-dev-skill` (also served at https://solana.com/SKILL.md).
> Code in the cookbook and task pages comes from tested example files. Prefer it over writing API calls from memory.

# Storing SOL in a PDA

> Using PDAs, you can reward SOL to players playing your game. Learn how to reward SOL from a PDA when players find chests in this game.

Here you will learn how to store SOL in a PDA. In the example we will use it to
reward players in a game. We will build a simple game where players can move
right and collect a reward when they reach a specific position. The reward will
be stored in a PDA, and players can claim it by interacting with the game.

## Tiny Adventure Anchor Program - Part Two

In this tutorial, we will rebuild the Tiny Adventure game and introduce a chest
with a reward of 0.1 SOL. The chest will "spawn" at a specific position, and
when the player reaches that position, they will receive the reward. The goal of
this program is to demonstrate how to store SOL within a program account and
distribute it to players.

The Tiny Adventure Two Program consists of 3 instructions:

- `initialize_level_one` - This instruction initializes two onchain accounts:
  one for recording the player's position and another for holding the SOL reward
  that represents the “reward chest”.
- `reset_level_and_spawn_chest` - This instruction resets the player's position
  to zero and "respawns" a reward chest by transferring SOL from the user
  invoking the instruction to the reward chest account.
- `move_right` - This instruction allows the player to move their position to
  the right and collect the SOL in the reward chest once they reach a specific
  position.

In the following sections, we will guide you through building the program step
by step in a local Anchor project, then play the game from a TypeScript client
that runs against a local validator. The complete program is in
[Build the program](#build-the-program).

### Getting Started

This tutorial uses the Anchor CLI on your computer. If you haven't installed the
Solana development tools yet, follow the
[installation guide](/developers/docs/quickstart). It installs Rust, the Solana
CLI, the Anchor CLI, Surfpool, Node.js, and Yarn. This tutorial was tested with Anchor
CLI 1.1.2, Solana CLI 3.1.10 (the pair the installer sets up through AVM), and
Surfpool 1.7.0.

Create a project with a single-file program and a Mocha test:

```bash Terminal
anchor init tiny-adventure-two --template single --test-template mocha --package-manager yarn
cd tiny-adventure-two
```

`--package-manager yarn` sets the project up with Yarn. Without it,
`anchor init` uses the first of pnpm, Yarn, and npm that it finds. The program
lives in `programs/tiny-adventure-two/src/lib.rs`. The TypeScript test in
`tests/tiny-adventure-two.ts` is where you'll write the client.

The `initialize_level_one` instruction uses Anchor's `init_if_needed`
constraint, which needs the `init-if-needed` feature. In
`programs/tiny-adventure-two/Cargo.toml`, replace the `anchor-lang` line under
`[dependencies]` with:

```toml title="programs/tiny-adventure-two/Cargo.toml"
[dependencies]
anchor-lang = { version = "1.1.2", features = ["init-if-needed"] }
```

Then replace the starter code in `programs/tiny-adventure-two/src/lib.rs` with
the code below:

```rust title="programs/tiny-adventure-two/src/lib.rs"
use anchor_lang::prelude::*;
use anchor_lang::system_program;

// `anchor keys sync` replaces this with your program's address.
declare_id!("11111111111111111111111111111111");

// 1 SOL is 1 billion lamports.
const LAMPORTS_PER_SOL: u64 = 1_000_000_000;

#[program]
pub mod tiny_adventure_two {
    use super::*;
}

fn print_player(player_position: u8) {
    if player_position == 0 {
        msg!("A Journey Begins!");
        msg!("o.........💎");
    } else if player_position == 1 {
        msg!("..o.......💎");
    } else if player_position == 2 {
        msg!("....o.....💎");
    } else if player_position == 3 {
        msg!("........\\o/💎");
        msg!("..........\\o/");
        msg!("You have reached the end! Super!");
    }
}
```

In this game, the player starts at position 0 and can only move right. To
visualize the player's progress throughout the game, we'll use message logs to
represent their journey towards the reward chest.

### Defining the Chest Vault Account

Add the `CHEST_REWARD` constant at the beginning of the program. The
`CHEST_REWARD` represents the amount of lamports that will be put into the chest
and given out as rewards. Lamports are the smallest fractions of a SOL, with 1
billion lamports being equal to 1 SOL. The `LAMPORTS_PER_SOL` constant at the
top of the file holds that conversion.

To store the SOL reward, we will define a new `ChestVaultAccount` struct. This
is an empty struct because we will be directly updating the lamports in the
account. The account will hold the SOL reward and does not need to store any
additional data.

```rust
use anchor_lang::prelude::*;
use anchor_lang::system_program;

// `anchor keys sync` replaces this with your program's address.
declare_id!("11111111111111111111111111111111");

// 1 SOL is 1 billion lamports.
const LAMPORTS_PER_SOL: u64 = 1_000_000_000;

#[program]
pub mod tiny_adventure_two {
    use super::*;

    // The amount of lamports that will be put into chests and given out as rewards.
    const CHEST_REWARD: u64 = LAMPORTS_PER_SOL / 10; // 0.1 SOL
}

...

// Define the Chest Vault Account structure
#[account]
pub struct ChestVaultAccount {}
```

### Defining the Game Data Account

To keep track of the player's position within the game, we need to define a
structure for the onchain account that will store the player's position.

The `GameDataAccount` struct contains a single field, `player_position`, which
stores the player's current position as an unsigned 8-bit integer.

```rust
use anchor_lang::prelude::*;
use anchor_lang::system_program;

// `anchor keys sync` replaces this with your program's address.
declare_id!("11111111111111111111111111111111");

...

#[program]
pub mod tiny_adventure_two {
    use super::*;
    ...

}

...

// Define the Game Data Account structure
#[account]
pub struct GameDataAccount {
    player_position: u8,
}
```

With the `GameDataAccount` struct defined, you can now use it to store and
update the player's position as they interact with the game. As the player moves
right and progresses through the game, their position will be updated within the
`GameDataAccount`, allowing you to track their progress towards the chest
containing the SOL reward.

### Initialize Level One Instruction

With the `GameDataAccount` and `ChestVaultAccount` defined, let's implement the
`initialize_level_one` instruction. This instruction initializes both the
`GameDataAccount` and `ChestVaultAccount`, sets the player's position to 0, and
displays the starting message.

The `initialize_level_one` instruction requires 4 accounts:

- `new_game_data_account` - the `GameDataAccount` we are initializing to store
  the player's position
- `chest_vault` - the `ChestVaultAccount` we are initializing to store the SOL
  reward
- `signer` - the player paying for the initialization of the accounts
- `system_program` - a required account when creating a new account

```rust
#[program]
pub mod tiny_adventure_two {
    use super::*;

    pub fn initialize_level_one(_ctx: Context<InitializeLevelOne>) -> Result<()> {
        msg!("A Journey Begins!");
        msg!("o.......💎");
        Ok(())
    }

    ...
}

// Specify the accounts required by the initialize_level_one instruction
#[derive(Accounts)]
pub struct InitializeLevelOne<'info> {
    #[account(
        init_if_needed,
        seeds = [b"level1"],
        bump,
        payer = signer,
        space = 8 + 1
    )]
    pub new_game_data_account: Account<'info, GameDataAccount>,
    #[account(
        init_if_needed,
        seeds = [b"chestVault"],
        bump,
        payer = signer,
        space = 8
    )]
    pub chest_vault: Account<'info, ChestVaultAccount>,
    #[account(mut)]
    pub signer: Signer<'info>,
    pub system_program: Program<'info, System>,
}

...
```

Both the `GameDataAccount` and `ChestVaultAccount` are created using a Program
Derived Address (PDA) as the address of the account, allowing us to
deterministically locate the address later. The `init_if_needed` constraint
ensures that the accounts are only initialized if they don't already exist.
Since the PDAs for both accounts in this instruction use a single fixed seed,
our program can only create one of each type of account. In effect, the
instruction would only ever need to be invoked one time.

It's worth noting that the current implementation does not have any restrictions
on who can modify the `GameDataAccount`, effectively turning the game into a
multiplayer experience where everyone can control the player's movement.

Alternatively, you can use the signer's address as an extra seed in the
`initialize_level_one` instruction, allowing each player to create their own
`GameDataAccount`.

### Reset Level and Spawn Chest Instruction

Next, let's implement the `reset_level_and_spawn_chest` instruction, which
resets the player's position to the start and fills up the chest with a reward
of 0.1 SOL.

The `reset_level_and_spawn_chest` instruction requires 4 accounts:

- `payer` - the player providing the SOL reward for the chest
- `chest_vault` - the `ChestVaultAccount` storing the SOL reward
- `game_data_account` - the `GameDataAccount` storing the player's position
- `system_program` - the program we'll be invoking to transfer SOL using a
  cross-program invocation (CPI), more on this shortly

```rust
#[program]
pub mod tiny_adventure_two {
    use super::*;
    ...

    pub fn reset_level_and_spawn_chest(ctx: Context<SpawnChest>) -> Result<()> {
        ctx.accounts.game_data_account.player_position = 0;

        let cpi_context = CpiContext::new(
            ctx.accounts.system_program.key(),
            system_program::Transfer {
                from: ctx.accounts.payer.to_account_info(),
                to: ctx.accounts.chest_vault.to_account_info(),
            },
        );
        system_program::transfer(cpi_context, CHEST_REWARD)?;

        msg!("Level Reset and Chest Spawned at position 3");

        Ok(())
    }

    ...
}

// Specify the accounts required by the reset_level_and_spawn_chest instruction
#[derive(Accounts)]
pub struct SpawnChest<'info> {
    #[account(mut)]
    pub payer: Signer<'info>,
    #[account(mut, seeds = [b"chestVault"], bump)]
    pub chest_vault: Account<'info, ChestVaultAccount>,
    #[account(mut)]
    pub game_data_account: Account<'info, GameDataAccount>,
    pub system_program: Program<'info, System>,
}

...
```

This instruction includes a cross-program invocation (CPI) to transfer SOL from
the payer to the `ChestVaultAccount`. A cross-program invocation is when one
program invokes an instruction on another program. In this case, we use a CPI to
invoke the `Transfer` instruction from the `system_program` to transfer SOL from
the payer to the `ChestVaultAccount`. `CpiContext::new` takes the address of the
program to invoke, here the System Program's, and the accounts its instruction
expects.

Cross-program invocations are a key concept in the Solana programming model,
enabling programs to directly interact with instructions from other programs.
For a deeper dive into CPIs, feel free to explore the
[CPI guide](/developers/docs/core/cpi).

### Move Right Instruction

Finally, let's implement the `move_right` instruction which includes the logic
for collecting the chest reward. When a player reaches position 3 and inputs the
correct “password”, the reward is transferred from the **`ChestVaultAccount`**
to the player's account. If an incorrect password is entered, a custom Anchor
Error is returned. If the player is already at position 3, a message will be
logged. Otherwise, the position will be incremented by 1 to represent moving to
the right.

The main purpose of this "password" functionality is to demonstrate how to
incorporate parameters into an instruction and the implementation of custom
Anchor Errors for improved error handling. In this example, the correct password
will be "gib".

The `move_right` instruction requires 3 accounts:

- `chest_vault` - the `ChestVaultAccount` storing the SOL reward
- `game_data_account` - the `GameDataAccount` storing the player's position
- `player` - the wallet of the player invoking the instruction and the
  potential recipient of SOL reward

```rust
#[program]
pub mod tiny_adventure_two {
    use super::*;
    ...

    // Instruction to move right
    pub fn move_right(ctx: Context<MoveRight>, password: String) -> Result<()> {
        let game_data_account = &mut ctx.accounts.game_data_account;
        if game_data_account.player_position == 3 {
            msg!("You have reached the end! Super!");
        } else if game_data_account.player_position == 2 {
            if password != "gib" {
                return err!(MyError::WrongPassword);
            }

            game_data_account.player_position = game_data_account.player_position + 1;

            msg!(
                "You made it! Here is your reward {0} lamports",
                CHEST_REWARD
            );

            **ctx
                .accounts
                .chest_vault
                .to_account_info()
                .try_borrow_mut_lamports()? -= CHEST_REWARD;
            **ctx
                .accounts
                .player
                .to_account_info()
                .try_borrow_mut_lamports()? += CHEST_REWARD;
        } else {
            game_data_account.player_position = game_data_account.player_position + 1;
            print_player(game_data_account.player_position);
        }
        Ok(())
    }

    ...
}

// Specify the accounts required by the move_right instruction
#[derive(Accounts)]
pub struct MoveRight<'info> {
    #[account(mut, seeds = [b"chestVault"], bump)]
    pub chest_vault: Account<'info, ChestVaultAccount>,
    #[account(mut)]
    pub game_data_account: Account<'info, GameDataAccount>,
    #[account(mut)]
    pub player: Signer<'info>,
}

// Custom Anchor Error
#[error_code]
pub enum MyError {
    #[msg("Password was wrong")]
    WrongPassword,
}

...
```

To transfer lamports from the reward chest to the player account, we can't use a
Cross-Program Invocation (CPI) to the System Program as we did previously, since
the `ChestVaultAccount` isn't owned by the System Program. Instead, we directly
modify the lamports within the accounts by using `try_borrow_mut_lamports`.

The program can subtract lamports from `ChestVaultAccount` because the program
owns that account: the runtime only lets an account's owner program debit it,
and no signature is involved. Any program can add lamports to a writable
account, so crediting the player works too. After each instruction, the runtime
also checks that the total balance across all accounts is unchanged (see the
[account modification rules](/developers/docs/core/accounts/modification-rules)).

PDA signing (`invoke_signed`, or `CpiContext::new_with_signer` in Anchor) is
only needed when a CPI requires the PDA as a signer, for example a System
Program transfer out of a PDA that the System Program owns. Here, the PDA gives
the chest a deterministic address that every client can derive from the
`chestVault` seed.

### Build the program

You've now completed part two of the Tiny Adventure program. Your
final program should look like this:

```rust title="programs/tiny-adventure-two/src/lib.rs"
use anchor_lang::prelude::*;
use anchor_lang::system_program;

// `anchor keys sync` replaces this with your program's address.
declare_id!("11111111111111111111111111111111");

// 1 SOL is 1 billion lamports.
const LAMPORTS_PER_SOL: u64 = 1_000_000_000;

#[program]
pub mod tiny_adventure_two {
    use super::*;

    // The amount of lamports that will be put into chests and given out as rewards.
    const CHEST_REWARD: u64 = LAMPORTS_PER_SOL / 10; // 0.1 SOL

    pub fn initialize_level_one(_ctx: Context<InitializeLevelOne>) -> Result<()> {
        // Usually in your production code you would not print lots of text because it costs compute units.
        msg!("A Journey Begins!");
        msg!("o.......💎");
        Ok(())
    }

    pub fn reset_level_and_spawn_chest(ctx: Context<SpawnChest>) -> Result<()> {
        ctx.accounts.game_data_account.player_position = 0;

        let cpi_context = CpiContext::new(
            ctx.accounts.system_program.key(),
            system_program::Transfer {
                from: ctx.accounts.payer.to_account_info(),
                to: ctx.accounts.chest_vault.to_account_info(),
            },
        );
        system_program::transfer(cpi_context, CHEST_REWARD)?;

        msg!("Level Reset and Chest Spawned at position 3");

        Ok(())
    }

    pub fn move_right(ctx: Context<MoveRight>, password: String) -> Result<()> {
        let game_data_account = &mut ctx.accounts.game_data_account;
        if game_data_account.player_position == 3 {
            msg!("You have reached the end! Super!");
        } else if game_data_account.player_position == 2 {
            if password != "gib" {
                return err!(MyError::WrongPassword);
            }

            game_data_account.player_position = game_data_account.player_position + 1;

            msg!(
                "You made it! Here is your reward {0} lamports",
                CHEST_REWARD
            );

            **ctx
                .accounts
                .chest_vault
                .to_account_info()
                .try_borrow_mut_lamports()? -= CHEST_REWARD;
            **ctx
                .accounts
                .player
                .to_account_info()
                .try_borrow_mut_lamports()? += CHEST_REWARD;
        } else {
            game_data_account.player_position = game_data_account.player_position + 1;
            print_player(game_data_account.player_position);
        }
        Ok(())
    }
}

fn print_player(player_position: u8) {
    if player_position == 0 {
        msg!("A Journey Begins!");
        msg!("o.........💎");
    } else if player_position == 1 {
        msg!("..o.......💎");
    } else if player_position == 2 {
        msg!("....o.....💎");
    } else if player_position == 3 {
        msg!("........\\o/💎");
        msg!("..........\\o/");
        msg!("You have reached the end! Super!");
    }
}

#[derive(Accounts)]
pub struct InitializeLevelOne<'info> {
    // We must specify the space in order to initialize an account.
    // The first 8 bytes are the default account discriminator,
    // the next 1 byte comes from GameDataAccount.player_position being type u8.
    // (u8 = 8-bit unsigned integer = 1 byte)
    // You can also use the signer as seed [signer.key().as_ref()],
    #[account(
        init_if_needed,
        seeds = [b"level1"],
        bump,
        payer = signer,
        space = 8 + 1
    )]
    pub new_game_data_account: Account<'info, GameDataAccount>,
    // This is the PDA in which we will deposit the reward SOL and
    // from where we send it back to the first player reaching the chest.
    #[account(
        init_if_needed,
        seeds = [b"chestVault"],
        bump,
        payer = signer,
        space = 8
    )]
    pub chest_vault: Account<'info, ChestVaultAccount>,
    #[account(mut)]
    pub signer: Signer<'info>,
    pub system_program: Program<'info, System>,
}

#[derive(Accounts)]
pub struct SpawnChest<'info> {
    #[account(mut)]
    pub payer: Signer<'info>,
    #[account(mut, seeds = [b"chestVault"], bump)]
    pub chest_vault: Account<'info, ChestVaultAccount>,
    #[account(mut)]
    pub game_data_account: Account<'info, GameDataAccount>,
    pub system_program: Program<'info, System>,
}

#[derive(Accounts)]
pub struct MoveRight<'info> {
    #[account(mut, seeds = [b"chestVault"], bump)]
    pub chest_vault: Account<'info, ChestVaultAccount>,
    #[account(mut)]
    pub game_data_account: Account<'info, GameDataAccount>,
    #[account(mut)]
    pub player: Signer<'info>,
}

#[account]
pub struct GameDataAccount {
    player_position: u8,
}

#[account]
pub struct ChestVaultAccount {}

#[error_code]
pub enum MyError {
    #[msg("Password was wrong")]
    WrongPassword,
}
```

Point `declare_id!` at your project's program address, then build the program:

```bash Terminal
anchor keys sync
anchor build
```

`anchor keys sync` reads the program keypair that `anchor init` created in
`target/deploy/tiny_adventure_two-keypair.json` and writes its address into
`declare_id!` and `Anchor.toml`. `anchor build` compiles the program to
`target/deploy/tiny_adventure_two.so` and writes its IDL to
`target/idl/tiny_adventure_two.json` and the TypeScript types the client imports
to `target/types/tiny_adventure_two.ts`.

<Warning>
  **`anchor build` fails with `Platform tools v1.52 is incompatible with SBPFv3`?**
  That happens with Anchor 1.1.x on Solana CLI 4.3 or later, without AVM. Build
  the program for SBPF v0 without the IDL, then build the IDL and the
  TypeScript types on their own:

  ```bash Terminal
  anchor build --no-idl -- --arch v0
  anchor idl build -o target/idl/tiny_adventure_two.json -t target/types/tiny_adventure_two.ts
  ```

  Then run the test in [Run the client](#run-the-client) with
  `anchor test --skip-build`, so it doesn't rebuild. For other Anchor and
  Solana CLI versions, see
  [Build your first program](/developers/docs/programs/build-first-program#run-test).
</Warning>

### Write the client

In this section, we'll walk through a simple client for interacting with the
game. The client is the Mocha test that `anchor init` created, and `anchor test`
runs it against a local validator. We will break down the code and provide
detailed explanations for each step.

Replace the contents of `tests/tiny-adventure-two.ts` with the code below, then
add the code snippets from the following sections, in order, inside the `it`
block:

```ts title="tests/tiny-adventure-two.ts"
import * as anchor from "@anchor-lang/core";
import { Program } from "@anchor-lang/core";
import { TinyAdventureTwo } from "../target/types/tiny_adventure_two";

describe("tiny-adventure-two", () => {
  // Configure the client to use the local cluster.
  const provider = anchor.AnchorProvider.env();
  anchor.setProvider(provider);

  const program = anchor.workspace.tinyAdventureTwo as Program<TinyAdventureTwo>;
  const player = provider.wallet.publicKey;

  // Print the messages the program logged with msg! during a transaction
  const printProgramLogs = async (txHash: string) => {
    const tx = await provider.connection.getTransaction(txHash, {
      commitment: "confirmed"
    });
    for (const log of tx?.meta?.logMessages ?? []) {
      if (log.startsWith("Program log: ")) console.log(log);
    }
  };

  it("Spawns a chest and collects the reward", async () => {
    // Add the code from the following sections here.
  });
});
```

`program` is the client for your program, built from the IDL and types that
`anchor build` wrote to `target`. `player` is the wallet set in `Anchor.toml`,
which pays for and signs every transaction the test sends. `printProgramLogs`
fetches a transaction and prints the lines your program logged with `msg!`, so
you can follow the program's side of the game in the test output.

First, let's derive the PDAs (program-derived addresses) for the
`GameDataAccount` and `ChestVaultAccount`. A PDA is a unique address in the
format of a public key, derived using the program's ID and additional seeds.

```ts
// The PDA address everyone will be able to control the character if they interact with your program
const [globalLevel1GameDataAccount, bump] =
  anchor.web3.PublicKey.findProgramAddressSync(
    [Buffer.from("level1", "utf8")],
    //[player.toBuffer()], <- You could also add the player wallet as a seed, then you would have one instance per player. Need to also change the seed in the rust part
    program.programId
  );

// This is where the program will save the SOL reward for the chests and from which the reward will be paid out again
const [chestVaultAccount, chestBump] =
  anchor.web3.PublicKey.findProgramAddressSync(
    [Buffer.from("chestVault", "utf8")],
    program.programId
  );
```

Next, we'll call the `initializeLevelOne` instruction to set up the
`GameDataAccount` and `ChestVaultAccount`.

```ts
// Initialize level
let txHash = await program.methods
  .initializeLevelOne()
  .accountsPartial({
    chestVault: chestVaultAccount,
    newGameDataAccount: globalLevel1GameDataAccount,
    signer: player,
    systemProgram: anchor.web3.SystemProgram.programId
  })
  .rpc({ commitment: "confirmed" });

console.log(`Transaction: ${txHash}`);
await printProgramLogs(txHash);

let balance = await provider.connection.getBalance(player);
console.log(
  `My balance before spawning a chest: ${balance / anchor.web3.LAMPORTS_PER_SOL} SOL`
);
```

`accountsPartial` lets you pass every account the instruction requires, as this
client does. With `.accounts()` instead, the client fills in the accounts it
can work out itself: PDAs whose seeds are in the IDL, the System Program, and
signers, which default to your wallet. `.rpc()` signs the transaction with your
wallet, sends it, and waits for the `confirmed` commitment, so
`printProgramLogs` can fetch it.

After that, we'll use the `resetLevelAndSpawnChest` instruction to set the
player's position to 0 and fill the `ChestVaultAccount` with 0.1 SOL.

```ts
// Set the player position back to 0 and pay to fill up the chest with sol
txHash = await program.methods
  .resetLevelAndSpawnChest()
  .accountsPartial({
    chestVault: chestVaultAccount,
    gameDataAccount: globalLevel1GameDataAccount,
    payer: player,
    systemProgram: anchor.web3.SystemProgram.programId
  })
  .rpc({ commitment: "confirmed" });

console.log(`Transaction: ${txHash}`);
await printProgramLogs(txHash);
console.log("Level reset and chest spawned 💎");
console.log("o........💎");
```

Now we can interact with the game by calling the `moveRight` instruction. In
this example, we'll loop through this instruction until the player reaches the
position to collect the reward from the `ChestVaultAccount`.

```ts
// Here we move to the right three times and collect the chest at the end of the level
for (let i = 0; i < 3; i++) {
  txHash = await program.methods
    .moveRight("gib")
    .accountsPartial({
      chestVault: chestVaultAccount,
      gameDataAccount: globalLevel1GameDataAccount,
      player: player
    })
    .rpc({ commitment: "confirmed" });

  console.log(`Transaction: ${txHash}`);
  await printProgramLogs(txHash);
  let balance = await provider.connection.getBalance(player);
  console.log(`My balance: ${balance / anchor.web3.LAMPORTS_PER_SOL} SOL`);

  let gameDataAccount = await program.account.gameDataAccount.fetch(
    globalLevel1GameDataAccount
  );

  console.log("Player position is:", gameDataAccount.playerPosition.toString());

  switch (gameDataAccount.playerPosition) {
    case 0:
      console.log("A journey begins...");
      console.log("o........💎");
      break;
    case 1:
      console.log("....o....💎");
      break;
    case 2:
      console.log("......o..💎");
      break;
    case 3:
      console.log(".........\\o/💎");
      console.log("...........\\o/");
      break;
  }
}
```

### Run the client

Run the test:

```bash Terminal
anchor test
```

`anchor test` builds the program, starts a local validator (Surfpool, the
default in Anchor CLI 1.1.2), deploys the program to it, and runs the test. The
validator funds your wallet, so you don't need devnet SOL, and it stops when the
test finishes. If Surfpool isn't installed, `anchor test` fails with
`` Failed to spawn `surfpool` ``; run `anchor test --validator legacy` to use
`solana-test-validator` instead.

The output should resemble the following. Your transaction signatures and
balances will differ:

```txt title="Output"
  tiny-adventure-two
Transaction: 5mF83zReJ7LNWTMBCkLJxDLMZA2XbRQpyU6NvcebgNNwRUP4ZUsFSP1wbRmeWumF6ZFDhUP1p1KDkP2Zg5HJu1s9
Program log: Instruction: InitializeLevelOne
Program log: A Journey Begins!
Program log: o.......💎
My balance before spawning a chest: 9999.99860816 SOL
Transaction: 2Rz3yutGXpScFqd5pPCEeL8U4btqpz6g9z88BqaRzsJQwEPYBezSCPmBqcniwsyeKQRkpbKSPyhrXqvPyGuPy7NC
Program log: Instruction: ResetLevelAndSpawnChest
Program log: Level Reset and Chest Spawned at position 3
Level reset and chest spawned 💎
o........💎
Transaction: 5rmP5x8azn9oKErRSf77xfqdkBSjspJkRycJeFmt6eazSBrrJ6tVnznDUmwjJNr2UvMHHUb8EceYAEW2U23udAT5
Program log: Instruction: MoveRight
Program log: ..o.......💎
My balance: 9999.89859816 SOL
Player position is: 1
....o....💎
Transaction: 63kWgqgJG1QPz7ELNNAvusBEVdUbPVusNNt8tbsafwZmPLUKxvt9SwoKxdEsrE2xcdavKwSqJJimoqW3AqtEEzN3
Program log: Instruction: MoveRight
Program log: ....o.....💎
My balance: 9999.89859316 SOL
Player position is: 2
......o..💎
Transaction: 544dsXqNUnYbAXfzeWhgVnefdQgooTPHYfz21a8HXquPQRC4VzTjNYCjw8Be8JuZY15YjnTnDH37MkebEaBoysQh
Program log: Instruction: MoveRight
Program log: You made it! Here is your reward 100000000 lamports
My balance: 9999.99858816 SOL
Player position is: 3
.........\o/💎
...........\o/
    ✔ Spawns a chest and collects the reward (170ms)


  1 passing (171ms)
```

Your balance drops by 0.1 SOL, plus transaction fees, when you spawn the chest,
and the 0.1 SOL comes back when you reach the chest with the right password.

If you change the password passed to **`moveRight`** to anything other than
"gib", the third `moveRight` call fails when the player tries to claim the
chest, and the test fails with this error:

```txt
Error: AnchorError thrown in programs/tiny-adventure-two/src/lib.rs:47. Error Code: WrongPassword. Error Number: 6000. Error Message: Password was wrong.
```

You have built Tiny Adventure Two, deployed it to a local validator, and played
it from a client. You've incorporated a new feature that allows players to
collect rewards by reaching the chest at the end of the level. Moreover, you've
learned how to transfer SOL within an Anchor program using cross-program
invocations and by directly modifying lamports in accounts.

Feel free to continue building independently and enhance the game with
additional features like new levels or alternative rewards.

For more advanced examples you can check out the
[Solana Game Examples](/developers/cookbook/games/game-examples).
