Build a transaction
Last updated:
First we need to make a transaction message.
import { createTransactionMessage } from "@solana/transaction-messages";
let message = createTransactionMessage({ version: 0 });
The idea of a message vs a transaction can be confusing. In Kit, a TransactionMessage
does not actually become a Transaction
until its compiled.
Then usually we want to add a fee payer
import { address } from "@solana/addresses";
import { setTransactionMessageFeePayer } from "@solana/transaction-messages";
const myAddress = address("mpngsFd4tmbUfzDYJayjKZwZcaR7aWb2793J6grLsGu");
message = setTransactionMessageFeePayer(myAddress, message);
For the transaction to land on-chain we need to provide a recent blockhash
import { setTransactionMessageLifetimeUsingBlockhash } from "@solana/transaction-messages";
const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();
const message = setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, message);
Then we can add our instructions:
import { appendTransactionMessageInstruction } from "@solana/transaction-messages";
const memoTransaction = appendTransactionMessageInstruction(
{
data: new TextEncoder().encode("Hello world!"),
programAddress: address("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),
},
message,
);
So we have a bunch of instruction adding methods:
appendTransactionMessageInstruction
appendTransactionMessageInstructions
prependTransactionMessageInstruction
prependTransactionMessageInstructions
Usually we are not doing this one step at a time, instead we build up transactions through a series of functions we pipe
through:
import { pipe } from "@solana/functional";
import {
appendTransactionMessageInstruction,
createTransactionMessage,
setTransactionMessageFeePayer,
setTransactionMessageLifetimeUsingBlockhash,
} from "@solana/transaction-messages";
const transferTransactionMessage = pipe(
createTransactionMessage({ version: 0 }),
m => setTransactionMessageFeePayer(myAddress, m),
m => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, m),
m => appendTransactionMessageInstruction(getTransferSolInstruction({ source, destination, amount }), m),
);