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

# IDL Types

> Interface Definition Language types for Anchor programs

## Overview

The IDL (Interface Definition Language) is a JSON structure that describes an Anchor program's interface. It defines instructions, accounts, types, events, and errors in a machine-readable format.

## Idl

The root IDL type that describes an entire Anchor program.

```typescript theme={null}
type Idl = {
  address: string;
  metadata: IdlMetadata;
  docs?: string[];
  instructions: IdlInstruction[];
  accounts?: IdlAccount[];
  events?: IdlEvent[];
  errors?: IdlErrorCode[];
  types?: IdlTypeDef[];
  constants?: IdlConst[];
};
```

<ResponseField name="address" type="string" required>
  The on-chain program address.

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

<ResponseField name="metadata" type="IdlMetadata" required>
  Program metadata including name, version, and spec version.
</ResponseField>

<ResponseField name="docs" type="string[]">
  Documentation comments from the Rust program.
</ResponseField>

<ResponseField name="instructions" type="IdlInstruction[]" required>
  Array of program instructions.
</ResponseField>

<ResponseField name="accounts" type="IdlAccount[]">
  Array of account type definitions.
</ResponseField>

<ResponseField name="events" type="IdlEvent[]">
  Array of event definitions.
</ResponseField>

<ResponseField name="errors" type="IdlErrorCode[]">
  Array of custom error codes.
</ResponseField>

<ResponseField name="types" type="IdlTypeDef[]">
  Array of custom type definitions (structs, enums).
</ResponseField>

<ResponseField name="constants" type="IdlConst[]">
  Array of program constants.
</ResponseField>

## IdlMetadata

Program metadata and version information.

```typescript theme={null}
type IdlMetadata = {
  name: string;
  version: string;
  spec: string;
  description?: string;
  repository?: string;
  dependencies?: IdlDependency[];
  contact?: string;
  deployments?: IdlDeployments;
};
```

<ResponseField name="name" type="string" required>
  The program name.
</ResponseField>

<ResponseField name="version" type="string" required>
  The program version (e.g., "0.1.0").
</ResponseField>

<ResponseField name="spec" type="string" required>
  The IDL spec version (e.g., "0.1.0").
</ResponseField>

<ResponseField name="description" type="string">
  Program description.
</ResponseField>

<ResponseField name="repository" type="string">
  Source code repository URL.
</ResponseField>

<ResponseField name="dependencies" type="IdlDependency[]">
  External program dependencies.
</ResponseField>

## IdlInstruction

Defines a single program instruction.

```typescript theme={null}
type IdlInstruction = {
  name: string;
  docs?: string[];
  discriminator: IdlDiscriminator;
  accounts: IdlInstructionAccountItem[];
  args: IdlField[];
  returns?: IdlType;
};
```

<ResponseField name="name" type="string" required>
  The instruction name in snake\_case.

  ```typescript theme={null}
  program.idl.instructions.forEach(ix => {
    console.log(ix.name); // e.g., "initialize", "transfer"
  });
  ```
</ResponseField>

<ResponseField name="docs" type="string[]">
  Documentation from Rust doc comments.
</ResponseField>

<ResponseField name="discriminator" type="number[]" required>
  8-byte instruction discriminator for identifying the instruction.
</ResponseField>

<ResponseField name="accounts" type="IdlInstructionAccountItem[]" required>
  Required accounts for the instruction.
</ResponseField>

<ResponseField name="args" type="IdlField[]" required>
  Instruction arguments.
</ResponseField>

<ResponseField name="returns" type="IdlType">
  Return type if the instruction returns a value.
</ResponseField>

## IdlInstructionAccount

Defines a single account required by an instruction.

```typescript theme={null}
type IdlInstructionAccount = {
  name: string;
  docs?: string[];
  writable?: boolean;
  signer?: boolean;
  optional?: boolean;
  address?: string;
  pda?: IdlPda;
  relations?: string[];
};
```

