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

# Program

> The Program class provides the IDL-based client for interacting with Anchor programs

## Overview

The `Program` class is the primary interface for interacting with Anchor programs. It provides a type-safe, IDL-driven API for sending transactions, fetching accounts, and listening to events.

```typescript theme={null}
import { Program, AnchorProvider } from "@anchor-lang/anchor";
import { Connection, PublicKey } from "@solana/web3.js";

const program = new Program(idl, provider);
```

## Constructor

<ResponseField name="constructor" type="(idl, provider?, coder?, getCustomResolver?) => Program">
  Creates a new Program instance.

  <Expandable title="parameters">
    <ResponseField name="idl" type="Idl" required>
      The Interface Definition Language object describing the program
    </ResponseField>

    <ResponseField name="provider" type="Provider">
      The network and wallet context. Defaults to `getProvider()` if not specified
    </ResponseField>

    <ResponseField name="coder" type="Coder">
      Custom coder for serialization. Defaults to `BorshCoder`
    </ResponseField>

    <ResponseField name="getCustomResolver" type="(instruction: IdlInstruction) => CustomAccountResolver | undefined">
      Function returning custom account resolvers for instructions
    </ResponseField>
  </Expandable>
</ResponseField>

## Static Methods

<ResponseField name="Program.at" type="async (address, provider?) => Promise<Program>">
  Fetches the IDL from the blockchain and creates a Program instance.

  ```typescript theme={null}
  const program = await Program.at(
    new PublicKey("11111111111111111111111111111111"),
    provider
  );
  ```

  <Expandable title="parameters">
    <ResponseField name="address" type="Address" required>
      The on-chain address of the program
    </ResponseField>

    <ResponseField name="provider" type="Provider">
      The network and wallet context
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="Program.fetchIdl" type="async (address, provider?) => Promise<Idl | null>">
  Fetches the IDL from the blockchain without creating a Program instance.

  ```typescript theme={null}
  const idl = await Program.fetchIdl(programId, provider);
  ```

  <Expandable title="parameters">
    <ResponseField name="address" type="Address" required>
      The on-chain address of the program
    </ResponseField>

    <ResponseField name="provider" type="Provider">
      The network and wallet context
    </ResponseField>
  </Expandable>
</ResponseField>

## Properties

<ResponseField name="programId" type="PublicKey">
  The on-chain address of the program.

  ```typescript theme={null}
  console.log(program.programId.toString());
  ```
</ResponseField>

<ResponseField name="idl" type="IDL">
  The IDL in camelCase format for TypeScript compatibility.

  ```typescript theme={null}
  const instructions = program.idl.instructions;
  ```
</ResponseField>

<ResponseField name="rawIdl" type="Idl">
  The original IDL without camelCase conversion (snake\_case from Rust).

  ```typescript theme={null}
  const originalIdl = program.rawIdl;
  ```
</ResponseField>

<ResponseField name="provider" type="Provider">
  The wallet and network provider used by this program.

  ```typescript theme={null}
  const connection = program.provider.connection;
  ```
</ResponseField>

<ResponseField name="coder" type="Coder">
  The coder used for serializing and deserializing data.

  ```typescript theme={null}
  const encoded = program.coder.instruction.encode("initialize", {});
  ```
</ResponseField>

## Namespaces

### methods

<ResponseField name="methods" type="MethodsNamespace<IDL>">
  The recommended builder API for constructing and sending transactions.

  ```typescript theme={null}
  const signature = await program.methods
    .initialize(new anchor.BN(100))
    .accounts({
      myAccount: myAccount.publicKey,
      user: provider.wallet.publicKey,
      systemProgram: SystemProgram.programId,
    })
    .signers([myAccount])
    .rpc();
  ```

  The methods namespace provides:

  * `.accounts()` - Set instruction accounts
  * `.signers()` - Add transaction signers
  * `.remainingAccounts()` - Add extra accounts
  * `.preInstructions()` - Add instructions before
  * `.postInstructions()` - Add instructions after
  * `.rpc()` - Send and confirm transaction
  * `.instruction()` - Build TransactionInstruction
  * `.transaction()` - Build Transaction
  * `.simulate()` - Simulate transaction
  * `.view()` - Call read-only instruction
</ResponseField>

### account

<ResponseField name="account" type="AccountNamespace<IDL>">
  Provides access to account clients for fetching and subscribing to account data.

  ```typescript theme={null}
  // Fetch a single account
  const accountData = await program.account.myAccount.fetch(address);

  // Fetch multiple accounts
  const accounts = await program.account.myAccount.fetchMultiple([
    address1,
    address2,
  ]);

  // Fetch all accounts of this type
  const allAccounts = await program.account.myAccount.all();

  // Subscribe to account changes
  const listener = program.account.myAccount.subscribe(address);
  listener.on("change", (account) => {
    console.log("Account changed:", account);
  });
  ```

  See [AccountClient](/api/typescript/program) for full details.
</ResponseField>

### rpc (deprecated)

