Coder Social home page Coder Social logo

dao-template's Issues

Error: VM Exception while processing transaction: reverted with reason string 'Governor: proposal not successful'

Can someone tell me why this issue arises?

These are my tests

const { ethers, network } = require("hardhat");
const {
  VOTING_DELAY,
  VOTING_PERIOD,
  PROPOSAL_DESCRIPTION,
  NEW_STORE_VALUE,
  FUNC,
  DEVELOPMENT_CHAINS,
  MIN_DELAY,
  QUORUM_PERCENTAGE,
  PROPOSAL_FILE,
} = require("../globals");
const fs = require("fs");

let caller;
let deployer;
let governorAddress;
let governorTokenAddress;
let timelockAddress;
let boxAddress;
let proposalIdString;

const setCaller = async () => {
  const accs = await ethers.getSigners();
  caller = accs[0];
  deployer = accs[1];
};

const getLatestBlock = async () => {
  return await ethers.provider.getBlockNumber();
};

async function moveTime(amount) {
  await network.provider.send("evm_increaseTime", [amount]);
  console.log(`πŸ•ž Moved forward in time ${amount} seconds`);
}

async function moveBlocks(amount) {
  console.log("Moving blocks...");
  for (let index = 0; index < amount; index++) {
    await network.provider.request({
      method: "evm_mine",
      params: [],
    });
  }
  console.log(`Moved ${amount} blocks`);
}

const propose = async (args, functionToCall, proposalDescription) => {
  // Deploying governor token contract.
  const GovernorToken = await ethers.getContractFactory("GovernanceToken");
  const governorToken = await GovernorToken.connect(deployer).deploy();
  governorTokenAddress = governorToken.address;

  // Deploying Timelock contract.
  const Timelock = await ethers.getContractFactory("Timelock");
  const timelock = await Timelock.connect(deployer).deploy(MIN_DELAY, [], []);

  //   Governor contract.
  const Governor = await ethers.getContractFactory("DAO");
  const governor = await Governor.connect(deployer).deploy(
    governorToken.address,
    timelock.address,
    QUORUM_PERCENTAGE,
    VOTING_PERIOD,
    VOTING_DELAY
  );
  governorAddress = governor.address;

  // Giving governor the rights to propose something on the timelock contract.
  const proposerRole = await timelock.PROPOSER_ROLE();
  const executorRole = await timelock.EXECUTOR_ROLE();
  await (await timelock.grantRole(proposerRole, governor.address)).wait(1);
  await (await timelock.grantRole(executorRole, governor.address)).wait(1);

  // Box Contract.
  const Box = await ethers.getContractFactory("Box");
  const box = await Box.connect(deployer).deploy();
  boxAddress = box.address;

  const encodedFunctionCall = box.interface.encodeFunctionData(
    functionToCall,
    args
  );
  console.log(`Proposing ${functionToCall} on ${box.address} with ${args}`);
  console.log(`Proposal Description:\n  ${proposalDescription}`);

  // Check the existing value in Box contract.
  console.log("Box :: Value: ", await box.retrieve());

  const proposeTx = await governor.propose(
    [box.address],
    [0],
    [encodedFunctionCall],
    proposalDescription
  );
  console.log("⛏ Block Number: ", await getLatestBlock());
  if (DEVELOPMENT_CHAINS.includes(network.name)) {
    console.log("Jumping blocks.");
    await moveBlocks(VOTING_DELAY + 1);
  }
  const proposeReciept = await proposeTx.wait(1);
  const proposalId = proposeReciept.events[0].args.proposalId;
  proposalIdString = proposalId;
  console.log(`Proposed with proposal ID:\n  ${proposalId}`);

  const proposalState = await governor.state(proposalId);
  const proposalSnapShot = await governor.proposalSnapshot(proposalId);
  const proposalDeadline = await governor.proposalDeadline(proposalId);
  // save the proposalId
  let proposals = JSON.parse(fs.readFileSync(PROPOSAL_FILE, "utf8"));
  console.log("Network Chain Id: ", network.config.chainId);
  proposals[network.config.chainId.toString()].push(proposalId.toString());
  fs.writeFileSync(PROPOSAL_FILE, JSON.stringify(proposals));

  // The state of the proposal. 1 is not passed. 0 is passed.
  console.log(`Current Proposal State: ${proposalState}`);
  // What block # the proposal was snapshot
  console.log(`Current Proposal Snapshot: ${proposalSnapShot}`);
  // The block number the proposal voting expires
  console.log(`Current Proposal Deadline: ${proposalDeadline}`);

  console.log("⛏ Block Number: ", await getLatestBlock());
  const latestBlock = await getLatestBlock();
  const power = await governorToken.getVotes(deployer.address);
  console.log("πŸ’ͺ🏻 Power: ", power);
  console.table([
    { name: "Caller", balance: await governorToken.balanceOf(caller.address) },
    {
      name: "Deployer",
      balance: await governorToken.balanceOf(deployer.address),
    },
  ]);
};

