Since VersionedTransaction
are a fairly new, the docs and content for them is still in the works of being created. But, here is a snippet from an upcoming doc that explains how to create a VersionedTransaction
with web3.js:
const web3 = require("@solana/web3.js");
// connect to the cluster and get the minimum rent for rent exempt status
const connection = new web3.Connection(web3.clusterApiUrl("devnet"));
let minRent = await connection.getMinimumBalanceForRentExemption(0);
let blockhash = await connection
.getLatestBlockhash()
.then((res) => res.blockhash);
Create an array
of all the instructions
you desire to send in your transaction. In this example below, we are creating a simple SOL transfer instruction:
// create an array with your desires `instructions`
const instructions = [
web3.SystemProgram.transfer({
fromPubkey: payer.publicKey,
toPubkey: toAccount.publicKey,
lamports: minRent,
}),
];
Next, construct a MessageV0
formatted transaction message with your desired instructions
:
// create v0 compatible message
const messageV0 = new web3.TransactionMessage({
payerKey: payer.publicKey,
recentBlockhash: blockhash,
instructions,
}).compileToV0Message();
Then, create a new VersionedTransaction
, passing in our v0 compatible message:
const transaction = new web3.VersionedTransaction(messageV0);
// sign your transaction with the required `Signers`
transaction.sign([payer]);
You can sign the transaction by either:
- passing an array of
signatures
into the VersionedTransaction
method, or
- call the
transaction.sign()
method, passing an array of the required Signers
NOTE:
After calling the transaction.sign()
method, all the previous transaction signatures
will be fully replaced by new signatures created from the provided in Signers
.
After your VersionedTransaction
has been signed by all required accounts, you can send it to the cluster and await
the response.
// send our v0 transaction to the cluster
const txid = await connection.sendTransaction(transaction);
console.log(`https://explorer.solana.com/tx/${txid}?cluster=devnet`);
NOTE:
Unlike legacy
transactions, sending a VersionedTransaction
via sendTransaction
does NOT support transaction signing via passing in an array of Signers
as the second parameter. You will need to sign the transaction before calling connection.sendTransaction()
.