Fetching data from smart contracts

Smart contracts contain relevant information to applications built on top of blockchains that can run the Ethereum Virtual Machine. Some of the information in these contracts can be exposed in the form of View functions that do not need gas or fees to be executed. Now we will explore how to get that information in Next.js

Instanciating a connection to the smart contract

A first step needed to contact these smart contracts via RPC is to instanciate a connection with them using a library like Ethers.js. There are also convenient libraries like Typechain to help in this process.

The ABI contains information about the available function and can be obtained through Etherscan. We will use the Bored Ape Yatch Club popular NFT contract.

import abi from '../lib/BAYC.abi.json'

const contractAddress = '0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D'

const contract = new ethers.Contract(contractAddress, abi)

Fetching the data

This can now be used in getStaticProps orgetServerSideProps to pre-render the contract information, or client-side with SWR, which might be better for active contracts with a lot of usage.

// Server side
export async function getStaticProps() {
  const contractName = await contract.name()

  return {
    revalidate: 3600,
    props: {
      contractName,
    },
  }
}

// with SWR
const { data } = useSWR('name', () => contract.name())

That's it! Now if we use the contractName prop its value should be:

BoredApeYachtClub