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

# How to Add a Memo to a Transaction

> Transactions come with metadata information about what was transacted. Learn how to add a memo to your transactions on Solana.

Any transaction can add a message making use of the SPL memo program.

<Tabs>
<Tab title="Kit">
<div className="sol-tab-label">Kit</div>

```ts
import { createClient, generateKeyPairSigner, lamports } from "@solana/kit";
import { rpcAirdrop, solanaRpc } from "@solana/kit-plugin-rpc";
import { airdropPayer, payer } from "@solana/kit-plugin-signer";
import { getAddMemoInstruction } from "@solana-program/memo";

const sender = await generateKeyPairSigner();
const LAMPORTS_PER_SOL = 1_000_000_000n;

const client = await createClient()
  .use(payer(sender))
  .use(
    solanaRpc({
      rpcUrl: "http://localhost:8899",
      rpcSubscriptionsUrl: "ws://localhost:8900",
    }),
  )
  .use(rpcAirdrop())
  .use(airdropPayer(lamports(LAMPORTS_PER_SOL)));

const memoInstruction = getAddMemoInstruction({
  memo: "Hello, world!",
});

const { context } = await client.sendTransaction([memoInstruction]);
console.log("Transaction Signature:", context.signature);
```

<div className="sol-run" data-run="cookbook/transactions/add-memo/memo" data-tab="Kit">
<div className="sol-run-bar"><button type="button" className="sol-run-btn">Run</button><span className="sol-run-note">Output from a local Surfpool network</span></div>
<div className="sol-run-out">

```text Output
Transaction Signature: f9zS5dzfVGYvPWZqZRRJjGnSE8scz3hRLosiGjZyGYnfUbF3hdghAJURJvHWTiAFSZfydWfxNm1HY64So479UD9
```

</div>
</div>

</Tab>
<Tab title="Web3.js v3">
<div className="sol-tab-label">Web3.js v3</div>

```ts highlight={33}
import {
  Connection,
  Keypair,
  LAMPORTS_PER_SOL,
  Transaction,
  sendAndConfirmTransaction,
} from "@solana/web3.js";

import { getAddMemoInstruction } from "@solana-program/memo";

// Connect to Solana cluster
const connection = new Connection("http://localhost:8899", "confirmed");

// Create keypair for the fee payer
const feePayer = await Keypair.generate();

// Request and confirm airdrop
const airdropSignature = await connection.requestAirdrop(
  feePayer.publicKey,
  LAMPORTS_PER_SOL,
);

// Get latest blockhash for confirmation
const { blockhash, lastValidBlockHeight } =
  await connection.getLatestBlockhash();
await connection.confirmTransaction({
  signature: airdropSignature,
  blockhash,
  lastValidBlockHeight,
});

// Create a memo instruction
const memoInstruction = getAddMemoInstruction({ memo: "Hello, World!" });

// Create transaction and add the memo instruction
const transaction = new Transaction().add(memoInstruction);

// Sign and send transaction
const transactionSignature = await sendAndConfirmTransaction(
  connection,
  transaction,
  [feePayer],
);
console.log("Transaction Signature: ", transactionSignature);
```

<div className="sol-run" data-run="cookbook/transactions/add-memo/memo" data-tab="Web3.js v3">
<div className="sol-run-bar"><button type="button" className="sol-run-btn">Run</button><span className="sol-run-note">Output from a local Surfpool network</span></div>
<div className="sol-run-out">

```text Output
Transaction Signature:  MwUSzZVqLLpRCvmGDGHhbtGvD8T2Cv5wEEXmkcwfwomCksdGByWCExWWRMoBfASiLRE2q6NzuzoZBrSvTWDR2Z6
```

</div>
</div>

</Tab>
<Tab title="Rust">
<div className="sol-tab-label">Rust</div>