<ResponseField name="name" type="string" required>
  Account name.
</ResponseField>

<ResponseField name="writable" type="boolean">
  Whether the account is writable. Defaults to false.
</ResponseField>

<ResponseField name="signer" type="boolean">
  Whether the account must be a signer. Defaults to false.
</ResponseField>

<ResponseField name="optional" type="boolean">
  Whether the account is optional. Defaults to false.
</ResponseField>

<ResponseField name="address" type="string">
  Hardcoded account address if known at compile time.
</ResponseField>

<ResponseField name="pda" type="IdlPda">
  PDA derivation information if this account is a PDA.
</ResponseField>

<ResponseField name="relations" type="string[]">
  Related accounts for validation.
</ResponseField>

## IdlPda

Defines how to derive a Program Derived Address.

```typescript theme={null}
type IdlPda = {
  seeds: IdlSeed[];
  program?: IdlSeed;
};

type IdlSeed = IdlSeedConst | IdlSeedArg | IdlSeedAccount;

type IdlSeedConst = {
  kind: "const";
  value: number[];
};

type IdlSeedArg = {
  kind: "arg";
  path: string;
};

type IdlSeedAccount = {
  kind: "account";
  path: string;
  account?: string;
};
```

<ResponseField name="seeds" type="IdlSeed[]" required>
  Array of seeds used to derive the PDA.
</ResponseField>

<ResponseField name="program" type="IdlSeed">
  Optional program ID seed. Defaults to the current program.
</ResponseField>

## IdlAccount

Defines an account type stored by the program.

```typescript theme={null}
type IdlAccount = {
  name: string;
  discriminator: IdlDiscriminator;
};
```

<ResponseField name="name" type="string" required>
  The account type name.
</ResponseField>

<ResponseField name="discriminator" type="number[]" required>
  8-byte account discriminator for identifying the account type.
</ResponseField>

## IdlEvent

Defines an event that can be emitted by the program.

```typescript theme={null}
type IdlEvent = {
  name: string;
  discriminator: IdlDiscriminator;
};
```

<ResponseField name="name" type="string" required>
  Event name in PascalCase.
</ResponseField>

<ResponseField name="discriminator" type="number[]" required>
  8-byte event discriminator.
</ResponseField>

## IdlTypeDef

Defines a custom type (struct or enum).

```typescript theme={null}
type IdlTypeDef = {
  name: string;
  docs?: string[];
  serialization?: IdlSerialization;
  repr?: IdlRepr;
  generics?: IdlTypeDefGeneric[];
  type: IdlTypeDefTy;
};

type IdlTypeDefTy =
  | IdlTypeDefTyEnum
  | IdlTypeDefTyStruct
  | IdlTypeDefTyType;

type IdlTypeDefTyStruct = {
  kind: "struct";
  fields?: IdlDefinedFields;
};

type IdlTypeDefTyEnum = {
  kind: "enum";
  variants: IdlEnumVariant[];
};

type IdlTypeDefTyType = {
  kind: "type";
  alias: IdlType;
};
```

<ResponseField name="name" type="string" required>
  Type name.
</ResponseField>

<ResponseField name="type" type="IdlTypeDefTy" required>
  The type definition (struct, enum, or type alias).
</ResponseField>

<ResponseField name="generics" type="IdlTypeDefGeneric[]">
  Generic type parameters.
</ResponseField>

## IdlType

Represents any Anchor type.

```typescript theme={null}
type IdlType =
  | "bool"
  | "u8" | "i8"
  | "u16" | "i16"
  | "u32" | "i32"
  | "f32"
  | "u64" | "i64"
  | "f64"
  | "u128" | "i128"
  | "u256" | "i256"
  | "bytes"
  | "string"
  | "pubkey"
  | IdlTypeOption
  | IdlTypeCOption
  | IdlTypeVec
  | IdlTypeArray
  | IdlTypeDefined
  | IdlTypeGeneric;
```

### Primitive Types

