import { dynamicClient } from '<path to client file>'
import { PublicKey, SystemProgram, Transaction } from '@solana/web3.js'
const wallet = dynamicClient.wallets.primary
if (!wallet) {
// user is not connected yet
} else {
const connection = dynamicClient.solana.getConnection()
const signer = dynamicClient.solana.getSigner({ wallet })
const fromKey = new PublicKey(wallet.address)
const toKey = new PublicKey('<destinationAddress>')
const amountInLamports = 1_000_000_000 // 1 SOL
const tx = new Transaction().add(
SystemProgram.transfer({ fromPubkey: fromKey, toPubkey: toKey, lamports: amountInLamports })
)
const { blockhash } = await connection.getLatestBlockhash()
tx.recentBlockhash = blockhash
tx.feePayer = fromKey
const { signature } = await signer.signAndSendTransaction(tx)
console.log('Successful transaction signature:', signature)
}
Simulate a Transaction
Before sending a transaction, you can simulate it to preview the effects and validate that it will succeed. Transaction simulation shows all asset transfers involved in the transaction.
Transaction simulation uses the currently selected primary wallet. Make sure the user has a wallet connected before attempting to simulate a transaction.
import { dynamicClient } from '<path to client file>'
import { PublicKey, SystemProgram, Transaction, LAMPORTS_PER_SOL } from '@solana/web3.js'
const simulateSolanaLegacyTransaction = async (to: string, amountSol: number) => {
const connection = dynamicClient.solana.getConnection()
const fromKey = new PublicKey(dynamicClient.wallets.primary.address)
const toKey = new PublicKey(to)
const amountInLamports = Math.round(amountSol * LAMPORTS_PER_SOL)
const tx = new Transaction().add(
SystemProgram.transfer({ fromPubkey: fromKey, toPubkey: toKey, lamports: amountInLamports })
)
const { blockhash } = await connection.getLatestBlockhash()
tx.recentBlockhash = blockhash
tx.feePayer = fromKey
const simulationResult = await dynamicClient.solana.simulateSVMTransaction({
transaction: tx,
type: 'SignTransaction',
})
console.log('Simulation result:', simulationResult)
return simulationResult
}