```rust
use solana_client::{nonblocking::rpc_client::RpcClient, rpc_config::RpcTransactionConfig};
use solana_commitment_config::CommitmentConfig;
use solana_sdk::{
    native_token::LAMPORTS_PER_SOL, signature::Keypair, signer::Signer, transaction::Transaction,
};
use solana_transaction_status_client_types::{
    option_serializer::OptionSerializer, UiTransactionEncoding,
};
use spl_memo_interface::{instruction::build_memo, v3::ID as MEMO_V3_PROGRAM_ID};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let client = RpcClient::new_with_commitment(
        String::from("http://localhost:8899"),
        CommitmentConfig::confirmed(),
    );

    let signer_keypair = Keypair::new();
    let memo = String::from("Memo message to be logged in this transaction");

    let memo_ix = build_memo(
        &MEMO_V3_PROGRAM_ID,
        memo.as_bytes(),
        &[&signer_keypair.pubkey()],
    );

    let transaction_signature = client
        .request_airdrop(&signer_keypair.pubkey(), 5 * LAMPORTS_PER_SOL)
        .await?;
    loop {
        if client.confirm_transaction(&transaction_signature).await? {
            break;
        }
    }

    let mut transaction = Transaction::new_with_payer(&[memo_ix], Some(&signer_keypair.pubkey()));
    transaction.sign(&[&signer_keypair], client.get_latest_blockhash().await?);

    let signature = client.send_and_confirm_transaction(&transaction).await?;

    // Fetch the transaction details with config
    let tx_details = client
        .get_transaction_with_config(
            &signature,
            RpcTransactionConfig {
                encoding: Some(UiTransactionEncoding::Json),
                commitment: Some(CommitmentConfig::confirmed()),
                max_supported_transaction_version: Some(0),
            },
        )
        .await?;

    // Extract and display logs
    if let Some(meta) = tx_details.transaction.meta {
        if let OptionSerializer::Some(logs) = meta.log_messages {
            println!("\nTransaction Logs:");
            for log in logs {
                println!("  {}", log);
            }
        }
    }

    Ok(())
}
```

<div className="sol-run" data-run="cookbook/transactions/add-memo/memo" data-tab="Rust">
<div className="sol-run-bar"><button type="button" className="sol-run-btn">Run</button><span className="sol-run-note">Output from a local Surfpool network</span></div>
<div className="sol-run-out">

```text Output

Transaction Logs:
  Program MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr invoke [1]
  Program log: Signed by:
  Program log: 3oUYds9KwTv1qu5iGddAR3yR2dyG3p6qdq7uYZeKBq8q
  Program log: Memo (len 45)
  Program log: Memo message to be logged in this transaction
  Program MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr consumed 513 of 200000 compute units
  Program MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr success
```

</div>
</div>

</Tab>
<Tab title="Python">
<div className="sol-tab-label">Python</div>

```py
import asyncio

from solana.rpc.async_api import AsyncClient
from solana.rpc.commitment import Confirmed
from solders.instruction import Instruction
from solders.keypair import Keypair
from solders.message import MessageV0
from solders.pubkey import Pubkey
from solders.transaction import VersionedTransaction

MEMO_PROGRAM_ID = Pubkey.from_string("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr")


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

        memo_instruction = Instruction(MEMO_PROGRAM_ID, b"Hello, world!", [])

        blockhash = (await client.get_latest_blockhash()).value.blockhash
        message = MessageV0.try_compile(sender.pubkey(), [memo_instruction], [], blockhash)
        transaction = VersionedTransaction(message, [sender])

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


asyncio.run(main())
```

<div className="sol-run" data-run="cookbook/transactions/add-memo/memo" data-tab="Python">
<div className="sol-run-bar"><button type="button" className="sol-run-btn">Run</button><span className="sol-run-note">Output from a local Surfpool network</span></div>
<div className="sol-run-out">

```text Output
Transaction Signature: Lwhdj17PT2sFwikXZPuEtzDuFznCdPK5mzmYAtZR1w67K3UqJm1ymE7nhGVT441Mh69meAmKd9Gqvs5f5T5gbCf
```