<ResponseField name="bool" type="boolean">
  Boolean value.
</ResponseField>

<ResponseField name="u8, i8, u16, i16, u32, i32" type="number">
  Integer types that fit in JavaScript number.
</ResponseField>

<ResponseField name="u64, i64, u128, i128, u256, i256" type="BN">
  Large integer types requiring BN (Big Number) in JavaScript.
</ResponseField>

<ResponseField name="f32, f64" type="number">
  Floating point types.
</ResponseField>

<ResponseField name="bytes" type="Uint8Array">
  Raw bytes.
</ResponseField>

<ResponseField name="string" type="string">
  UTF-8 string.
</ResponseField>

<ResponseField name="pubkey" type="PublicKey">
  Solana public key.
</ResponseField>

### Complex Types

```typescript theme={null}
type IdlTypeOption = {
  option: IdlType;
};

type IdlTypeCOption = {
  coption: IdlType;
};

type IdlTypeVec = {
  vec: IdlType;
};

type IdlTypeArray = {
  array: [idlType: IdlType, size: IdlArrayLen];
};

type IdlTypeDefined = {
  defined: {
    name: string;
    generics?: IdlGenericArg[];
  };
};
```

<ResponseField name="option" type="{ option: IdlType }">
  Rust `Option<T>` type.
</ResponseField>

<ResponseField name="coption" type="{ coption: IdlType }">
  Compact option for primitives.
</ResponseField>

<ResponseField name="vec" type="{ vec: IdlType }">
  Dynamic array (Rust `Vec<T>`).
</ResponseField>

<ResponseField name="array" type="{ array: [IdlType, number] }">
  Fixed-size array.
</ResponseField>

<ResponseField name="defined" type="{ defined: { name: string } }">
  Custom defined type (references a type in `idl.types`).
</ResponseField>

## IdlField

A named field with a type.

```typescript theme={null}
type IdlField = {
  name: string;
  docs?: string[];
  type: IdlType;
};
```

<ResponseField name="name" type="string" required>
  Field name.
</ResponseField>

<ResponseField name="type" type="IdlType" required>
  Field type.
</ResponseField>

<ResponseField name="docs" type="string[]">
  Field documentation.
</ResponseField>

## IdlErrorCode

Defines a custom error.

```typescript theme={null}
type IdlErrorCode = {
  name: string;
  code: number;
  msg?: string;
};
```

<ResponseField name="name" type="string" required>
  Error name.
</ResponseField>

<ResponseField name="code" type="number" required>
  Error code (starting at 6000 for custom errors).
</ResponseField>

<ResponseField name="msg" type="string">
  Error message.
</ResponseField>

## Helper Functions

<ResponseField name="convertIdlToCamelCase" type="<I extends Idl>(idl: I) => I">
  Converts IDL from snake\_case to camelCase for TypeScript.

  ```typescript theme={null}
  import { convertIdlToCamelCase } from "@anchor-lang/anchor";

  const camelIdl = convertIdlToCamelCase(rawIdl);
  ```

  The `Program` class automatically applies this conversion.
</ResponseField>

<ResponseField name="idlAddress" type="async (programId: PublicKey) => Promise<PublicKey>">
  Derives the deterministic IDL account address for a program.

  ```typescript theme={null}
  import { idlAddress } from "@anchor-lang/anchor";

  const idlPubkey = await idlAddress(programId);
  ```
</ResponseField>

<ResponseField name="decodeIdlAccount" type="(data: Buffer) => IdlProgramAccount">
  Decodes an on-chain IDL account.

  ```typescript theme={null}
  import { decodeIdlAccount } from "@anchor-lang/anchor";

  const accountInfo = await connection.getAccountInfo(idlAddress);
  const idlAccount = decodeIdlAccount(accountInfo.data.slice(8));
  ```
</ResponseField>

