> ## 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.

# PDA Accounts

> Create onchain accounts at Solana PDA addresses using invoke_signed and Anchor's init constraint. invoke_signed verification flow and Anchor PDA creation patterns with code examples.

<Info>
  **Summary**

  Create PDA accounts via `invoke_signed` with the PDA's seeds. Only the
  owning program can sign for a PDA. Anchor's `init` constraint automates
  PDA account creation.
</Info>

## PDA Signing via `invoke_signed`

When a program needs to sign on behalf of a PDA during a CPI, it uses
`invoke_signed` with the PDA's seeds. The runtime verifies the seeds derive
the expected PDA using the **calling program's ID**, ensuring only the owning
program can sign. For the full verification flow, see
[PDA Signing](/developers/docs/core/cpi/cpi-cost-model#pda-signing).

<Security title="Control what a PDA signature authorizes">
  The runtime checks that your program owns the PDA. It doesn't check what
  the signature is used for. Inside `invoke_signed`, the callee can do
  anything that PDA's signature allows, so:

  - Build signer seeds from validated accounts and stored state, never from
    raw instruction data. Caller-supplied seeds let the caller pick which of
    your PDAs signs.
  - Verify the program ID you invoke before signing (see
    [CPI](/developers/docs/core/cpi)).
  - Re-derive the PDA and compare it with the account passed in, so the
    signature covers the account you intend.
</Security>

## Create a PDA Account

Deriving a PDA and creating an account at a PDA are separate operations. You
must explicitly create the account after deriving the address.

To create an account at a PDA, the deriving program invokes the System Program's
`create_account` instruction via [`invoke_signed`](/developers/docs/core/cpi), passing
the PDA's seeds so the runtime can verify the program's authority over that
address.

The example below uses the [Anchor framework](https://www.anchor-lang.com/docs)
to create a new account with a program-derived address. The program includes a
single `initialize` instruction to create the new account,
which will store the user address and
bump seed used to derive the PDA.

To run this example locally with the Anchor CLI:

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

   ```bash Terminal
   anchor init pda-account --template single --test-template mocha
   cd pda-account
   ```

2. Replace `programs/pda-account/src/lib.rs` with the program below and
   `tests/pda-account.ts` with the test.
3. Point the program's `declare_id!` at your project's program ID:

   ```bash Terminal
   anchor keys sync
   ```

   Without this step, `anchor build` only warns
   `Program ID mismatch detected`, and `anchor test` fails with an error such
   as `DeclaredProgramIdMismatch` (Anchor 1.1.2) or
   `This program may not be used for executing instructions`.

4. Build the program and run the test:

   ```bash Terminal
   anchor test
   ```

```rs Program highlight={12,14,27,29,40-41}
use anchor_lang::prelude::*;

declare_id!("75GJVCJNhaukaa2vCCqhreY31gaphv7XTScBChmr1ueR");

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

    pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
        let account_data = &mut ctx.accounts.pda_account;
        // store the address of the `user`
        account_data.user = *ctx.accounts.user.key;
        // store the canonical bump
        account_data.bump = ctx.bumps.pda_account;
        Ok(())
    }
}

#[derive(Accounts)]
pub struct Initialize<'info> {
    #[account(mut)]
    pub user: Signer<'info>,

    #[account(
        init,
        // define the seeds to derive the PDA
        seeds = [b"data", user.key().as_ref()],
        // use the canonical bump
        bump,
        payer = user,
        space = 8 + DataAccount::INIT_SPACE // 8 bytes for Anchor account discriminator
    )]
    pub pda_account: Account<'info, DataAccount>,
    pub system_program: Program<'info, System>,
}

#[account]
#[derive(InitSpace)]
pub struct DataAccount {
    pub user: Pubkey,
    pub bump: u8,
}
```

The `init` constraint tells Anchor to
[invoke the System Program](/developers/docs/core/programs/builtin-programs#the-system-program)
to create a new account using the PDA as the address. The seeds
used to create the PDA are:

- The fixed string: "data"
- The address of the user account provided in the instruction
- The canonical bump seed

In this example, the bump constraint is not assigned a value, so Anchor will use
`find_program_address` to derive the PDA and find the bump.

```rust pda_account
#[account(
    init,
    seeds = [b"data", user.key().as_ref()],
    bump,
    payer = user,
    space = 8 + DataAccount::INIT_SPACE // 8 bytes for Anchor account discriminator
)]
pub pda_account: Account<'info, DataAccount>,
```

The test file below contains a transaction that invokes the
`initialize` instruction to create a new account with a
program-derived address. The file contains code to
derive the PDA.

The example also shows how to fetch the new account that will
be created.

```ts Test
import * as anchor from "@anchor-lang/core";
import { Program } from "@anchor-lang/core";
import { PdaAccount } from "../target/types/pda_account";
import { PublicKey } from "@solana/web3.js";

describe("pda-account", () => {
  const provider = anchor.AnchorProvider.env();
  anchor.setProvider(provider);

  const program = anchor.workspace.PdaAccount as Program<PdaAccount>;
  const user = provider.wallet as anchor.Wallet;

  // Derive the PDA address using the seeds specified on the program
  const [PDA] = PublicKey.findProgramAddressSync(
    [Buffer.from("data"), user.publicKey.toBuffer()],
    program.programId
  );

  it("Is initialized!", async () => {
    const transactionSignature = await program.methods
      .initialize()
      .accounts({
        user: user.publicKey
      })
      .rpc();

    console.log("Transaction Signature:", transactionSignature);
  });

  it("Fetch Account", async () => {
    const pdaAccount = await program.account.dataAccount.fetch(PDA);
    console.log(JSON.stringify(pdaAccount, null, 2));
  });
});
```

<Warning>
  If you invoke the `initialize` instruction again with the same `user` address
  seed, the transaction will fail. This happens because an account already
  exists at the derived address.
</Warning>

<Security title="Reinitialization with init_if_needed">
  Anchor's `init` fails when the account exists, which is the behavior
  above. `init_if_needed` succeeds either way and runs your handler on an
  existing account. If the handler writes initial state unconditionally, a
  caller can reset a live account, for example overwriting its stored
  `user` or zeroing a balance. Use `init` where you can; with
  `init_if_needed`, check whether the account is already initialized before
  writing to it.
</Security>