</div>
</div>

</Tab>
<Tab title="Go">
<div className="sol-tab-label">Go</div>

```go
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/solana-foundation/solana-go/v2"
	"github.com/solana-foundation/solana-go/v2/programs/memo"
	"github.com/solana-foundation/solana-go/v2/rpc"
)

func main() {
	ctx := context.Background()
	client := rpc.New("http://localhost:8899")

	sender := solana.NewWallet()

	// Fund the sender so it can pay the transaction fee.
	_, err := client.RequestAirdrop(ctx, sender.PublicKey(), solana.LAMPORTS_PER_SOL, rpc.CommitmentConfirmed)
	if err != nil {
		panic(err)
	}
	time.Sleep(2 * time.Second)

	recent, err := client.GetLatestBlockhash(ctx, rpc.CommitmentConfirmed)
	if err != nil {
		panic(err)
	}

	tx, err := solana.NewTransaction(
		[]solana.Instruction{
			memo.NewMemoInstruction([]byte("Hello, world!")).Build(),
		},
		recent.Value.Blockhash,
		solana.TransactionPayer(sender.PublicKey()),
	)
	if err != nil {
		panic(err)
	}
	tx.Sign(func(solana.PublicKey) *solana.PrivateKey { return &sender.PrivateKey })

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

<div className="sol-run" data-run="cookbook/transactions/add-memo/memo" data-tab="Go">
<div className="sol-run-bar"><button type="button" className="sol-run-btn">Run</button><span className="sol-run-note">Output from a local Surfpool network</span></div>
<div className="sol-run-out">

```text Output
Transaction Signature: 7TFKkiXHCj5o9nCahfSdZD6wuyPhmDfuByi6xXVcqTpaANH8ygNXsW3GXtJ872hipCEns2GWz6qZfcHJt4zA2fi
```

</div>
</div>

</Tab>
<Tab title="Web3.js (legacy)">
<div className="sol-tab-label">Web3.js (legacy)</div>

<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 highlight={33}
import {
  Connection,
  Keypair,
  LAMPORTS_PER_SOL,
  Transaction,
  sendAndConfirmTransaction,
} from "@solana/web3.js";

import { createMemoInstruction } from "@solana/spl-memo";

// Connect to Solana cluster
const connection = new Connection("http://localhost:8899", "confirmed");

// Create keypair for the fee payer
const feePayer = Keypair.generate();

// Request and confirm airdrop
const airdropSignature = await connection.requestAirdrop(
  feePayer.publicKey,
  LAMPORTS_PER_SOL,
);

// Get latest blockhash for confirmation
const { blockhash, lastValidBlockHeight } =
  await connection.getLatestBlockhash();
await connection.confirmTransaction({
  signature: airdropSignature,
  blockhash,
  lastValidBlockHeight,
});

// Create a memo instruction
const memoInstruction = createMemoInstruction("Hello, World!");

// Create transaction and add the memo instruction
const transaction = new Transaction().add(memoInstruction);

// Sign and send transaction
const transactionSignature = await sendAndConfirmTransaction(
  connection,
  transaction,
  [feePayer],
);
console.log("Transaction Signature: ", transactionSignature);
```

<div className="sol-run" data-run="cookbook/transactions/add-memo/memo" data-tab="Web3.js (legacy)">
<div className="sol-run-bar"><button type="button" className="sol-run-btn">Run</button><span className="sol-run-note">Output from a local Surfpool network</span></div>
<div className="sol-run-out">

```text Output
Transaction Signature:  ZHnHKxFHcUYKrvADPMY4eiFPYCfYTYznF6LAkDtHFFCyCmnb23bp9z2TQnS6nQvuJ6qcnyfvBm69atPUTnwYrfn
```

</div>
</div>

</Tab>
</Tabs>
