|
| 1 | +'use client'; |
| 2 | +import { useWallet } from '@solana/wallet-adapter-react'; |
| 3 | +import { useWalletModal } from '@solana/wallet-adapter-react-ui'; |
| 4 | +import { Connection, VersionedTransaction } from '@solana/web3.js'; |
| 5 | +import { useMemo } from 'react'; |
| 6 | +import { ActionConfig } from '../api'; |
| 7 | + |
| 8 | +/** |
| 9 | + * Hook to create an action adapter using solana's wallet adapter. |
| 10 | + * |
| 11 | + * Be sure to call `action.setAdapter` with the to update the adapter, every time the instance updates. |
| 12 | + * |
| 13 | + * @param rpcUrlOrConnection |
| 14 | + * @see {Action} |
| 15 | + */ |
| 16 | +export function useActionAdapter(rpcUrlOrConnection: string | Connection) { |
| 17 | + const wallet = useWallet(); |
| 18 | + const walletModal = useWalletModal(); |
| 19 | + |
| 20 | + const finalConnection = useMemo(() => { |
| 21 | + return typeof rpcUrlOrConnection === 'string' |
| 22 | + ? new Connection(rpcUrlOrConnection, 'confirmed') |
| 23 | + : rpcUrlOrConnection; |
| 24 | + }, [rpcUrlOrConnection]); |
| 25 | + |
| 26 | + const adapter = useMemo(() => { |
| 27 | + return new ActionConfig(finalConnection, { |
| 28 | + connect: async () => { |
| 29 | + try { |
| 30 | + await wallet.connect(); |
| 31 | + } catch { |
| 32 | + walletModal.setVisible(true); |
| 33 | + return null; |
| 34 | + } |
| 35 | + |
| 36 | + return wallet.publicKey?.toBase58() ?? null; |
| 37 | + }, |
| 38 | + signTransaction: async (txData: string) => { |
| 39 | + try { |
| 40 | + const tx = await wallet.sendTransaction( |
| 41 | + VersionedTransaction.deserialize(Buffer.from(txData, 'base64')), |
| 42 | + finalConnection, |
| 43 | + ); |
| 44 | + return { signature: tx }; |
| 45 | + } catch { |
| 46 | + return { error: 'Signing failed.' }; |
| 47 | + } |
| 48 | + }, |
| 49 | + }); |
| 50 | + }, [finalConnection, wallet, walletModal]); |
| 51 | + |
| 52 | + return { adapter }; |
| 53 | +} |
0 commit comments