<ResponseField name="rpc" type="RpcNamespace<IDL>">
  Legacy API for sending signed transactions. Use `methods` instead.

  ```typescript theme={null}
  // Deprecated - use program.methods instead
  const signature = await program.rpc.initialize({
    accounts: {
      counter: counterAddress,
      authority: provider.wallet.publicKey,
    },
  });
  ```

  <Warning>
    The `rpc` namespace is deprecated. Use `program.methods.<method>(...args).rpc()` instead.
  </Warning>
</ResponseField>

### transaction (deprecated)

<ResponseField name="transaction" type="TransactionNamespace<IDL>">
  Legacy API for building Transaction objects. Use `methods` instead.

  ```typescript theme={null}
  // Deprecated - use program.methods instead
  const tx = await program.transaction.initialize({
    accounts: {
      counter: counterAddress,
    },
  });
  ```

  <Warning>
    The `transaction` namespace is deprecated. Use `program.methods.<method>(...args).transaction()` instead.
  </Warning>
</ResponseField>

### simulate (deprecated)

<ResponseField name="simulate" type="SimulateNamespace<IDL>">
  Legacy API for simulating transactions. Use `methods` instead.

  ```typescript theme={null}
  // Deprecated - use program.methods instead
  const result = await program.simulate.initialize({
    accounts: {
      counter: counterAddress,
    },
  });
  ```

  <Warning>
    The `simulate` namespace is deprecated. Use `program.methods.<method>(...args).simulate()` instead.
  </Warning>
</ResponseField>

### instruction (deprecated)

<ResponseField name="instruction" type="InstructionNamespace<IDL>">
  Legacy API for building TransactionInstruction objects. Use `methods` instead.

  ```typescript theme={null}
  // Deprecated - use program.methods instead
  const ix = await program.instruction.initialize({
    accounts: {
      counter: counterAddress,
    },
  });
  ```

  <Warning>
    The `instruction` namespace is deprecated. Use `program.methods.<method>(...args).instruction()` instead.
  </Warning>
</ResponseField>

## Event Handling

<ResponseField name="addEventListener" type="(eventName, callback, commitment?) => number">
  Subscribe to program events emitted in transaction logs.

  ```typescript theme={null}
  const listenerId = program.addEventListener(
    "MyEvent",
    (event, slot, signature) => {
      console.log("Event:", event);
      console.log("Slot:", slot);
      console.log("Signature:", signature);
    },
    "confirmed"
  );
  ```

  <Expandable title="parameters">
    <ResponseField name="eventName" type="string" required>
      The PascalCase name of the event from the IDL
    </ResponseField>

    <ResponseField name="callback" type="(event, slot, signature) => void" required>
      Function called when the event is emitted
    </ResponseField>

    <ResponseField name="commitment" type="Commitment">
      Transaction commitment level to monitor
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="removeEventListener" type="async (listener) => Promise<void>">
  Unsubscribe from a program event.

  ```typescript theme={null}
  await program.removeEventListener(listenerId);
  ```

  <Expandable title="parameters">
    <ResponseField name="listener" type="number" required>
      The listener ID returned from `addEventListener`
    </ResponseField>
  </Expandable>
</ResponseField>

## Usage Examples

### Basic Initialization

```typescript theme={null}
import * as anchor from "@anchor-lang/anchor";
import { Program } from "@anchor-lang/anchor";
import { MyProgram } from "./target/types/my_program";

// Get provider from environment
const provider = anchor.AnchorProvider.env();
anchor.setProvider(provider);

// Load from workspace
const program = anchor.workspace.MyProgram as Program<MyProgram>;

// Or create with IDL
const program = new Program(idl, provider);
```

### Sending Transactions

```typescript theme={null}
const myAccount = anchor.web3.Keypair.generate();

const signature = await program.methods
  .initialize(new anchor.BN(100), "hello")
  .accounts({
    myAccount: myAccount.publicKey,
    user: provider.wallet.publicKey,
    systemProgram: anchor.web3.SystemProgram.programId,
  })
  .signers([myAccount])
  .rpc();

console.log("Transaction signature:", signature);
```

### Fetching Accounts

```typescript theme={null}
// Fetch single account
const account = await program.account.myAccount.fetch(accountAddress);
console.log("Balance:", account.balance);

// Fetch all accounts
const allAccounts = await program.account.myAccount.all();
allAccounts.forEach((acc) => {
  console.log("Account:", acc.publicKey.toString());
  console.log("Data:", acc.account);
});
```

### Building Complex Transactions

```typescript theme={null}
// Build instruction
const instruction = await program.methods
  .transfer(new anchor.BN(50))
  .accounts({
    from: fromAccount,
    to: toAccount,
  })
  .instruction();

// Add to transaction with other instructions
const transaction = new Transaction()
  .add(someOtherInstruction)
  .add(instruction);

const signature = await provider.sendAndConfirm(transaction);
```

### Listening to Events

```typescript theme={null}
// Listen for events
const listener = program.addEventListener(
  "TransferEvent",
  (event, slot) => {
    console.log(`Transfer of ${event.amount} at slot ${slot}`);
  }
);

// Later: remove listener
await program.removeEventListener(listener);
```
