Hardhat-Deploy – How to Interact With a Deployed Contract in a Script/Task

hardhathardhat-deployjavascript

I have a folder structure that looks like the following in my hardhat project.

scripts/
└── enter.ts
deploy
└── 01_Deploy_Raffle.ts

After I deploy a contract using hardhat deploy, my other deploy script, I am able to get the address of recent deployments with the get command.

const deployRaffle: DeployFunction = async function (
  hre: HardhatRuntimeEnvironment
) {
  const { deployments, getNamedAccounts, getChainId } = hre
  const { deploy, log, get } = deployments

However, when I use this outside the deploy folder, I seem to run into issues. Hardhat-deploy might not be saving the deployments when I run them to a local blockchain. So, I'll run npx hardhat node (which runs the scripts in my deploy folder), and then try my script outlined below:

import { run, ethers, deployments } from 'hardhat'

async function main() {
  await run('compile')
  const { get } = deployments
  const accounts = await ethers.getSigners()
  const Raffle = await ethers.getContractFactory('Raffle')
  const RaffleDeployment = await get('Raffle')
  const raffle = new ethers.Contract(RaffleDeployment.address, Raffle.interface, accounts[0])
  console.log(raffle.s_entranceFee()) // this line errors
}

I get the following error:

Error: No deployment found for: Raffle
    at get (/Users/patrick/code/decentralized-raffle/node_modules/hardhat-deploy/src/DeploymentsManager.ts:150:17)
    at processTicksAndRejections (internal/process/task_queues.js:95:5)
    at async main (/Users/patrick/code/decentralized-raffle/scripts/enter.ts:11:28)

So what's the best way to write a script with hardhat-deploy?

Best Answer

A common "gotcha" of hardhat deploy. You have to use --network localhost when running a script with your own hardhat node locally.

The default network is the hardhat network otherwise.

Related Topic