const vote = async (proposalId, voteWay, reason) => {
  console.log("⛏ Block Number: ", await getLatestBlock());
  console.log("Voting started.");
  const Governor = await ethers.getContractFactory("DAO");
  console.log("Governor Address: ", governorAddress);
  const governor = await Governor.attach(governorAddress);
  const GovernanceToken = await ethers.getContractFactory("GovernanceToken");
  const governanceToken = await GovernanceToken.attach(governorTokenAddress);
  await (
    await governanceToken.connect(deployer).delegate(deployer.address)
  ).wait(1);
  const voteTx = await governor
    .connect(deployer)
    .castVoteWithReason(proposalId, voteWay, reason);
  const voteTx1 = await governor
    .connect(caller)
    .castVoteWithReason(proposalId, voteWay, reason);
  await voteTx1.wait(1);

  const voteTxReceipt = await voteTx.wait(1);
  console.log(voteTxReceipt.events[0].args.reason);
  const proposalState = await governor.state(proposalId);

  const voteBalance = await governanceToken.getVotes(deployer.address);
  console.log(`Vote Balance: ${voteBalance}`);
  console.log(`Current Proposal State: ${proposalState}`);
  if (DEVELOPMENT_CHAINS.includes(network.name)) {
    console.log(`πŸ“¦ Moving ${VOTING_PERIOD + 1} blocks`);
    await moveBlocks(VOTING_PERIOD + 1);
  }

  // Logging the proposal state.
  console.log(`πŸ“ State of proposal: ${await governor.state(proposalId)}`);
  console.log(`Proposal Votes:`, await governor.proposalVotes(proposalId));
};

const queueAndExecute = async () => {
  console.log("Block Number", await getLatestBlock());
  console.log("πŸ›³ Queue and Execute");

  const Box = await ethers.getContractFactory("Box");
  const box = Box.attach(boxAddress);
  const encodedFunctionCall = box.interface.encodeFunctionData(FUNC, [
    NEW_STORE_VALUE,
  ]);
  const descriptionHash = ethers.utils.keccak256(
    ethers.utils.toUtf8Bytes(PROPOSAL_DESCRIPTION)
  );
  const Governor = await ethers.getContractFactory("DAO");
  const governor = await Governor.attach(governorAddress);
  const queueTx = await governor.queue(
    [box.address],
    [0],
    [encodedFunctionCall],
    descriptionHash
  );
  await queueTx.wait(1);
};

const main = async () => {
  await setCaller();
  await propose([NEW_STORE_VALUE], FUNC, PROPOSAL_DESCRIPTION);
  await vote(proposalIdString, 1, "I like the proposal that's it.");
  await queueAndExecute();
};

main()
  .then(() => process.exit(0))
  .catch((e) => {
    console.error(e);
    process.exit(1);
  });

Error - TimelockController: operation is not ready

Hi Patrick,

I wrote my testcases in javascript, and not sure why but I keep getting this error: reverted with reason string 'TimelockController: operation is not ready'.

Also, I had to add a saltHash parameter in the execute function. Checked the contract and it does needed that. Could you please explain what is that for?

const exTx = await timelock.connect(Executor).execute(treasury.address, 0, encodedFunctionCall, descriptionHash, saltHash)
await exTx.wait(1)

Note- treasury.address here is like my Box.sol and 'Executor' is the one who I have given executor role.

Thank you so much for your time

Questions on Expanding on Your DAO Template

Hi @PatrickAlphaC

Thank you for this helpful tutorial!

