SendTransaction.tsx 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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, Transaction, TransactionInstruction } from '@solana/web3.js';
  5. import React, { useCallback, type FC } from 'react';
  6. import { useNotify } from './useNotify';
  7. export const SendTransaction: FC = () => {
  8. const { connection } = useConnection();
  9. const { publicKey, sendTransaction } = useWallet();
  10. const notify = useNotify();
  11. const onClick = useCallback(async () => {
  12. let signature: TransactionSignature | undefined = undefined;
  13. try {
  14. if (!publicKey) throw new Error('Wallet not connected!');
  15. const {
  16. context: { slot: minContextSlot },
  17. value: { blockhash, lastValidBlockHeight },
  18. } = await connection.getLatestBlockhashAndContext();
  19. const transaction = new Transaction({
  20. feePayer: publicKey,
  21. recentBlockhash: blockhash,
  22. }).add(
  23. new TransactionInstruction({
  24. data: Buffer.from('Hello, from the Solana Wallet Adapter example app!'),
  25. keys: [],
  26. programId: new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),
  27. })
  28. );
  29. signature = await sendTransaction(transaction, connection, { minContextSlot });
  30. notify('info', 'Transaction sent:', signature);
  31. await connection.confirmTransaction({ blockhash, lastValidBlockHeight, signature });
  32. notify('success', 'Transaction successful!', signature);
  33. } catch (error: any) {
  34. notify('error', `Transaction failed! ${error?.message}`, signature);
  35. }
  36. }, [publicKey, connection, sendTransaction, notify]);
  37. return (
  38. <Button variant="contained" color="secondary" onClick={onClick} disabled={!publicKey}>
  39. Send Transaction (devnet)
  40. </Button>
  41. );
  42. };