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

# Instruction Structure

> Solana instruction structure — program_id, accounts, and data fields, AccountMeta flags is_signer and is_writable, compiled instructions, and SOL transfer examples in TypeScript and Rust.

<Info>
  **Summary**

  An instruction has 3 fields: `program_id` (which program to invoke),
  `accounts` (AccountMeta list with is_signer/is_writable flags), and `data`
  (byte array of data that the program interprets).
</Info>

## Instruction structure

An
[`Instruction`](https://github.com/anza-xyz/solana-sdk/blob/clock%40v2.2.3/instruction/src/lib.rs#L97)
consists of three fields:

- `program_id`: The [ID](#program-id) of the program being
  invoked.
- `accounts`: An array of
  [account metadata](#account-metadata)
- `data`: A byte array with additional [data](#data)
  to be used by the instruction.

```rust title="Instruction struct"
pub struct Instruction {
    /// Pubkey of the program that executes this instruction.
    pub program_id: Pubkey,
    /// Metadata describing accounts that should be passed to the program.
    pub accounts: Vec<AccountMeta>,
    /// Opaque data passed to the program for its own interpretation.
    pub data: Vec<u8>,
}
```

### Program ID

The instruction's [`program_id`](/developers/docs/references/terminology#program-id) is the
public key address of the program that contains the instruction's execution
logic. The runtime uses this field to route the instruction to the correct
program for processing.

### Account metadata

The instruction's `accounts` array is an ordered list of
[`AccountMeta`](https://github.com/anza-xyz/solana-sdk/blob/clock%40v2.2.3/instruction/src/account_meta.rs#L25)
structs. Metadata must be provided for each account the instruction interacts
with. The validator uses this metadata to determine which transactions can run
in parallel. Transactions that write to different accounts can execute in
parallel.

The diagram below depicts a transaction that contains a single instruction. The
instruction's `accounts` array contains metadata for two accounts.

<Frame caption="Each entry in an instruction's accounts list is an AccountMeta: an address plus signer and writable flags.">
  <img className="block dark:hidden" src="/docs-assets/assets/docs/core/transactions/accountmeta-light.svg" alt="Each entry in an instruction's accounts list is an AccountMeta: an address plus signer and writable flags." />

  <img className="hidden dark:block" src="/docs-assets/assets/docs/core/transactions/accountmeta.svg" alt="Each entry in an instruction's accounts list is an AccountMeta: an address plus signer and writable flags." />

  <img className="block dark:hidden" src="/docs-assets/assets/docs/core/transactions/accountmeta-sm-light.svg" alt="Each entry in an instruction's accounts list is an AccountMeta: an address plus signer and writable flags." />

  <img className="hidden dark:block" src="/docs-assets/assets/docs/core/transactions/accountmeta-sm.svg" alt="Each entry in an instruction's accounts list is an AccountMeta: an address plus signer and writable flags." />
</Frame>

Each `AccountMeta` has three fields:

- pubkey: The account's public key address
- is_signer: Set to `true` if the account must sign the
  transaction
- is_writable: Set to `true` if the instruction modifies
  the account's data

<Note>
  To know which accounts an instruction requires, including which must be
  writable, read-only, or sign the transaction, you must refer to the
  implementation of the instruction, as defined by the program.
</Note>

```rust AccountMeta
pub struct AccountMeta {
    /// An account's public key.
    pub pubkey: Pubkey,
    /// True if an `Instruction` requires a `Transaction` signature matching `pubkey`.
    pub is_signer: bool,
    /// True if the account data or metadata may be mutated during program execution.
    pub is_writable: bool,
}
```

### Data

The instruction's `data` field is a byte array that tells the program which
function to invoke and supplies the arguments for that function. The data
typically begins with a discriminator or index byte(s) that identifies the
target function, followed by the serialized arguments. The encoding format is
defined by each program (for example, Borsh serialization or a custom layout).

Common encoding conventions:

- **Core programs** (System, Stake, Vote): Use a Bincode-serialized enum variant
  index followed by serialized arguments.
- **Anchor programs**: Use an 8-byte discriminator (the first 8 bytes of the
  SHA-256 hash of `"global:<function_name>"`) followed by Borsh-serialized
  arguments.

The runtime does not interpret the `data` field. It is passed as-is to the
program's `process_instruction` entrypoint.

## Compiled instruction

When instructions are serialized into a transaction message, they become
[`CompiledInstruction`](/developers/docs/core/transactions/transaction-structure#instructions)
structs that replace all public keys with compact integer indices into the
message's `account_keys` array.

## Example: SOL transfer instruction

The example below shows the structure of a SOL transfer instruction.

<Note>
  The Rust tabs on this page use the 2.x Solana crates. Install the
  dependencies with (tested with Rust 1.89 and 1.98):

  ```bash
  cargo add anyhow solana-sdk@2 solana-system-interface@1
  cargo add tokio --features full
  ```
</Note>

<CodeGroup>

```ts Kit
import { createClient, generateKeyPairSigner, lamports } from "@solana/kit";
import { solanaRpc, rpcAirdrop } from "@solana/kit-plugin-rpc";
import { generatedPayer, airdropPayer } from "@solana/kit-plugin-signer";
import { systemProgram } from "@solana-program/system";

const client = await createClient()
  .use(generatedPayer())
  .use(
    solanaRpc({
      rpcUrl: "http://localhost:8899",
      rpcSubscriptionsUrl: "ws://localhost:8900"
    })
  )
  .use(rpcAirdrop())
  .use(airdropPayer(lamports(1_000_000_000n)))
  .use(systemProgram());

// Generate sender and recipient keypairs
const sender = client.payer;
const recipient = await generateKeyPairSigner();

// Define the amount to transfer
const LAMPORTS_PER_SOL = 1_000_000_000n;
const transferAmount = lamports(LAMPORTS_PER_SOL / 100n); // 0.01 SOL

// Create a transfer instruction for transferring SOL from sender to recipient
const transferInstruction = client.system.instructions.transferSol({
  source: sender,
  destination: recipient.address,
  amount: transferAmount
});

console.log(JSON.stringify(transferInstruction, null, 2));
```

```ts title="Web3.js v3"
import {
  LAMPORTS_PER_SOL,
  SystemProgram,
  Transaction,
  Keypair
} from "@solana/web3.js";

// Generate sender and recipient keypairs
const sender = await Keypair.generate();
const recipient = await Keypair.generate();

// Define the amount to transfer
const transferAmount = 0.01; // 0.01 SOL

// Create a transfer instruction for transferring SOL from sender to recipient
const transferInstruction = SystemProgram.transfer({
  fromPubkey: sender.publicKey,
  toPubkey: recipient.publicKey,
  lamports: transferAmount * LAMPORTS_PER_SOL // Convert transferAmount to lamports
});

console.log(JSON.stringify(transferInstruction, null, 2));
```

```rs Rust
use anyhow::Result;
use solana_sdk::{native_token::LAMPORTS_PER_SOL, signature::Signer, signer::keypair::Keypair};
use solana_system_interface::instruction::transfer;

#[tokio::main]
async fn main() -> Result<()> {
    // Generate sender and recipient keypairs
    let sender = Keypair::new();
    let recipient = Keypair::new();

    // Define the amount to transfer
    let transfer_amount = LAMPORTS_PER_SOL / 100; // 0.01 SOL

    // Create a transfer instruction for transferring SOL from sender to recipient
    let transfer_instruction = transfer(&sender.pubkey(), &recipient.pubkey(), transfer_amount);

    println!("{:#?}", transfer_instruction);

    Ok(())
}
```

<Warning>
  **`@solana/web3.js` 1.x is no longer actively maintained**

  It receives critical fixes only. Use [Kit](/developers/docs/clients/official/javascript#solana-kit) for new code. To migrate existing code, follow the [Kit upgrade guide](https://www.solanakit.com/docs/upgrade-guide), or the [web3.js v3 migration guide](https://github.com/solana-foundation/solana-web3.js/blob/main/docs/web3js-v1-to-v3-migration.md) to keep the class-based API.

  To run this code, install 1.x with `npm install @solana/web3.js@1`. A plain `npm install @solana/web3.js` installs v3, which this code doesn't run on.
</Warning>

```ts title="Web3.js (legacy)"
import {
  LAMPORTS_PER_SOL,
  SystemProgram,
  Transaction,
  Keypair
} from "@solana/web3.js";

// Generate sender and recipient keypairs
const sender = Keypair.generate();
const recipient = new Keypair();

// Define the amount to transfer
const transferAmount = 0.01; // 0.01 SOL

// Create a transfer instruction for transferring SOL from sender to recipient
const transferInstruction = SystemProgram.transfer({
  fromPubkey: sender.publicKey,
  toPubkey: recipient.publicKey,
  lamports: transferAmount * LAMPORTS_PER_SOL // Convert transferAmount to lamports
});

console.log(JSON.stringify(transferInstruction, null, 2));
```

</CodeGroup>

The code below shows the output from the previous code snippets. The format will
differ between SDKs, but notice that each instruction contains the same three
pieces of required information: `program_id`,
`accounts`, `data`.

<CodeGroup>

```json Kit
{
  "accounts": [
    {
      "address": "Hu28vRMGWpQXN56eaE7jRiDDRRz3vCXEs7EKHRfL6bC",
      "role": 3,
      "signer": {
        "address": "Hu28vRMGWpQXN56eaE7jRiDDRRz3vCXEs7EKHRfL6bC",
        "keyPair": {
          "privateKey": {},
          "publicKey": {}
        }
      }
    },
    {
      "address": "2mBY6CTgeyJNJDzo6d2Umipw2aGUquUA7hLdFttNEj7p",
      "role": 1
    }
  ],
  "programAddress": "11111111111111111111111111111111",
  "data": {
    "0": 2,
    "1": 0,
    "2": 0,
    "3": 0,
    "4": 128,
    "5": 150,
    "6": 152,
    "7": 0,
    "8": 0,
    "9": 0,
    "10": 0,
    "11": 0
  }
}
```

```json title="Web3.js v3"
{
  "keys": [
    {
      "pubkey": "3z9vL1zjN6qyAFHhHQdWYRTFAcy69pJydkZmSFBKHg1R",
      "isSigner": true,
      "isWritable": true
    },
    {
      "pubkey": "BpvxsLYKQZTH42jjtWHZpsVSa7s6JVwLKwBptPSHXuZc",
      "isSigner": false,
      "isWritable": true
    }
  ],
  "programId": "11111111111111111111111111111111",
  "data": [2, 0, 0, 0, 128, 150, 152, 0, 0, 0, 0, 0]
}
```

```txt Rust
Instruction {
    program_id: 11111111111111111111111111111111,
    accounts: [
        AccountMeta {
            pubkey: DbEkAfFN4rQcX7W4YdhjrzagyCwKEUbEXioTiWBoKovt,
            is_signer: true,
            is_writable: true,
        },
        AccountMeta {
            pubkey: 5QYSRAuoo1bX4NA8z2AEe9akr6byGbQkXqh75RPFrJeu,
            is_signer: false,
            is_writable: true,
        },
    ],
    data: [
        2,
        0,
        0,
        0,
        128,
        150,
        152,
        0,
        0,
        0,
        0,
        0,
    ],
}
```

```json title="Web3.js (legacy)"
{
  "keys": [
    {
      "pubkey": "3z9vL1zjN6qyAFHhHQdWYRTFAcy69pJydkZmSFBKHg1R",
      "isSigner": true,
      "isWritable": true
    },
    {
      "pubkey": "BpvxsLYKQZTH42jjtWHZpsVSa7s6JVwLKwBptPSHXuZc",
      "isSigner": false,
      "isWritable": true
    }
  ],
  "programId": "11111111111111111111111111111111",
  "data": [2, 0, 0, 0, 128, 150, 152, 0, 0, 0, 0, 0]
}
```

</CodeGroup>

The examples below show how to manually build the transfer instruction. (The
`Expanded Instruction` tab is functionally equivalent to the `Instruction` tab.)

<Info>
  In practice, you usually don’t have to construct an `Instruction`
  manually. Most programs provide client libraries with helper functions that
  create the instructions for you. If a library isn't available, you can
  manually build the instruction.
</Info>

<Tabs>

<Tab title="Kit">

<CodeGroup>

```ts Instruction
const transferAmount = lamports(LAMPORTS_PER_SOL / 100n); // 0.01 SOL

const transferInstruction = client.system.instructions.transferSol({
  source: sender,
  destination: recipient.address,
  amount: transferAmount
});
```

```ts title="Expanded Instruction"
const transferAmount = LAMPORTS_PER_SOL / 100n; // 0.01 SOL

// Instruction index for the System Program's transfer instruction
const TRANSFER_INSTRUCTION_INDEX = 2;

// Create a buffer for the data to include in the instruction
const instructionData = Buffer.alloc(4 + 8); // uint32 + uint64
instructionData.writeUInt32LE(TRANSFER_INSTRUCTION_INDEX, 0);
instructionData.writeBigUInt64LE(transferAmount, 4);

const SYSTEM_PROGRAM_ADDRESS = "11111111111111111111111111111111" as Address;

// Manually create the transfer instruction
const transferInstruction: Instruction = {
  programAddress: SYSTEM_PROGRAM_ADDRESS,
  accounts: [
    {
      address: sender.address,
      role: AccountRole.WRITABLE_SIGNER
    },
    {
      address: recipient.address,
      role: AccountRole.WRITABLE
    }
  ],
  data: new Uint8Array(instructionData)
};
```

</CodeGroup>

</Tab>

<Tab title="Web3.js v3">

<CodeGroup>

```ts Instruction
const transferAmount = 0.01; // 0.01 SOL

const transferInstruction = SystemProgram.transfer({
  fromPubkey: sender.publicKey,
  toPubkey: recipient.publicKey,
  lamports: transferAmount * LAMPORTS_PER_SOL
});
```

```ts title="Expanded Instruction"
const transferAmount = 0.01; // 0.01 SOL

// Instruction index for the System Program's transfer instruction
const transferInstructionIndex = 2;

// Create a buffer for the data to include in the instruction
const instructionData = Buffer.alloc(4 + 8); // uint32 + uint64
instructionData.writeUInt32LE(transferInstructionIndex, 0);
instructionData.writeBigUInt64LE(BigInt(transferAmount * LAMPORTS_PER_SOL), 4);

// Manually create a transfer instruction
const transferInstruction = new TransactionInstruction({
  keys: [
    { pubkey: sender.publicKey, isSigner: true, isWritable: true }, // from account, is signer and is writable
    { pubkey: recipient.publicKey, isSigner: false, isWritable: true } // to account, is not signer but is writable
  ],
  programId: SystemProgram.programId,
  data: instructionData
});
```

</CodeGroup>

</Tab>

<Tab title="Rust">

<CodeGroup>

```rs Instruction
let transfer_amount = LAMPORTS_PER_SOL / 100; // 0.01 SOL

let transfer_instruction = solana_system_interface::instruction::transfer(
    &sender.pubkey(),
    &recipient.pubkey(),
    transfer_amount,
);
```

```rs title="Expanded Instruction"
// Instruction index for the System Program's transfer instruction
let transfer_instruction_index: u32 = 2;

// Define the amount to transfer
let transfer_amount = LAMPORTS_PER_SOL / 100; // 0.01 SOL

// Create instruction data manually (12 bytes: 4 for u32 index + 8 for u64 lamports)
let mut instruction_data = Vec::with_capacity(12);
instruction_data.extend_from_slice(&transfer_instruction_index.to_le_bytes());
instruction_data.extend_from_slice(&transfer_amount.to_le_bytes());

// Manually create the transfer instruction
let transfer_instruction = Instruction {
    program_id: solana_system_interface::program::ID,
    accounts: vec![
        AccountMeta::new(sender.pubkey(), true), // from account, is signer and is writable
        AccountMeta::new(recipient.pubkey(), false), // to account, is not signer but is writable
    ],
    data: instruction_data,
};
```

</CodeGroup>

</Tab>

<Tab title="Web3.js (legacy)">

<Warning>
  **`@solana/web3.js` 1.x is no longer actively maintained**

  It receives critical fixes only. Use [Kit](/developers/docs/clients/official/javascript#solana-kit) for new code. To migrate existing code, follow the [Kit upgrade guide](https://www.solanakit.com/docs/upgrade-guide), or the [web3.js v3 migration guide](https://github.com/solana-foundation/solana-web3.js/blob/main/docs/web3js-v1-to-v3-migration.md) to keep the class-based API.

  To run this code, install 1.x with `npm install @solana/web3.js@1`. A plain `npm install @solana/web3.js` installs v3, which this code doesn't run on.
</Warning>

<CodeGroup>

```ts Instruction
const transferAmount = 0.01; // 0.01 SOL

const transferInstruction = SystemProgram.transfer({
  fromPubkey: sender.publicKey,
  toPubkey: recipient.publicKey,
  lamports: transferAmount * LAMPORTS_PER_SOL
});
```

```ts title="Expanded Instruction"
const transferAmount = 0.01; // 0.01 SOL

// Instruction index for the System Program's transfer instruction
const transferInstructionIndex = 2;

// Create a buffer for the data to include in the instruction
const instructionData = Buffer.alloc(4 + 8); // uint32 + uint64
instructionData.writeUInt32LE(transferInstructionIndex, 0);
instructionData.writeBigUInt64LE(BigInt(transferAmount * LAMPORTS_PER_SOL), 4);

// Manually create a transfer instruction
const transferInstruction = new TransactionInstruction({
  keys: [
    { pubkey: sender.publicKey, isSigner: true, isWritable: true }, // from account, is signer and is writable
    { pubkey: recipient.publicKey, isSigner: false, isWritable: true } // to account, is not signer but is writable
  ],
  programId: SystemProgram.programId,
  data: instructionData
});
```

</CodeGroup>

</Tab>

</Tabs>
