In order to interact with a smart contract you will need to have one deployed in a EVM-compatible blockchain. There are several tools to help you deploy a smart contract:
We have already deployed a simple smart contract (0xEe6D291CC60d7CeD6627fA4cd8506912245c8cA4) in Sepolia Testnet for you to use. Once you compile the smart contract, you get the ABI.
The ABI is a set of rules that define how the contract’s functions can be called and how data is sent and received.
To interact with the smart contract, you need to have some tokens to pay for gas fees when writing to the contract. You can get them from this faucet, but you can also look for other options on the web.
It’s also good to know that reading from a smart contract is free.
For both SDKs, you need to declare the contract address and ABI.
// Call the function to read the smart contract and print on consoleconst handleReadSmartContract = async () => { const { data } = await readContract.refetch(); console.log("data: ", data);};// Write to the smart contract and check if the transaction is successful with useEffectconst handleWriteSmartContract = () => { writeContract({ address: storageSC, abi: storageABI, functionName: "store", args: [123n], });};// useEffect to print the success message when the contract is writtenuseEffect(() => { if (isSuccess) { console.log("contract write success"); }}, [isSuccess]);
Start by importing the libraries needed to interact:
Copy
import { useAppKitProvider } from "@reown/appkit/react";import { Contract, BrowserProvider } from "ethers";import type { Provider } from "@reown/appkit/react";
// get the data from the smart contract and print on consoleconst handleReadSmartContract = async () => { const ethersProvider = new BrowserProvider(walletProvider); const signer = await ethersProvider.getSigner(); const contract = new Contract(storageSC, storageABI, signer); const data = await contract.retrieve(); console.log("data: ", data);};// write to the smart contract and print on consoleconst handleWriteSmartContract = async () => { const ethersProvider = new BrowserProvider(walletProvider); const signer = await ethersProvider.getSigner(); const contract = new Contract(storageSC, storageABI, signer); const data = await contract.store(1n); console.log("data: ", data);};
By following this guide, you’ve learned how to integrate Reown AppKit with Wagmi or Ethers to interact with a smart contract.
With very few lines of code you can read and write to a smart contract.
Keep exploring AppKit to enhance your dApp’s functionality and user experience!