|
| 1 | +import type { Dispatch, SetStateAction } from 'react'; |
| 2 | +// ANCHOR: setup-imports |
| 3 | +import { createWalletClient, custom } from 'viem'; |
| 4 | +import { |
| 5 | + // zksync, |
| 6 | + zksyncSepoliaTestnet, |
| 7 | + // zksyncInMemoryNode, |
| 8 | + // zksyncLocalNode |
| 9 | +} from 'viem/chains'; |
| 10 | +import { eip712WalletActions, getGeneralPaymasterInput } from 'viem/zksync'; |
| 11 | +// ANCHOR_END: setup-imports |
| 12 | +import greeterAbi from '../utils/Greeter.json'; |
| 13 | +import { publicClient } from '../utils/client'; |
| 14 | + |
| 15 | +const Paymaster = ({ update }: { update: Dispatch<SetStateAction<number>> }) => { |
| 16 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 17 | + const window: any = globalThis.window; |
| 18 | + |
| 19 | + async function writeToContract() { |
| 20 | + try { |
| 21 | + // ANCHOR: client |
| 22 | + // Initialize and extend the wallet client |
| 23 | + const client = createWalletClient({ |
| 24 | + chain: zksyncSepoliaTestnet, |
| 25 | + transport: custom(window.ethereum!), |
| 26 | + }).extend(eip712WalletActions()); |
| 27 | + // ANCHOR_END: client |
| 28 | + |
| 29 | + const [account] = await window.ethereum.request({ method: 'eth_requestAccounts' }); |
| 30 | + if (!account) { |
| 31 | + console.error('User account is not set. Please connect your wallet.'); |
| 32 | + return; |
| 33 | + } |
| 34 | + |
| 35 | + // ANCHOR: use-paymaster |
| 36 | + // Replace with your paymaster address |
| 37 | + const paymasterAddress = '0xdeAD0bD94D5975538B7678C0EaAd28d20FbFF8A7'; |
| 38 | + |
| 39 | + // Call the contract function |
| 40 | + const hash = await client.writeContract({ |
| 41 | + account, |
| 42 | + address: '0xe2e810a56672336C0Cc303E5f8156A5a56DBE150', |
| 43 | + abi: greeterAbi, |
| 44 | + functionName: 'sendMessage', |
| 45 | + args: ['ZKsync Paymaster'], |
| 46 | + paymaster: paymasterAddress, |
| 47 | + paymasterInput: getGeneralPaymasterInput({ innerInput: new Uint8Array() }), |
| 48 | + }); |
| 49 | + |
| 50 | + await publicClient.waitForTransactionReceipt({ hash }); |
| 51 | + // ANCHOR_END: use-paymaster |
| 52 | + update((prev) => prev + 1); |
| 53 | + } catch (error) { |
| 54 | + console.error('Error writing to contract:', error); |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + return ( |
| 59 | + <> |
| 60 | + <button onClick={writeToContract}>Write with Paymaster</button> |
| 61 | + </> |
| 62 | + ); |
| 63 | +}; |
| 64 | + |
| 65 | +export default Paymaster; |
0 commit comments