coral-xyz / anchor-book

The Anchor Book
https://book.anchor-lang.com
Apache License 2.0
97 stars 59 forks source link

TicTacToe example: trying to use ctx inside Game #74

Closed netpoe closed 2 years ago

netpoe commented 2 years ago

Following the TicTacToe example, I'm trying to pass ctx to a public method flip of Game:

// instructions/play.rs
pub fn play(ctx: Context<Play>, data: FlipArgs) -> Result<()> {
    ctx.accounts.game.flip(&ctx, data)
}
pub fn flip(&mut self, ctx: Context<Play>, data: FlipArgs) -> Result<()> {
    self.charge_fee(ctx);

    match data.heads_or_tails {
        true => self.play_heads(ctx),
        false => self.play_tails(ctx),
    }
}

fn charge_fee(&self, ctx: Context<Play>) -> Result<()> {
    let player = &ctx.accounts.player;

    if **player.try_borrow_lamports()? < self.static_amount {
        return Err(CoinflipError::InsufficientFunds.into());
    }

    let fee = self.calculate_fee();

    **player.try_borrow_mut_lamports()? -= fee as u64;

    Ok(())
}

However, this results in an error:

anchor_lang::context::Context<instructions::play::Play>
ctx: Context<Play>
anchor_lang::context::Context<instructions::play::Play>
ctx: Context<Play>
mismatched types

expected struct `anchor_lang::context::Context`, found reference

So, how to make ctx work from inside Game in order to access the ctx.accounts.player?

paul-schaaf commented 2 years ago

pls use discord for support