3

I have the following Accounts struct in my program:

#[derive(Accounts)]
pub struct StartLottery<'info> {
    #[account(init, payer = user, space = 8 + 8 + 8 + 8)]
    pub lottery_state: Account<'info, LotteryState>,
    #[account(mut)]
    pub user: Signer<'info>,
    pub system_program: Program<'info, System>,
}

And make the following call to the respective endpoint from my client using anchor-ts:

const lotteryStateKeyPair = anchor.web3.Keypair.generate();

// Add your test here.
const tx = await program.methods
  .startLottery()
  .accounts({
    lotteryState: lotteryStateKeyPair.publicKey,
  })
  .signers([lotteryStateKeyPair])
  .rpc();

This transaction works and succeeds. My question is, why do I not need to pass the user account or the system_program account into the .accounts({...}) method object and why do I not have to pass the user into the .signers([...]) method array? Both the system_program and user are specified as dependencies in the StartLottery struct.

It seems that these fields are auto-populated. But why? What are the rules for when a signer or account field gets auto populated?

1 Answer 1

4

I think the .rpc() method calls the sendAndConfirm (src) method on the AnchorProvider which uses AnchorWallet to sign the transaction before sending:

tx = await this.wallet.signTransaction(tx);

Found here: https://github.com/coral-xyz/anchor/blob/47ff77f4df503b109e32a559daa209ade5f86487/ts/packages/anchor/src/provider.ts#L156

4
  • What about the system program, why does that not need to be passed in? Jan 4 at 12:44
  • Technically, you do need to pass it into the request, however, Anchor abstracts common/known accounts like system account and token program account and adds them under the hood for you. If you'd like, you can use .accountsStrict method instead of .accounts and Anchor will force you to enter all necessary accounts including system program. github.com/coral-xyz/anchor/blob/…
    – AMilz
    Jan 4 at 14:49
  • is there documentation for this or can you only find this out via reading the code? Jan 4 at 15:01
  • 1
    Unfortunately, I couldn't find any Anchor docs which is why I pulled up the source.
    – AMilz
    Jan 4 at 15:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.