SendLegacyTransaction.tsx 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { Button } from '@mui/material';
  2. import { useConnection, useWallet } from '@solana/wallet-adapter-react';
  3. import type { TransactionSignature } from '@solana/web3.js';
  4. import { PublicKey, TransactionMessage, VersionedTransaction } from '@solana/web3.js';
  5. import React, { useCallback, type FC } from 'react';
  6. import { useNotify } from './useNotify';
  7. export const SendLegacyTransaction: FC = () => {
  8. const { connection } = useConnection();
  9. const { publicKey, sendTransaction, wallet } = useWallet();
  10. const notify = useNotify();
  11. const supportedTransactionVersions = wallet?.adapter.supportedTransactionVersions;
  12. const onClick = useCallback(async () => {
  13. let signature: TransactionSignature | undefined = undefined;
  14. try {
  15. if (!publicKey) throw new Error('Wallet not connected!');
  16. if (!supportedTransactionVersions) throw new Error("Wallet doesn't support versioned transactions!");
  17. if (!supportedTransactionVersions.has('legacy'))
  18. throw new Error("Wallet doesn't support legacy transactions!");
  19. const {
  20. context: { slot: minContextSlot },
  21. value: { blockhash, lastValidBlockHeight },
  22. } = await connection.getLatestBlockhashAndContext();
  23. const message = new TransactionMessage({
  24. payerKey: publicKey,
  25. recentBlockhash: blockhash,
  26. instructions: [
  27. {
  28. data: Buffer.from('Hello, from the Solana Wallet Adapter example app!'),
  29. keys: [],
  30. programId: new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),
  31. },
  32. ],
  33. });
  34. const transaction = new VersionedTransaction(message.compileToLegacyMessage());
  35. signature = await sendTransaction(transaction, connection, { minContextSlot });
  36. notify('info', 'Transaction sent:', signature);
  37. await connection.confirmTransaction({ blockhash, lastValidBlockHeight, signature });
  38. notify('success', 'Transaction successful!', signature);
  39. } catch (error: any) {
  40. notify('error', `Transaction failed! ${error?.message}`, signature);
  41. }
  42. }, [publicKey, supportedTransactionVersions, connection, sendTransaction, notify]);
  43. return (
  44. <Button
  45. variant="contained"
  46. color="secondary"
  47. onClick={onClick}
  48. disabled={!publicKey || !supportedTransactionVersions?.has('legacy')}
  49. >
  50. Send Legacy Transaction (devnet)
  51. </Button>
  52. );
  53. };