I'm leveling-up my Solidity skills and learning about DAOs using OpenZeppelin's standards! So, these are just questions on how to build upon your template and not issues.

  1. Is some sort of "gatekeeper" function needed to only allow holders of the token to make proposals and to vote? Or is this built into ERC20Votes.sol? My actual use-case is draft-ERC721Votes.sol .

  2. What would be the purpose of ADDRESS_ZERO in the config and setup files? Is this to save gas?

  3. It's mentioned that TimeLock.sol handles all the money, ownerships, etc

    • How would this apply to the following use-case? If you want (i) to charge for your token and (ii) store those received funds in your DAO's Treasury, wouldn't this all be inside your token minter contract, that is, GovernanceToken.sol and not in TimeLock.sol?

Update of the TimeLockController openzeppelin contract

The constructor for this has changed and should be renounced in the TimeLock.sol contract after they added the "admin" to the constructor instead of the previous versions of this contract that would assign this admin to the deployer automatically

Here's how the updated version should look like:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/governance/TimelockController.sol";

contract TimeLock is TimelockController {
    constructor(
        uint256 minDelay, 
        address[] memory proposers, 
        address[] memory executors, 
        address admin
    ) TimelockController(minDelay, proposers, executors, admin) {}
}

TypeError: Cannot read properties of undefined (reading '0')

I am running the propose.ts to execute the propose function from Governor contract the args are transacted on the local blockchain as I retrieved the logs from the transaction event.

EventLog {
    fragment: EventFragment {
      type: 'event',
      inputs: [Array],
      name: 'ProposalCreated',
      anonymous: false
    },
    args: Result(9) [
      71868859171677419052155345699497483540960066113331982602962523540651890624828n,
      '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266',
      [Result],
      [Result],
      [Result],
      [Result],
      16n,
      21n,
      'This proposal shall execute the box store function to save the uint256 passed through proposal'
    ]
  }
]

Here's the code according to the tutorial video though I am using ethers v6

const proposeTx = await governor.getFunction("propose")(
    [await box.getAddress()],
    [0],
    [encodedFunctionCall],
    proposalDescription
  )
  // If working on a development chain, we will push forward till we get to the voting period.
  if (developmentChains.includes(network.name)) {
    await moveBlocks(VOTING_DELAY + 1)
  }

  const proposeReceipt = await proposeTx.wait(1);
  const proposalId = proposeReceipt.events[0].args.proposalId
  console.log(`Proposed with proposal ID:\n  ${proposalId}`)

Error running yarn hardhat deploy

When I finished the script 03-deploy-governor-contract and try to run the deploy command, it throws the error below, I have the exact same code shown in the YT tutorial. The first two contracts are deployed but the error comes in the third one, the GovernorContract.

Error: cannot estimate gas; transaction may fail or may require manual gas limit [ See: https://links.ethers.org/v5-errors-UNPREDICTABLE_GAS_LIMIT ] (reason="Transaction reverted: trying to deploy a contract whose code is too large", method="estimateGas"

Screen Shot 2022-07-05 at 12 39 40 AM

Error when running queue-and-execute.ts on Sepolia

I've got everything working perfectly on localhost. Sepolia testnet works fine for Propose, vote. But I got an error when trying to run the Queue and execute.ts script. I saw the comment on the code ("this will fail on a testnet because you need to wait for the MIN_DELAY!") . But I'd like to know how can I change the code so that It'll run on testnet.
Thanks

The logical flow of governance seems off

I'm following along with the scripts and this DAO seems insecure.

the export async function queueAndExecute() allows you to pass what ever you want to queue and execute.

Shouldn't the encodeFunctionData really come from on chain instead of passing it manually?
Also I don't see any logic which checks whether or not the vote actually passes before queue and execute?

Governance Execution Delay?

Is there a configuration for delay in exeuction? I could of sworn there was a property to delay exeuction to assure members have enough time from when the vote passes to get out of the DAO if necessary. Maybe I'm thinking of a different governor?

I see these variables in OZ Settings:

/**
 * @notice module:user-config
 * @dev Delay, in number of block, between the proposal is created and the vote starts. This can be increassed to
 * leave time for users to buy voting power, or delegate it, before the voting of a proposal starts.
 */
function votingDelay() public view virtual returns (uint256);

/**
 * @notice module:user-config
 * @dev Delay, in number of blocks, between the vote start and vote ends.
 *
 * NOTE: The {votingDelay} can delay the start of the vote. This must be considered when setting the voting
 * duration compared to the voting delay.
 */
function votingPeriod() public view virtual returns (uint256); 

Is there a variable for delayed execution?

TypeError: Cannot read properties of ')undefined (reading '0)

