Skip to main content
  • React
  • React Native
  • JavaScript
React
import { isSolanaWallet } from '@dynamic-labs/solana';
import { useDynamicContext } from '@dynamic-labs/sdk-react-core';
import { Connection, PublicKey, SystemProgram, TransactionMessage, VersionedTransaction, VersionedTransactionResponse } from "@solana/web3.js";

const { primaryWallet } = useDynamicContext();

if(!primaryWallet || !isSolanaWallet(primaryWallet)) {
  return;
}

const connection: Connection = await primaryWallet.getConnection();

const fromKey = new PublicKey(primaryWallet.address);
const toKey = new PublicKey(address);
const amountInLamports = Number(amount) * 1000000000;

const instructions = [
  SystemProgram.transfer({
    fromPubkey: fromKey,
    lamports: amountInLamports,
    toPubkey: toKey,
  }),
];

const blockhash = await connection.getLatestBlockhash();

// create v0 compatible message
const messageV0 = new TransactionMessage({
  instructions,
  payerKey: fromKey,
  recentBlockhash: blockhash.blockhash,
}).compileToV0Message();

const transferTransaction = new VersionedTransaction(messageV0);

const signer = await primaryWallet.getSigner();

await signer
  .signAndSendTransaction(transferTransaction)
  .then((res: any) => {
    console.log(
      `Transaction successful: https://solscan.io/tx/${res.signature}?cluster=devnet`,
    );
  })
  .catch((reason: any) => {
    console.error(reason);
  });

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.
  • React Native
React Native
import { dynamicClient } from '<path to client file>'
import {
  LAMPORTS_PER_SOL,
  PublicKey,
  SystemProgram,
  TransactionMessage,
  VersionedTransaction,
} from '@solana/web3.js'

const simulateSolanaVersionedTransaction = async (to: string, amountSol: number) => {
  const connection = dynamicClient.solana.getConnection()

  const { blockhash } = await connection.getLatestBlockhash()
  const amountInLamports = Math.round(amountSol * LAMPORTS_PER_SOL)
  const fromKey = new PublicKey(dynamicClient.wallets.primary.address)
  const toKey = new PublicKey(to)

  const instructions = [
    SystemProgram.transfer({
      fromPubkey: fromKey,
      lamports: amountInLamports,
      toPubkey: toKey,
    }),
  ]

  const messageV0 = new TransactionMessage({
    instructions,
    payerKey: fromKey,
    recentBlockhash: blockhash,
  }).compileToV0Message()

  const transaction = new VersionedTransaction(messageV0)

  const simulationResult = await dynamicClient.solana.simulateSVMTransaction({
    transaction,
    type: 'SignTransaction',
  })

  console.log('Simulation result:', simulationResult)
  return simulationResult
}