0

I am working on some hardhat tasks to automate the management of a smart contract. Here's a basic task for granting roles

require("@nomiclabs/hardhat-web3");

task("grantrole", "Grants <Role> to <Wallet>")
    .addParam("account", "The account's address")
    .addParam("role", "The Role to Grant")
    .setAction(async (taskArgs) => {
        let minterRole = ethers.utils.id("MINTER_ROLE");


        const account = web3.utils.toChecksumAddress(taskArgs.account);
        const MyContract = await ethers.getContractFactory("MyContract");
        const contract = await MyContract.attach(
            "0x5FbDB2315678afecb367f032d93F642f64180aa3"
        );

        console.log(await contract.grantRole(minterRole, account));
});

module.exports = {}

A couple of problems here.

  • Is there a way I can configure this to a specific contract for one environment vs another. I don't want to hardcode any contract addresses here.
  • The method above does nothing. If I execute the following npx hardhat grantrole --account 0xfabb0ac9d68b0b445fb7357272ff202c5651694a --role MINTER_ROLE then I go into npx hardhat console to verify:
> await contract.hasRole(minterRole, "0xfabb0ac9d68b0b445fb7357272ff202c5651694a");
false

In fact, I don't see the RPC call to my local node ever get made.

So my questions are, how do I configure the task to call the right RPC/contract based on environment? (localhost vs prod)? and can I configure it so contracts aren't hard coded in the task?

1
  • I answered only the second question because I don't understand the first one. Also, you should try to make one question per post, I believe it's part of the rules of the site, and in any case it's a good practice. Sep 20 at 19:14
2

The method above does nothing. If I execute the following...

When you execute a task without passing any --network, that task is run in the in-process Hardhat network. This is an ephemeral network that is created and destroyed with the process. So when you run your task and then do npx hardhat console, the second command is using a new, fresh instance of the Hardhat network.

Instead, you should start a Hardhat node with npx hardhat node in one terminal to have a persistent instance of the network, and then in another terminal do npx hardhat <your-task> --network localhost and then npx hardhat console --network localhost.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.