Search code examples
javascriptsolidityethers.jshardhat

How to change wallet in hardhat


I'm trying to make a simple governance protocol I was following along with a tutorial and I have working code.

In my hardhat config I add 2 private keys to the accounts tab:

const config: HardhatUserConfig = {
  defaultNetwork: "hardhat",
  networks: {
    hardhat: {
      chainId: 31337,
      allowUnlimitedContractSize: true
    },
    mumbai: {
      url: INFURA_RPC_URL,
      accounts: [PRIVATE_KEY, PRIVATE_KEY_2],
      chainId: 80001,
    },
  },
//...
}

I have a deployment script which create a governance token:

const deployGovernanceToken: DeployFunction = async function (hre: HardhatRuntimeEnvironment) {
  // @ts-ignore
  const { getNamedAccounts, deployments, network } = hre
  const { deploy, log } = deployments
  const { deployer, user } = await getNamedAccounts()
  const governanceToken = await deploy("GovernanceToken", {
    from: deployer, args: [], log: true,
    waitConfirmations: networkConfig[network.name].blockConfirmations || 1,
  })
  await delegate(governanceToken.address, deployer, user)
  //...
}

const delegate = async (governanceTokenAddress: string, delegatedAccount: string, userAccount: string) => {
  const governanceToken = await ethers.getContractAt("GovernanceToken", governanceTokenAddress)
  const transactionResponse = await governanceToken.mint(userAccount, "10000000000000000000000000");
  await transactionResponse.wait(1)
  console.log(`Checkpoints: ${await governanceToken.numCheckpoints(delegatedAccount)}`)
}

Then I have a script which is meant to vote on a proposal.

export async function vote(proposalId: string, voteWay: number, reason: string) {
  console.log("Voting...")
  const signer = await ethers.getSigners()

  console.log('signers:' + signer);

  const governor = await ethers.getContract("GovernorContract")
  const voteTx = await governor.castVoteWithReason(proposalId, voteWay, reason)
  const voteTxReceipt = await voteTx.wait(1)
  console.log(voteTxReceipt.events[0].args.reason)
  const proposalState = await governor.state(proposalId)
  console.log(`Current Proposal State: ${proposalState}`)
  if (developmentChains.includes(network.name)) {
    await moveBlocks(VOTING_PERIOD + 1)
  }
}

How can I change to use my named user when voting?


Solution

  • You'd use .connect()

    Let accounts = await ethers.getSigners();
    admin = accounts[0];
    user1 = accounts[1];
    user2 = accounts[2];
    await governor.connect(user1).castVoteWithReason(proposalId, voteWay, reason);