Hi every body
I am currently encountering a problem in the part of the code where we try to find the id of a proposal with this line

 const proposalId = proposeReceipt.events[0].args.proposalId

So this gives an error : TypeError: Cannot read properties of ')undefined (reading '0),

I saw a closed issue on this repo which said to do instead:

const proposalId = governor.interface.parseLog(proposeReceipt.logs[0].args.proposeId);

But this also leads to an error which is:

TypeError: Cannot read properties of undefined (reading 'topics')
    at Interface.parseLog

I hate this ethers v6 update, anyone have a solution to this? thank you so much...

VM Exception while processing transaction: reverted with reason string 'Governor: vote not currently active'

Hey @PatrickAlphaC ,
Thank you for the video and code, I'm running yarn hardhat run scripts/vote.ts and got the following error:.

Error: cannot estimate gas; transaction may fail or may require manual gas limit [ See: https://links.ethers.org/v5-errors-UNPREDICTABLE_GAS_LIMIT ] (reason="Error: VM Exception while 
processing transaction: reverted with reason string 'Governor: vote not currently active'", 
method="estimateGas", transaction={"from":"0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266","to":"0xCf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9"

I tried to use the solution proposed here #6 but did not work for this case.

I am getting this error when i try to deploy code

When i run yarn hardhat deploy It gives me this error
No need to generate any newer typings.
An unexpected error occurred:


Error: ERROR processing skip func of /dao-governance/deploy/04-setup-governance-contract.ts:
TSError: β¨― Unable to compile TypeScript:
deploy/04-setup-governance-contract.ts:15:33 - error TS2551: Property 'getContract' does not exist on type 'typeof import("/dao-governance/node_modules/ethers/lib/ethers") & HardhatEthersHelpers'. Did you mean 'getContractAt'?

15   const timeLock = await ethers.getContract("TimeLock", deployer);

Can anyone help about this.

No Contract deployed with name Box

I'm trying to run queue-and-execute and im getting an error:

No Contract deployed with name Box

Its weird because if I run

yarn hardhat console --network localhost

I can grab the box contract just fine. Any Ideas on why?

TypeError: Cannot read properties of undefined (reading 'length')

Hi @PatrickAlphaC @zeuslawyer ,
I am following your tutorial step by step instead of cloning the the repo and I am running into this error when I try to deploy:

yarn hardhat deploy --show-stack-traces
yarn run v1.22.19
warning package.json: No license field
$ /home/chinmay/dev/governance/node_modules/.bin/hardhat deploy --show-stack-traces
Nothing to compile
No need to generate any newer typings.
----------------------------------------------------
Deploying GovernanceToken and waiting for confirmations...
An unexpected error occurred:

Error: ERROR processing /home/chinmay/dev/governance/deploy/deploy-Governance-token.ts:
TypeError: Cannot read properties of undefined (reading 'length')
 at getFrom (/home/chinmay/dev/governance/node_modules/hardhat-deploy/src/helpers.ts:1713:14)
 at _deploy (/home/chinmay/dev/governance/node_modules/hardhat-deploy/src/helpers.ts:533:9)
 at processTicksAndRejections (node:internal/process/task_queues:96:5)
 at async _deployOne (/home/chinmay/dev/governance/node_modules/hardhat-deploy/src/helpers.ts:1004:16)
 at async Object.deployGovernanceToken [as func] (/home/chinmay/dev/governance/deploy/deploy-Governance-token.ts:14:27)
 at async DeploymentsManager.executeDeployScripts (/home/chinmay/dev/governance/node_modules/hardhat-deploy/src/DeploymentsManager.ts:1219:22)
 at async DeploymentsManager.runDeploy (/home/chinmay/dev/governance/node_modules/hardhat-deploy/src/DeploymentsManager.ts:1052:5)
 at async SimpleTaskDefinition.action (/home/chinmay/dev/governance/node_modules/hardhat-deploy/src/index.ts:438:5)
 at async Environment._runTaskDefinition (/home/chinmay/dev/governance/node_modules/hardhat/src/internal/core/runtime-environment.ts:219:14)
 at async Environment.run (/home/chinmay/dev/governance/node_modules/hardhat/src/internal/core/runtime-environment.ts:131:14)
 at DeploymentsManager.executeDeployScripts (/home/chinmay/dev/governance/node_modules/hardhat-deploy/src/DeploymentsManager.ts:1222:19)
 at processTicksAndRejections (node:internal/process/task_queues:96:5)
 at async DeploymentsManager.runDeploy (/home/chinmay/dev/governance/node_modules/hardhat-deploy/src/DeploymentsManager.ts:1052:5)
 at async SimpleTaskDefinition.action (/home/chinmay/dev/governance/node_modules/hardhat-deploy/src/index.ts:438:5)
 at async Environment._runTaskDefinition (/home/chinmay/dev/governance/node_modules/hardhat/src/internal/core/runtime-environment.ts:219:14)
 at async Environment.run (/home/chinmay/dev/governance/node_modules/hardhat/src/internal/core/runtime-environment.ts:131:14)
 at async SimpleTaskDefinition.action (/home/chinmay/dev/governance/node_modules/hardhat-deploy/src/index.ts:584:32)
 at async Environment._runTaskDefinition (/home/chinmay/dev/governance/node_modules/hardhat/src/internal/core/runtime-environment.ts:219:14)
 at async Environment.run (/home/chinmay/dev/governance/node_modules/hardhat/src/internal/core/runtime-environment.ts:131:14)
 at async SimpleTaskDefinition.action (/home/chinmay/dev/governance/node_modules/hardhat-deploy/src/index.ts:669:5)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Really not sure what to do but it does seem very similar to another issue created here: PatrickAlphaC/all-on-chain-generated-nft#6

ERROR DEOPLOYING

The code in line line 37 of deploy-box.ts

const transferTx = await boxContract.transferOwnership(timeLock.address)

is causing deployments to have an error stating transferownership function doens't exist, please how do i resolve

Error: could not decode result data PROPOSER_ROLE()

I am getting an error during deploying on hardhat node with setup_governor script:

Error: could not decode result data (value="0x", info={ "method": "PROPOSER_ROLE", "signature": "PROPOSER_ROLE()" },

const timeLock = await ethers.getContractAt("TimeLock", deployer);
    const governance = await ethers.getContractAt("GovernorContract", deployer);

    log("----------------------------------------------------")
    log("Setting up roles...");
    const proposerRole = await timeLock.PROPOSER_ROLE();
    const executorRole = await timeLock.EXECUTOR_ROLE();
    const adminRole = await timeLock.TIMELOCK_ADMIN_ROLE();

    const proposerTx = await timeLock.grantRole(proposerRole, governance.getAddress());
    await proposerTx.wait(1); // wait for 1 block confirmation
    const executorTx = await timeLock.grantRole(executorRole, ADDRESS_ZERO);
    await executorTx.wait(1); // wait for 1 block confirmation
    const revokeTx = await timeLock.revokeRole(adminRole, deployer);
    await revokeTx.wait(1);

Transaction ran out of gas

Hi Bro @PatrickAlphaC ,
Thankyou for video and code, Im run deloy and got errow with governor.
deploy/3-deploy-governor-contract.ts:
TransactionExecutionError: Transaction ran out of gas

Can help me, thankyou!
Minh,

Error: Unable to propose a new proposal with error TypeError: Cannot read properties of undefined (reading 'args')

Hi @PatrickAlphaC,

I'm getting an issue is unable to propose a new proposal when running script yarn hardhat run scripts/propose.ts on local. The interest thing is the script works well last week. I've run the script on Goerli testnet and it also works well.

The error I got on local environment:
image

As you can see, the events response empty and the proposal cannot be created successfully.

I've investigating and found some updated from libraries hardhat and @nomiclabs/hardhat-ethers to fix the issue related to function getContractAt https://github.com/NomicFoundation/hardhat/releases/tag/%40nomiclabs%2Fhardhat-ethers%402.1.1.

Unfortunately, we're using the library "@nomiclabs/hardhat-ethers": "npm:[email protected]" in package.json to wrapping hardhat-ethers. I've checked and seen the library is no longer to update and maintenance.

Could you please help to review the issue and give us your advice?

Thank you!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.