<ResponseField name="isCompositeAccounts" type="(item: IdlInstructionAccountItem) => boolean">
  Type guard to check if an account item is a nested accounts group.

  ```typescript theme={null}
  import { isCompositeAccounts } from "@anchor-lang/anchor";

  if (isCompositeAccounts(accountItem)) {
    // Handle nested accounts
    accountItem.accounts.forEach(...);
  }
  ```
</ResponseField>

## Usage Examples

### Reading IDL Structure

```typescript theme={null}
import { Program } from "@anchor-lang/anchor";

const program = anchor.workspace.MyProgram;
const idl = program.idl;

console.log("Program:", idl.metadata.name);
console.log("Version:", idl.metadata.version);
console.log("Address:", idl.address);

// List all instructions
idl.instructions.forEach(ix => {
  console.log(`Instruction: ${ix.name}`);
  console.log(`  Args: ${ix.args.map(a => `${a.name}: ${JSON.stringify(a.type)}`).join(", ")}`);
  console.log(`  Accounts: ${ix.accounts.map(a => a.name).join(", ")}`);
});

// List all account types
idl.accounts?.forEach(acc => {
  console.log(`Account: ${acc.name}`);
});

// List all custom types
idl.types?.forEach(type => {
  console.log(`Type: ${type.name}`);
});
```

### Working with Types

```typescript theme={null}
const idl = program.idl;

// Find a specific type
const myStruct = idl.types?.find(t => t.name === "MyStruct");

if (myStruct && myStruct.type.kind === "struct") {
  console.log("Struct fields:");
  myStruct.type.fields?.forEach((field: any) => {
    console.log(`  ${field.name}: ${JSON.stringify(field.type)}`);
  });
}

// Find an enum
const myEnum = idl.types?.find(t => t.name === "MyEnum");

if (myEnum && myEnum.type.kind === "enum") {
  console.log("Enum variants:");
  myEnum.type.variants.forEach(variant => {
    console.log(`  ${variant.name}`);
  });
}
```

### Fetching IDL from Chain

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

const connection = new Connection("https://api.devnet.solana.com");
const programId = new PublicKey("YourProgramId");

// Fetch IDL from blockchain
const idl = await Program.fetchIdl(programId, provider);

if (idl) {
  console.log("Fetched IDL:", idl.metadata.name);
  
  // Create program with fetched IDL
  const program = new Program(idl, provider);
} else {
  console.log("IDL not found on-chain");
}
```

### Type Checking

```typescript theme={null}
import { IdlType } from "@anchor-lang/anchor";

function describeType(type: IdlType): string {
  if (typeof type === "string") {
    return type; // Primitive type
  }
  
  if ("vec" in type) {
    return `Vec<${describeType(type.vec)}>`;
  }
  
  if ("option" in type) {
    return `Option<${describeType(type.option)}>`;
  }
  
  if ("array" in type) {
    return `[${describeType(type.array[0])}; ${type.array[1]}]`;
  }
  
  if ("defined" in type) {
    return type.defined.name;
  }
  
  return "unknown";
}

// Use with IDL
idl.instructions.forEach(ix => {
  ix.args.forEach(arg => {
    console.log(`${arg.name}: ${describeType(arg.type)}`);
  });
});
```

### Generating Documentation

```typescript theme={null}
const idl = program.idl;

// Generate markdown documentation
let markdown = `# ${idl.metadata.name}\n\n`;
markdown += `Version: ${idl.metadata.version}\n\n`;

if (idl.metadata.description) {
  markdown += `${idl.metadata.description}\n\n`;
}

markdown += `## Instructions\n\n`;
idl.instructions.forEach(ix => {
  markdown += `### ${ix.name}\n\n`;
  
  if (ix.docs) {
    markdown += `${ix.docs.join("\n")}\n\n`;
  }
  
  markdown += `**Arguments:**\n`;
  ix.args.forEach(arg => {
    markdown += `- \`${arg.name}\`: ${describeType(arg.type)}\n`;
  });
  markdown += `\n`;
});

console.log(markdown);
```
