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

# Address Lookup Tables

> Learn how to use Solana Address Lookup Tables (ALTs) to efficiently handle up to 64 addresses per transaction. Create, extend, and utilize lookup tables using web3.js.

Address Lookup Tables, commonly referred to as "_lookup tables_" or "_ALTs_" for
short, allow developers to create a collection of related addresses to
efficiently load more addresses in a single transaction.

Since each transaction on the Solana blockchain requires a listing of every
address that is interacted with as part of the transaction, this listing would
effectively be capped at 32 addresses per transaction. With the help of Address
Lookup Tables, a transaction can raise that limit to 64 addresses.

> Address Lookup Tables are supported by v0 transactions only. The
> [v1 transaction format](/developers/docs/core/transactions/versioned-transactions#v1-format)
> does not support them — its 4,096-byte size limit fits up to 64 addresses
> inline instead.

## Compressing onchain addresses

After all the desired addresses have been stored onchain in an Address Lookup
Table, each address can be referenced inside a transaction by its 1-byte index
within the table (instead of their full 32-byte address). This lookup method
effectively "_compresses_" a 32-byte address into a 1-byte index value.

A single lookup table can store up to 256 addresses, and a transaction may
reference more than one table. That storage capacity is separate from how many
addresses a transaction can actually use: the runtime loads at most 64 accounts
per transaction regardless of how many addresses the tables it references hold.

## Versioned Transactions

To utilize an Address Lookup Table inside a transaction, developers must use v0
transactions that were introduced with the new
[Versioned Transaction format](/developers/cookbook/transactions/versions).

## How to create an address lookup table

Creating a new lookup table with the `@solana/web3.js` library is similar to the
older `legacy` transactions, but with some differences.

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

Using the `@solana/web3.js` library, you can use the
[`createLookupTable`](https://solana-foundation.github.io/solana-web3.js/v1.x/classes/AddressLookupTableProgram.html#createlookuptable)
function to construct the instruction needed to create a new lookup table, as
well as determine its address:

<CodeGroup>

```js title="Web3.js (legacy)"
import * as web3 from "@solana/web3.js";

// connect to a cluster and get the current `slot`
const connection = new web3.Connection(web3.clusterApiUrl("devnet"));
const slot = await connection.getSlot();

// Assumption:
// `payer` is a valid `Keypair` with enough SOL to pay for the execution

const [lookupTableInst, lookupTableAddress] =
  web3.AddressLookupTableProgram.createLookupTable({
    authority: payer.publicKey,
    payer: payer.publicKey,
    recentSlot: slot
  });

console.log("lookup table address:", lookupTableAddress.toBase58());

// To create the Address Lookup Table onchain:
// send the `lookupTableInst` instruction in a transaction
```

```py Python
import asyncio
import struct

from solana.rpc.async_api import AsyncClient
from solana.rpc.commitment import Confirmed
from solders.address_lookup_table_account import (
    ID as LOOKUP_TABLE_PROGRAM_ID,
    AddressLookupTable,
    AddressLookupTableAccount,
    derive_lookup_table_address,
)
from solders.instruction import AccountMeta, Instruction
from solders.keypair import Keypair
from solders.message import MessageV0
from solders.system_program import ID as SYSTEM_PROGRAM_ID, TransferParams, transfer
from solders.transaction import VersionedTransaction


async def main():
    async with AsyncClient("http://localhost:8899", commitment=Confirmed) as client:
        payer = Keypair()
        airdrop = await client.request_airdrop(payer.pubkey(), 1_000_000_000)
        await client.confirm_transaction(airdrop.value)

        async def send(instructions):
            blockhash = (await client.get_latest_blockhash()).value.blockhash
            message = MessageV0.try_compile(payer.pubkey(), instructions, [], blockhash)
            tx = VersionedTransaction(message, [payer])
            signature = (await client.send_transaction(tx)).value
            await client.confirm_transaction(signature)
            return signature

        def table_accounts(table):
            return [
                AccountMeta(table, is_signer=False, is_writable=True),
                AccountMeta(payer.pubkey(), is_signer=True, is_writable=False),  # authority
                AccountMeta(payer.pubkey(), is_signer=True, is_writable=True),  # payer
                AccountMeta(SYSTEM_PROGRAM_ID, is_signer=False, is_writable=False),
            ]

        slot = (await client.get_slot()).value
        lookup_table_address, bump = derive_lookup_table_address(payer.pubkey(), slot)

        # CreateLookupTable: instruction index 0, recent slot, bump seed
        create_instruction = Instruction(
            LOOKUP_TABLE_PROGRAM_ID,
            struct.pack("<IQB", 0, slot, bump),
            table_accounts(lookup_table_address),
        )
        await send([create_instruction])
        print("lookup table address:", lookup_table_address)

        # The next steps run here, inside main()

asyncio.run(main())
```

```go Go
ctx := context.Background()
client := rpc.New("http://localhost:8899")

payer := solana.NewWallet()
_, err := client.RequestAirdrop(ctx, payer.PublicKey(), solana.LAMPORTS_PER_SOL, rpc.CommitmentConfirmed)
if err != nil {
	panic(err)
}
time.Sleep(2 * time.Second)

signer := func(solana.PublicKey) *solana.PrivateKey { return &payer.PrivateKey }
send := func(instructions ...solana.Instruction) {
	recent, err := client.GetLatestBlockhash(ctx, rpc.CommitmentConfirmed)
	if err != nil {
		panic(err)
	}
	tx, err := solana.NewTransaction(instructions, recent.Value.Blockhash, solana.TransactionPayer(payer.PublicKey()))
	if err != nil {
		panic(err)
	}
	tx.Sign(signer)
	_, err = client.SendTransactionWithOpts(ctx, tx, rpc.TransactionOpts{PreflightCommitment: rpc.CommitmentConfirmed})
	if err != nil {
		panic(err)
	}
	time.Sleep(2 * time.Second)
}

slot, err := client.GetSlot(ctx, rpc.CommitmentConfirmed)
if err != nil {
	panic(err)
}
createInstruction, lookupTableAddress, err := lookup.NewCreateLookupTableInstruction(
	payer.PublicKey(), // authority
	payer.PublicKey(), // payer
	slot,
)
if err != nil {
	panic(err)
}
send(createInstruction.Build())
fmt.Println("lookup table address:", lookupTableAddress)
```

</CodeGroup>

> NOTE: Address lookup tables can be **created** with either a `v0` transaction
> or a `legacy` transaction. But the Solana runtime can only retrieve and handle
> the additional addresses within a lookup table while using
> [v0 Versioned Transactions](/developers/cookbook/transactions/versions#current-transaction-versions).

## Add addresses to a lookup table

Adding addresses to a lookup table is known as "_extending_". Using the
`@solana/web3.js` library, you can create a new _extend_ instruction using the
[`extendLookupTable`](https://solana-foundation.github.io/solana-web3.js/v1.x/classes/AddressLookupTableProgram.html#extendlookuptable)
method:

<CodeGroup>

```js title="Web3.js (legacy)"
// the address your transactions will send to
const recipient = web3.Keypair.generate().publicKey;

// add addresses to the `lookupTableAddress` table via an `extend` instruction.
// A transaction can't load its signers or the programs it invokes through a
// lookup table, so store the other accounts it uses, like `recipient`
const extendInstruction = web3.AddressLookupTableProgram.extendLookupTable({
  payer: payer.publicKey,
  authority: payer.publicKey,
  lookupTable: lookupTableAddress,
  addresses: [
    recipient
    // list more `publicKey` addresses here
  ]
});

// Send this `extendInstruction` in a transaction to the cluster
// to insert the listing of `addresses` into your lookup table with address `lookupTableAddress`
```

```py Python
recipient = Keypair().pubkey()
addresses = [recipient, SYSTEM_PROGRAM_ID]

# ExtendLookupTable: instruction index 2, number of addresses, addresses
extend_instruction = Instruction(
    LOOKUP_TABLE_PROGRAM_ID,
    struct.pack("<IQ", 2, len(addresses)) + b"".join(bytes(a) for a in addresses),
    table_accounts(lookup_table_address),
)
await send([extend_instruction])
```

```go Go
recipient := solana.NewWallet().PublicKey()
extendInstruction := lookup.NewExtendLookupTableInstruction(
	lookupTableAddress,
	payer.PublicKey(), // authority
	payer.PublicKey(), // payer
	[]solana.PublicKey{recipient, solana.SystemProgramID},
)
send(extendInstruction.Build())
```

</CodeGroup>

> NOTE: Due to the same memory limits of `legacy` transactions, any transaction
> used to _extend_ an Address Lookup Table is also limited in how many addresses
> can be added at a time. Because of this, you will need to use multiple
> transactions to _extend_ any table with more addresses (~20) that can fit
> within a single transaction's memory limits.

Once these addresses have been inserted into the table, and stored onchain, you
will be able to utilize the Address Lookup Table in future transactions.
Enabling up to 64 addresses in those future transactions.

## Fetch an Address Lookup Table

Similar to requesting another account (or PDA) from the cluster, you can fetch a
complete Address Lookup Table with the
[`getAddressLookupTable`](https://solana-foundation.github.io/solana-web3.js/v1.x/classes/Connection.html#getaddresslookuptable)
method:

<CodeGroup>

```js title="Web3.js (legacy)"
// define the `PublicKey` of the lookup table to fetch
const lookupTableAddress = new web3.PublicKey("");

// get the table from the cluster
const lookupTableAccount = (
  await connection.getAddressLookupTable(lookupTableAddress)
).value;

// `lookupTableAccount` will now be an `AddressLookupTableAccount` object

console.log("Table address from cluster:", lookupTableAccount.key.toBase58());
```

```py Python
account = (await client.get_account_info(lookup_table_address)).value
lookup_table = AddressLookupTable.deserialize(account.data)
print("Table address from cluster:", lookup_table_address)
```

```go Go
lookupTable, err := lookup.GetAddressLookupTable(ctx, client, lookupTableAddress)
if err != nil {
	panic(err)
}
fmt.Println("Table address from cluster:", lookupTableAddress)
```

</CodeGroup>

Our `lookupTableAccount` variable will now be an `AddressLookupTableAccount`
object which we can parse to read the listing of all the addresses stored on
chain in the lookup table:

<CodeGroup>

```js title="Web3.js (legacy)"
// loop through and parse all the addresses stored in the table
for (let i = 0; i < lookupTableAccount.state.addresses.length; i++) {
  const address = lookupTableAccount.state.addresses[i];
  console.log(i, address.toBase58());
}
```

```py Python
for i, address in enumerate(lookup_table.addresses):
    print(i, address)
```

```go Go
for i, address := range lookupTable.Addresses {
	fmt.Println(i, address)
}
```

</CodeGroup>

## How to use an address lookup table in a transaction

After you have created your lookup table, and stored your needed address on
chain (via extending the lookup table), you can create a `v0` transaction to
utilize the onchain lookup capabilities.

Just like older `legacy` transactions, you can create all the
[instructions](/developers/docs/references/terminology#instruction) your transaction will
execute onchain. You can then provide an array of these instructions to the
[Message](/developers/docs/references/terminology#message) used in the `v0` transaction.

> NOTE: The instructions used inside a `v0` transaction can be constructed using
> the same methods and functions used to create the instructions in the past.
> There is no required change to the instructions used involving an Address
> Lookup Table.

<CodeGroup>

```js title="Web3.js (legacy)"
// Assumptions:
// - `arrayOfInstructions` has been created as an `array` of `TransactionInstruction`
// - we are using the `lookupTableAccount` obtained above

// construct a v0 compatible transaction `Message`
const messageV0 = new web3.TransactionMessage({
  payerKey: payer.publicKey,
  recentBlockhash: blockhash,
  instructions: arrayOfInstructions // note this is an array of instructions
}).compileToV0Message([lookupTableAccount]);

// create a v0 transaction from the v0 message
const transactionV0 = new web3.VersionedTransaction(messageV0);

// sign the v0 transaction using the file system wallet we created named `payer`
transactionV0.sign([payer]);

// send and confirm the transaction
// (NOTE: There is NOT an array of Signers here; see the note below...)
const txid = await web3.sendAndConfirmTransaction(connection, transactionV0);

console.log(
  `Transaction: https://explorer.solana.com/tx/${txid}?cluster=devnet`
);
```

```py Python
# New addresses become usable one slot after they are added.
await asyncio.sleep(2)

lookup_table_account = AddressLookupTableAccount(
    lookup_table_address, list(lookup_table.addresses)
)
instructions = [
    transfer(
        TransferParams(
            from_pubkey=payer.pubkey(), to_pubkey=recipient, lamports=1_000_000
        )
    )
]

blockhash = (await client.get_latest_blockhash()).value.blockhash
message = MessageV0.try_compile(
    payer.pubkey(), instructions, [lookup_table_account], blockhash
)
transaction = VersionedTransaction(message, [payer])

signature = (await client.send_transaction(transaction)).value
print("Transaction:", signature)
```

```go Go
recent, err := client.GetLatestBlockhash(ctx, rpc.CommitmentConfirmed)
if err != nil {
	panic(err)
}
tx, err := solana.NewTransaction(
	[]solana.Instruction{
		system.NewTransferInstruction(1_000_000, payer.PublicKey(), recipient).Build(),
	},
	recent.Value.Blockhash,
	solana.TransactionPayer(payer.PublicKey()),
	// Passing the table makes this a v0 transaction that loads `recipient` from it.
	solana.TransactionAddressTables(map[solana.PublicKey]solana.PublicKeySlice{
		lookupTableAddress: lookupTable.Addresses,
	}),
)
if err != nil {
	panic(err)
}
tx.Sign(signer)

sig, err := client.SendTransactionWithOpts(ctx, tx, rpc.TransactionOpts{PreflightCommitment: rpc.CommitmentConfirmed})
if err != nil {
	panic(err)
}
fmt.Println("Transaction:", sig)
```

</CodeGroup>

> NOTE: When sending a `VersionedTransaction` to the cluster, it must be signed
> BEFORE calling the `sendAndConfirmTransaction` method. If you pass an array of
> `Signer` (like with `legacy` transactions) the method will trigger an error.

## More Resources

- Read the [proposal](https://docs.anza.xyz/proposals/versioned-transactions)
  for Address Lookup Tables and Versioned transactions
- [Example Rust program using Address Lookup Tables](https://github.com/TeamRaccoons/address-lookup-table-multi-swap)
