- Kit
- Web3.js v3
- Rust
- Python
- Go
- Web3.js (legacy)
Kit
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);
Output from a local Surfpool network
Output
Transaction Signature: f9zS5dzfVGYvPWZqZRRJjGnSE8scz3hRLosiGjZyGYnfUbF3hdghAJURJvHWTiAFSZfydWfxNm1HY64So479UD9
Web3.js v3
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);
Output from a local Surfpool network
Output
Transaction Signature: MwUSzZVqLLpRCvmGDGHhbtGvD8T2Cv5wEEXmkcwfwomCksdGByWCExWWRMoBfASiLRE2q6NzuzoZBrSvTWDR2Z6
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(())
}
Output from a local Surfpool network
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
Python
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())
Output from a local Surfpool network
Output
Transaction Signature: Lwhdj17PT2sFwikXZPuEtzDuFznCdPK5mzmYAtZR1w67K3UqJm1ymE7nhGVT441Mh69meAmKd9Gqvs5f5T5gbCf
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)
}
Output from a local Surfpool network
Output
Transaction Signature: 7TFKkiXHCj5o9nCahfSdZD6wuyPhmDfuByi6xXVcqTpaANH8ygNXsW3GXtJ872hipCEns2GWz6qZfcHJt4zA2fi
Web3.js (legacy)
@solana/web3.js 1.x is no longer actively maintainedIt receives critical fixes only. Use Kit for new code. To migrate existing code, follow the Kit upgrade guide, or the web3.js v3 migration guide 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.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);
Output from a local Surfpool network
Output
Transaction Signature: ZHnHKxFHcUYKrvADPMY4eiFPYCfYTYznF6LAkDtHFFCyCmnb23bp9z2TQnS6nQvuJ6qcnyfvBm69atPUTnwYrfn