What is the best practice to handle multiple transaction to sign and send at once with one popup of phantom wallet ?
1 Answer
In Solana, a Transaction
can contain multiple instructions
.
Here is an example of signing 2 instructions
, 1 for adding compute budget, and another calling an Anchor program in same transaction.
import {
Connection,
PublicKey,
SYSVAR_CLOCK_PUBKEY,
Transaction,
ComputeBudgetProgram,
sendAndConfirmTransaction,
} from '@solana/web3.js'
import { useAnchorWallet } from '@solana/wallet-adapter-react'
...
const wallet = useAnchorWallet()
...
// create Transaction
const transaction = new Transaction();
// create add compute budget Instruction
const additionalComputeBudgetInstruction =
ComputeBudgetProgram.requestUnits({
units: 1400000,
additionalFee: 0,
});
// create anchor instruction
const tx = program.instruction.initialize(
{
accounts: {
payer: wallet.publicKey,
clock: SYSVAR_CLOCK_PUBKEY,
systemProgram,
},
}
)
// add instructions to transaction
transaction.add(additionalComputeBudgetInstruction)
transaction.add(tx)
// sign transaction
const signature = wallet.signTransaction(transaction)
console.log('Your transaction signature', signature)
-
1Thanks, I need to sign with the Transaction instance instead of TransactionInstruction instance– AslamCommented Aug 22, 2022 at 9:20
-
1No problem, If I answered your question, please mark this as answered and upvote it . Thank you :)) solana.stackexchange.com/help/privileges/vote-up– vicyynCommented Aug 22, 2022 at 9:42
-
Sure, also please let me know, do I need to execute sendRawTransaction on each signed transaction or it can be possible at once ?– AslamCommented Aug 22, 2022 at 10:59
-
you have to sign for each yeah, you can create a function that takes a list of transactions and then loops through all of them and run
sendRawTransaction
But there's no implicit implementation in Solana.– vicyynCommented Aug 22, 2022 at 12:51