top of page

Connect Wagmi to localhost: testing dapps with Hardhat and Anvil

This brief tutorial demonstrates how you can use Wagmi + React to interact with your local Ethereum node, either through Anvil (Foundry) or Hardhat Network.


Both Hardhat and Foundry comes with their own built-in local Ethereum node. To use them, make sure you have either one of them installed.


Here’s a quick outline:

  • Anvil: Set up local ethereum node

  • Hardhat: Set up local ethereum node

  • Wagmi + React: Connect to local ethereum node

Anvil: Set up local ethereum node

Run a Local Ethereum Node with Foundry’s Anvil.

Required: Install Foundry

  1. Initialize Foundry forge init

  2. Run anvil in your terminal

                            (_) | |
      __ _   _ __   __   __  _  | |
     / _` | | '_ \  \ \ / / | | | |
    | (_| | | | | |  \ V /  | | | |
     \__,_| |_| |_|   \_/   |_| |_|

    0.2.0 (6676e81 2023-08-22T00:28:14.836672000Z)
    https://github.com/foundry-rs/foundry
(some text...)

Listening on 127.0.0.1:8545

Allow anvil to keep running in the background.


Hardhat: Set up local ethereum node

Run a Local Ethereum Node with Hardhat Network.


Note: You should not run hardhat and anvil at the same time. You should just use whichever development framework you prefer.


Required: Install Hardhat

  1. Initialize Hardhat Project npx hardhat

  2. Run npx hardhat node Started HTTP and WebSocket JSON-RPC server at http://127.0.0.1:8545/ (some text...) WARNING: These accounts, and their private keys, are publicly known. Any funds sent to them on Mainnet or any other live network WILL BE LOST.

Wagmi + React: Connect to local ethereum node

Create your Next.js project

npx create-next-app@latest

Select [yes] for the following:

  • Typescript

  • App Router (recommended)

Install wagmi and viem

npm i wagmi viem
pnpm i wagmi viem
yarn add wagmi viem

In your app directory, create a new file providers.tsx. We’ll be configuring our Wagmi Client into this file.

app
├── globals.css
├── layout.tsx
├── page.tsx 
└── providers.tsx (new)

providers.tsx

We’ll wrap the WagmiConfig component around the children prop, where children represents any React elements or components that are to be nested inside the WagmiConfig.

"use client"; // Wagmi is a client side component
import "./globals.css";
import { WagmiConfig, createConfig, configureChains } from "wagmi";
import { publicProvider } from "wagmi/providers/public";
import { localhost } from 'wagmi/chains'//Configure the chain and the RPC provider. Note that we've added localhost hereconst { chains, publicClient, webSocketPublicClient } = configureChains(
  [localhost],
  [publicProvider()]
);

//Instantiate a wagmi config and pass the results of configureChains.const config = createConfig({
  autoConnect: true,
  publicClient,
  webSocketPublicClient,
});

// Create a WagmiConfig, pass config and wrap it around the children.export default function Provider({
  children,
}: {
  children: React.ReactNode;
}) {
  return <WagmiConfig config={config}>{children}</WagmiConfig>;
}

layout.tsx

Import the Provider Component and pass children as it’s arguement. This way our entire React app is able to access the Ethereum network through the configured Wagmi connection.

import './globals.css'import type { Metadata } from 'next'
import { Inter } from 'next/font/google'
import Provider from './providers'
const inter = Inter({ subsets: ['latin'] })

export const metadata: Metadata = {
  title: 'Create Next App',
  description: 'Generated by create next app',
}

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en"><body className={inter.className}>
				{/* Our react app is now wrapped with Wagmi */}	
				<Provider children={children}/></body></html>
  )
}

Page.tsx

We’ll create a simple button that fetches an addresses’ balance formatted in WEI.

"use client"; // Wagmi is a Client Component
import { fetchBalance } from "@wagmi/core";

export default function Home() {
	// Function to get the balance of an address
  const getBalance = async () => {
		// The fetchBalance function returns an array. // We only want the value object, which is the balance in WEI.
    const balance = await fetchBalance({
      address: "0x976EA74026E726554dB657fA54763abd0C3a0aa9",
    });
		// Shows an alert of the address balance in WEI
    alert("This is 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266 balance " + balance.value);

  };
  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-24">
			{/* Button to call the function */}	
      <button onClick={getBalance} className="border p-4 rounded-3xl">
        getBalance
      </button></main>
  );
}

Your website should look like this now.


wagmi localhost

If you press the button this should pop up:

wagmi getting balance from localhost


We can see the local node receiving the eth_getBalance rpc call in the Anvil screenshot below

anvil rpc log

And if you are running hardhat you will see

hardhat rpc log

Authorship

This article was co-authored by Aymeric Taylor (LinkedIn, Twitter), a research intern at RareSkills.


Learn more with RareSkills

This tutorial is used in our Dapp Bootcamp

1,867 views0 comments

Comments


bottom of page