|
| 1 | +import { EthereumProvider } from '@walletconnect/ethereum-provider' |
| 2 | +import React, { useEffect, useState } from 'react' |
| 3 | +import ReactDOM from 'react-dom/client' |
| 4 | +import { |
| 5 | + http, |
| 6 | + Address, |
| 7 | + Hash, |
| 8 | + TransactionReceipt, |
| 9 | + createPublicClient, |
| 10 | + createWalletClient, |
| 11 | + custom, |
| 12 | + parseEther, |
| 13 | + stringify, |
| 14 | +} from 'viem' |
| 15 | +import { mainnet } from 'viem/chains' |
| 16 | +import 'viem/window' |
| 17 | + |
| 18 | +const projectId = 'fdb8164b4aa07b46f14e131f5c7c5903' |
| 19 | + |
| 20 | +const provider = await EthereumProvider.init({ |
| 21 | + chains: [1], |
| 22 | + projectId, |
| 23 | + showQrModal: true, |
| 24 | +}) |
| 25 | + |
| 26 | +const publicClient = createPublicClient({ |
| 27 | + chain: mainnet, |
| 28 | + transport: http(), |
| 29 | +}) |
| 30 | +const walletClient = createWalletClient({ |
| 31 | + chain: mainnet, |
| 32 | + transport: custom(provider), |
| 33 | +}) |
| 34 | + |
| 35 | +function Example() { |
| 36 | + const [account, setAccount] = useState<Address>() |
| 37 | + const [hash, setHash] = useState<Hash>() |
| 38 | + const [receipt, setReceipt] = useState<TransactionReceipt>() |
| 39 | + |
| 40 | + const addressInput = React.createRef<HTMLInputElement>() |
| 41 | + const valueInput = React.createRef<HTMLInputElement>() |
| 42 | + |
| 43 | + const connect = async () => { |
| 44 | + await provider.connect() |
| 45 | + const [address] = await walletClient.getAddresses() |
| 46 | + setAccount(address) |
| 47 | + } |
| 48 | + |
| 49 | + const sendTransaction = async () => { |
| 50 | + if (!account) return |
| 51 | + const hash = await walletClient.sendTransaction({ |
| 52 | + account, |
| 53 | + to: addressInput.current!.value as Address, |
| 54 | + value: parseEther(valueInput.current!.value as `${number}`), |
| 55 | + }) |
| 56 | + console.log('test', hash) |
| 57 | + setHash(hash) |
| 58 | + } |
| 59 | + |
| 60 | + useEffect(() => { |
| 61 | + ;(async () => { |
| 62 | + if (hash) { |
| 63 | + const receipt = await publicClient.waitForTransactionReceipt({ hash }) |
| 64 | + setReceipt(receipt) |
| 65 | + } |
| 66 | + })() |
| 67 | + }, [hash]) |
| 68 | + |
| 69 | + if (account) |
| 70 | + return ( |
| 71 | + <> |
| 72 | + <div>Connected: {account}</div> |
| 73 | + <input ref={addressInput} placeholder="address" /> |
| 74 | + <input ref={valueInput} placeholder="value (ether)" /> |
| 75 | + <button onClick={sendTransaction}>Send</button> |
| 76 | + {receipt && ( |
| 77 | + <div> |
| 78 | + Receipt:{' '} |
| 79 | + <pre> |
| 80 | + <code>{stringify(receipt, null, 2)}</code> |
| 81 | + </pre> |
| 82 | + </div> |
| 83 | + )} |
| 84 | + </> |
| 85 | + ) |
| 86 | + return <button onClick={connect}>Connect Wallet</button> |
| 87 | +} |
| 88 | + |
| 89 | +ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render( |
| 90 | + <Example />, |
| 91 | +) |
0 commit comments