How to set up Hardhat with Typescript support along with React & Typescript?

Viewed 326

I was wondering if anyone had create a contract in hardhat and generated & compiled the contract with typechain. Taking the compiled contract and used it in a react app.

I am able to write a contract & generate the necessary files fine using npx hardhat and choosing the option with typescript. npx hardhat compile generates the necessary json and typescript stubbings. Now I am lost on how to bring that into a React app. I also do not want to deploy the contract in the smart contract. Assume the smart contract is deployed (locally is fine). Knowing this, is it possible to use the smart contract in react with type safety.

2 Answers

There are many well written articles on the web about combining react with web3 stuff: https://dev.to/rounakbanik/building-a-web3-frontend-with-react-340c

But basically you have to compile your smart contract to an abi file that can be read by your react webapp.

There are libraries for that (also mentioned in most articles / tutorials)

Hope this helps ;)

In hardhat projects layout, we keep the hardhat stuff in its own directory, maybe named contracts. When you created the .json files, take that json file and copy it in a client directory, maybe create a lib folder. You should have this file

 client/lin/MyContract.json

to create the contract, we need to get the abi from json data.

 // your directory path  might be different
 // in next.js it is easy importing from .json, you have to handle it differently in webpack
 import abi from '../lib/MyContract.json'

Once you get the abi, you used it as abi.abi.

to create a contract write a function

const getEthereumContract = () => {
  // instead of ethereum u might be using a different provider
  const provider = new ethers.providers.Web3Provider(ethereum)
  const signer = provider.getSigner()
  // this is the contract 
  const MyContract = new ethers.Contract(
    contractAddress,
    abi.abi,
    signer,
  )
   return MyContract
}

You get the contract address when you run the deploy script.

const main = async () => {
  const transactionFactory = await hre.ethers.getContractFactory('Transactions')
  const transactionContract = await transactionFactory.deploy()
  await transactionContract.deployed()
  //    GET THIS CONTRACT ADDRESS
  console.log('Transactions deployed to:', transactionContract.address)
}

;(async () => {
  try {
    await main()
    process.exit(0)
  } catch (error) {
    console.error(error)
    process.exit(1)
  }
})()

Finally you should have this to create the contract:

Related