Wagmi is a React-based library designed to make working with Ethereum simpler. It provides hooks to manage wallet connections, read from and write to smart contracts, and handle blockchain events. By using wagmi, you can easily interact with the Ethereum blockchain and focus on building your dApp.
Prerequisites
Before diving into code, make sure you have the following:
- Basic understanding of React: The guide assumes you are familiar with React and hooks.
- MetaMask or another Ethereum wallet: You need a wallet to interact with the blockchain.
Step 1: Install wagmi
npm install wagmi
Step 2: Configure wagmi Client
import Messages from '@/utils/messages';
import { cookieStorage, createConfig, createStorage, http } from 'wagmi';
import { sepolia } from 'wagmi/chains'
import { walletConnect } from 'wagmi/connectors';
// Get projectId from this site https://cloud.walletconnect.com
export const projectId = process.env.PROJECT_ID || '';
if (!projectId) console.error("Wagmi project id not found");
const metadata = {
name: 'Testing',
description: 'Testing',
url: 'https://web3modal.com', // origin must match your domain & subdomain
icons: ['https://avatars.testing.com'],
};
// Create wagmiConfig
export const wagmiConfig = createConfig({
chains: [sepolia],
transports: {
[sepolia.id]: http(),
},
connectors: [walletConnect({ projectId, metadata, showQrModal: false })],
ssr: true,
storage: createStorage({ storage: cookieStorage, }),
});
Step 3: Create Web3ModalProvider for Wallet Connections and Data Fetching
'use client';
import { ReactNode } from 'react';
import { createWeb3Modal } from '@web3modal/wagmi/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { projectId, wagmiConfig } from '@/config/wagmi-config';
import { State, WagmiProvider } from 'wagmi';
const queryClient = new QueryClient();
if (!projectId) console.error('Project ID is not defined');
createWeb3Modal({
wagmiConfig: wagmiConfig,
projectId,
enableAnalytics: true,
enableOnramp: true,
});
export default function Web3ModalProvider({ children, initialState }: { children: ReactNode; initialState?: State }) {
return (
<WagmiProvider config={wagmiConfig} initialState={initialState}>
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
</WagmiProvider>
);
}
Step 4: Now Provide to Root File
import { wagmiConfig } from '@/config/wagmi-config';
import Web3ModalProvider from '@/context/web3-context';
import { cookieToInitialState } from 'wagmi';
const initialState = cookieToInitialState(wagmiConfig);
function App() {
return (
<Web3ModalProvider initialState={initialState}>
{/* Your components go here */}
</Web3ModalProvider>
);
}
export default App;
Connect and Disconnect Account
import { useAccount, useConnect, useDisconnect } from 'wagmi';
import { InjectedConnector } from 'wagmi/connectors/injected';
function ConnectButton() {
const { address, isConnected } = useAccount();
const { connect } = useConnect({
connector: new InjectedConnector(),
});
const { disconnect } = useDisconnect();
if (isConnected) {
return (
<div>
<p>Connected to {address}</p>
<button onClick={() => disconnect()}>Disconnect</button>
</div>
);
}
return <button onClick={() => connect()}>Connect Wallet</button>;
}
export default ConnectButton;
Get User Connected Wallet Balance
const { data: nativeCurrencyBalance } = useBalance({
address: '0xUserWalletAddress',
query: {
structuralSharing: false,
},
});
const { data: erc20CurrencyBalance } = useBalance({
address: '0xUserWalletAddress',
token: "0xadderc20currencytokens",
query: {
structuralSharing: false,
},
});
- Native Currency Balance: The first useBalance hook retrieves the balance of the native currency (e.g., ETH, BNB, etc.) for the wallet address.
- ERC-20 Token Balance: The second useBalance hook fetches the balance of a specific ERC-20 token from a token for the same wallet address. This would retrieve the balance of a token like USDT or DAI for the given address.
Reading Data from Smart Contracts
Reading data from a smart contract is a common requirement, such as checking a user's balance or querying contract details. wagmi provides the readContract function for this purpose. Here’s how you can use it:
import { useContractRead } from 'wagmi';
const contractConfig = {
address: '0xYourContractAddress',
abi: [
// Replace with your contract's ABI
"function balanceOf(address owner) view returns (uint256)"
],
};
function Balance({ address }) {
const { data, isError, isLoading } = useContractRead({
...contractConfig,
functionName: 'balanceOf',
args: [address],
});
if (isLoading) return <div>Loading...</div>;
if (isError) return <div>Error fetching balance</div>;
return <div>Balance: {data} ETH</div>;
}
export default Balance;
Writing to a Smart Contract
Writing data to a smart contract, such as sending tokens or making a transaction, is as straightforward as reading data. You use wagmi's writeContract function for this purpose.
import { useContractWrite, usePrepareContractWrite } from 'wagmi';
import { ethers } from 'ethers';
const contractConfig = {
address: '0xYourContractAddress',
abi: [
"function transfer(address to, uint256 amount) returns (bool)"
],
};
function TransferTokens({ toAddress, amount }) {
const { writeContract, data: hash, error } = useWriteContract();
const handleOnClick = async()=>{
const transfer = await writeContract({
....contractConfig,
functionName: 'transfer',
args: [toAddress, ethers.utils.parseEther(amount)],
value: ethers.utils.parseEther(amount),
});
return transfer;
}
return (
<button onClick={() => handleOnClick()}>Transfer {amount} ETH</button>
);
}
export default TransferTokens;
No comments:
Post a Comment