Code Monkey home page Code Monkey logo

hardhat-simple-storage-fcc's Introduction

Update: Head to Cyfrin Updraft

ℹ️ Important: This repo is no longer maintained; we invite all people learning Solidity to head to Cyfrin Updraft! The 100% free #1 smart contract education platform on earth. Developed with love by Patrick & Cyfrin <3

Hardhat Simple Storage

This is a section of the Javascript Blockchain/Smart Contract FreeCodeCamp Course.

⌨️ (08:20:17) Lesson 6: Hardhat Simple Storage

This repo has been updated for Sepolia over Goerli.

Full Repo

This project is apart of the Hardhat FreeCodeCamp video.

Getting Started

Requirements

  • git
    • You'll know you did it right if you can run git --version and you see a response like git version x.x.x
  • Nodejs
    • You'll know you've installed nodejs right if you can run:
      • node --version and get an output like: vx.x.x
  • Yarn instead of npm
    • You'll know you've installed yarn right if you can run:
      • yarn --version and get an output like: x.x.x
      • You might need to install it with npm or corepack

Quickstart

git clone https://github.com/PatrickAlphaC/hardhat-simple-storage-fcc
cd hardhat-simple-storage-fcc
yarn
yarn hardhat

Typescript

For the typescript edition, run:

git checkout typescript

Optional Gitpod

If you can't or don't want to run and install locally, you can work with this repo in Gitpod. If you do this, you can skip the clone this repo part.

Open in Gitpod

Usage

Deploy:

npx hardhat run scripts/deploy.js

Testing

npx hardhat test

Test Coverage

npx hardhat coverage

Estimate gas

You can estimate how much gas things cost by running:

npx hardhat test

And you'll see and output file called gas-report.txt

Local Deployment

If you'd like to run your own local hardhat network, you can run:

npx hardhat node

And then in a different terminal

npx hardhat run scripts/deploy.js --network localhost

And you should see transactions happen in your terminal that is running npx hardhat node

Important localhost note

If you use metamask with a local network, everytime you shut down your node, you'll need to reset your account. Settings -> Advanced -> Reset account. Don't do this with a metamask you have real funds in. And maybe don't do this if you're a little confused by this.

Deployment to a testnet or mainnet

  1. Setup environment variables

You'll want to set your SEPOLIA_RPC_URL and PRIVATE_KEY as environment variables. You can add them to a .env file, similar to what you see in .env.example.

  • PRIVATE_KEY: The private key of your account (like from metamask). NOTE: FOR DEVELOPMENT, PLEASE USE A KEY THAT DOESN'T HAVE ANY REAL FUNDS ASSOCIATED WITH IT.
  • SEPOLIA_RPC_URL: This is url of the sepolia testnet node you're working with. You can get setup with one for free from Alchemy
  1. Get testnet ETH

Head over to faucets.chain.link and get some tesnet ETH. You should see the ETH show up in your metamask.

  1. Deploy
npx hardhat run scripts/deploy.js --network sepolia

Verify on etherscan

If you deploy to a testnet or mainnet, you can verify it if you get an API Key from Etherscan and set it as an environment variable named ETHERSCAN_API_KEY. You can pop it into your .env file as seen in the .env.example.

In it's current state, if you have your api key set, it will auto verify sepolia contracts!

However, you can manual verify with:

npx hardhat verify --constructor-args arguments.js DEPLOYED_CONTRACT_ADDRESS

Linting

To check linting / code formatting:

yarn lint

or, to fix:

yarn lint:fix

Thank you!

If you appreciated this, feel free to follow me or donate!

ETH/Polygon/Avalanche/etc Address: 0x9680201d9c93d65a3603d2088d125e955c73BD65

Patrick Collins Twitter Patrick Collins YouTube Patrick Collins Linkedin Patrick Collins Medium

hardhat-simple-storage-fcc's People

Contributors

0xsanyam avatar alymurtazamemon avatar ayush-thakur-geek avatar joonakauranen avatar pappyj avatar patrickalphac avatar robocrypter avatar rohitks7 avatar uday03meh avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

hardhat-simple-storage-fcc's Issues

error

there is an error coming in.
yarn add hardat-gas-reporter --D
yarn add v1.22.15
[1/4] Resolving packages...
error An unexpected error occurred: "https://registry.yarnpkg.com/hardat-gas-reporter: Not found".
info If you think this is a bug, please open a bug report with the information provided in "/home/thakuradi/hh-fcc/ethers-simple-storage/yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.

Deployment issues with HardHat

On YouTube, I am on the 08:41:03 mark.

const { ethers, run, network } = require("hardhat")

async function main() {
    const SimpleStorageFactory = await ethers.getContractFactory(
        "SimpleStorage"
    )
    console.log("Deploying contract...")
    const simpleStorage = await SimpleStorageFactory.deploy()
    await simpleStorage.deployed()
    console.log(simpleStorage)
}

This returns the following error:

TypeError: no matching function (argument="key", value="deployed", code=INVALID_ARGUMENT, version=6.6.3)
    at makeError (/home/hamza/Documents/JS/Ethersjsx/hardhat/SimpleStorage/node_modules/ethers/src.ts/utils/errors.ts:670:21)
    at assert (/home/hamza/Documents/JS/Ethersjsx/hardhat/SimpleStorage/node_modules/ethers/src.ts/utils/errors.ts:694:25)
    at assertArgument (/home/hamza/Documents/JS/Ethersjsx/hardhat/SimpleStorage/node_modules/ethers/src.ts/utils/errors.ts:706:5)
    at Interface.getFunctionName (/home/hamza/Documents/JS/Ethersjsx/hardhat/SimpleStorage/node_modules/ethers/src.ts/abi/interface.ts:542:23)
    at buildWrappedMethod (/home/hamza/Documents/JS/Ethersjsx/hardhat/SimpleStorage/node_modules/ethers/src.ts/contract/contract.ts:334:34)
    at BaseContract.getFunction (/home/hamza/Documents/JS/Ethersjsx/hardhat/SimpleStorage/node_modules/ethers/src.ts/contract/contract.ts:859:22)
    at Object.get (/home/hamza/Documents/JS/Ethersjsx/hardhat/SimpleStorage/node_modules/ethers/src.ts/contract/contract.ts:757:39)
    at main (/home/hamza/Documents/JS/Ethersjsx/hardhat/SimpleStorage/scripts/deploy.js:10:25)
    at processTicksAndRejections (node:internal/process/task_queues:95:5) {
  code: 'INVALID_ARGUMENT',
  argument: 'key',
  value: 'deployed'
}

Yarn Version:
1.22.19

HardHat Version:
2.17.0

Node Version:
20.3.1

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

Guys,When I run this piece of code, I encounter a TypeError. How should I resolve it?

// imports
const { ethers, run, network } = require("hardhat");

// async main
async function main() {
const SimpleStorageFactory = await ethers.getContractFactory("SimpleStorage");
console.log("Deploying contract...");

const simpleStorage = await SimpleStorageFactory.deploy();
await simpleStorage.waitForDeployment();
console.log(Deployed contract to: ${simpleStorage.target});
// what happens when we deploy to our hardhat network?

if (network.config.chainId == 11155111 && process.env.ETHERSCAN_API_KEY) {
console.log("Waiting for block confirmations...");
await simpleStorage.deployTransaction.wait(6); //HERE!!!
await verify(simpleStorage.target, []);
}

Hardhat Plugin Update

Hello @PatrickAlphaC,

Hardhat has updated its plugins and move all its plugin to one plugin called @nomicfoundation/hardhat-toolbox. Now when people are installing the packages they are facing issues due to these plugin updates, because they also require changes in the hardhat.config.js file.

I have read the hardhat docs and tried that update on this project (has a similar setup for other projects), and now it is working correctly. I would like to update the projects with new hardhat plugin.

Should I send the pull request?

Solution: Hardhat has been updated (and will not be similar to the video)

For those of you (and me too) that have very little coding experience yet are following along with this great course I'd thought I'd share my pitfall and solution for the following issue:

If you are installing hardhat as per the instructions in the video you may find yourself installing a newer version of Hardhat that does not allow for the options that are shown in the video. If that should happen to you the following steps can get you back on track to following along with Patrick in the video.

  1. If you have already installed a newer version of hardhat we need to remove that to install the version that Patrick is using (which is version 2.9.3). To do so, type 'yarn remove hardhat' in the terminal. This will remove the latest version (type 'yarn list' in the terminal to check and verify if step 1 worked).

  2. Install the correct version of hardhat as used in the video. To do so type 'yarn add --dev [email protected]' in the terminal which will install the older version which Patrick is using. After installation you will find that the options are available now.

These two steps have helped me to work around the issues of the newer version.

  1. Another issue (that will also apply to later lessons) could be that while running hardhat (via the 'yarn hardhat' command in the terminal) you will not be prompted with a yes/no option to install all the required dependencies but you will be told to do so you yourself. This is really easy to fix as you can copy and paste the message into your terminal. For your convenience here is the command (the following list has more options as this post originally applied to lesson 10 in this coding course):
    yarn add --dev "hardhat@^2.9.3" "@nomiclabs/hardhat-waffle@^2.0.0" "ethereum-waffle@^3.0.0" "chai@^4.2.0" "@nomiclabs/hardhat-ethers@^2.0.0" "ethers@^5.0.0" "@nomiclabs/hardhat-etherscan@^3.0.0" "dotenv@^10.0.0" "eslint@^7.29.0" "eslint-config-prettier@^8.3.0" "eslint-config-standard@^16.0.3" "eslint-plugin-import@^2.23.4" "eslint-plugin-node@^11.1.0" "eslint-plugin-prettier@^3.4.0" "eslint-plugin-promise@^5.1.0" "hardhat-gas-reporter@^1.0.4" "prettier@^2.3.2" "prettier-plugin-solidity@^1.0.0-beta.13" "solhint@^3.3.6" "solidity-coverage@^0.7.16"

If any experts can chime in on any other tips/tricks to help us newbies that would be more than welcome.

From one Patrick (the newbie) to another Patrick (the pro); thanks for sharing your knowledge with us > this may change a lot of lives for the better tips hat to you.

*This is a repost from the original one that applies to Lesson 10.

HardhatError: HH700: Artifact for contract "SimpleStorage" not found.

I have this error at the start of Hardhat section

This is deploy.js:
const { ethers } = require("hardhat");

async function main() {
const SimpleStorageFactory = await ethers.getContractFactory("SimpleStorage");
console.log("Deploying contract...");
const simpleStorage = await SimpleStorageFactory.deploy();
await simpleStorage.deployed();
}

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

after I type: yarn hardhat run scripts/deploy.js
HardhatError: HH700: Artifact for contract "SimpleStorage" not found.
at Artifacts._handleWrongArtifactForContractName (/Users/enricoyu/Coding/hardhat-simple-storage-fcc/node_modules/hardhat/src/internal/artifacts.ts:478:11)
at Artifacts._getArtifactPathFromFiles (/Users/enricoyu/Coding/hardhat-simple-storage-fcc/node_modules/hardhat/src/internal/artifacts.ts:593:19)
at Artifacts._getArtifactPath (/Users/enricoyu/Coding/hardhat-simple-storage-fcc/node_modules/hardhat/src/internal/artifacts.ts:275:17)
at Artifacts.readArtifact (/Users/enricoyu/Coding/hardhat-simple-storage-fcc/node_modules/hardhat/src/internal/artifacts.ts:58:26)
at getContractFactory (/Users/enricoyu/Coding/hardhat-simple-storage-fcc/node_modules/@nomiclabs/hardhat-ethers/src/internal/helpers.ts:99:22)
at main (/Users/enricoyu/Coding/hardhat-simple-storage-fcc/scripts/deploy.js:4:32)
error Command failed with exit code 1.

Issue with latest Hardhat 6.6.2

While the tutorial was done with a prior generation of hardhat, I thought it would be worthwhile stating that under version 6.6.2 (the version that now installs when you follow the YARN commands) the line:

await simpleStorage.deployTransaction.wait(6)

Now fails, as the deployTransaction seems to have been removed. This creates something of a stumbling block for people who are trying to use the wait(6)function for 6 block confirmations.

Error:

TypeError: no matching function (argument="key", value="deployTransaction", code=INVALID_ARGUMENT, version=6.6.2)

There is a function called deploymentTransaction() that appears through intellisense, but if you attempt to chain wait(6), you get the error message:

TypeError: simpleStorage.deploymentTransaction.wait is not a function

So you are not able to wait for block confirmations, and without it you run into the error of the byte code not having been recognised on Etherscan yet as described in the video. Something to be aware of on this particular step if you are running Hardhat v6.x.x.

Possible issue with tsconfig.json

Hello,

At the end of Lesson 6, during the Typescript section, I ran into an unexpected issue that didn't appear to affect you in the video. Here's the breakdown of what went wrong and how I fixed it:

After copying over the contents of tsconfig.json from this repo, I had no issues converting the deploy and hardhat-config from .js to .ts. However, when I did the same with the block-number task I ran into the following error:
Property 'ethers' does not exist on type 'HardhatRuntimeEnvironment'.ts(2339)
Property 'ethers' does not exist on type 'HardhatRuntimeEnvironment'.ts(2339)

I thought this was odd, but after poking around for a few minutes I noticed this line in the tsconfig.json file I copied:

"include": ["./scripts", "./test"],

It occurred to me that "./tasks" was missing, and as soon as I added that to the list my error disappeared!

However, I find it curious that this didn't appear to be necessary in the video, as there's no sign of the same error in the screenshot of the video below:
image

It seems possible that this is due to some difference between dependency versions, since I added them myself as I followed along rather than copy your package.json contents. These are the versions specified in mine:

  "devDependencies": {
    "@nomiclabs/hardhat-ethers": "^2.0.0",
    "@nomiclabs/hardhat-etherscan": "^3.1.0",
    "@nomiclabs/hardhat-waffle": "^2.0.0",
    "@typechain/ethers-v5": "^10.1.0",
    "@typechain/hardhat": "^6.1.2",
    "@types/chai": "^4.3.1",
    "@types/mocha": "^9.1.1",
    "@types/node": "^18.0.0",
    "chai": "^4.2.0",
    "dotenv": "^16.0.1",
    "ethereum-waffle": "^3.0.0",
    "ethers": "^5.0.0",
    "hardhat": "^2.9.9",
    "hardhat-gas-reporter": "^1.0.8",
    "prettier": "^2.7.1",
    "prettier-plugin-solidity": "^1.0.0-beta.19",
    "solidity-coverage": "^0.7.21",
    "ts-node": "^10.8.1",
    "typechain": "^8.1.0",
    "typescript": "^4.7.4"
  }

Regardless, this is the modified tsconfig.json file that resolved my error:

{
  "compilerOptions": {
    "target": "es2018",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "outDir": "dist"
  },
  "include": ["./scripts", "./test", "./tasks"],
  "files": ["./hardhat.config.ts"]
}

lesson 6 Hardhat - HardHat issue Verifying to Sepolia

// imports
const { ethers, run, network } = require("hardhat")
require("@nomicfoundation/hardhat-ethers")

// async main
async function main() {
const SimpleStorageFactory =
await ethers.getContractFactory("SimpleStorage")
console.log("Deploying Contract...")
const simpleStorage = await SimpleStorageFactory.deploy()
await simpleStorage.getDeployedCode()
console.log(Deployed Contract to: ${simpleStorage.target})
// whats happened when we deploy to our hardhat network?
// console.log(network.config)
if (network.config.chainId === 11155111 && process.env.ETHERSCAN_API_KEY) {
console.log("Waiting blocks txes...")
await simpleStorage.deploytransaction().wait(6)
await verify(simpleStorage.target, [])
}
// const currentValue = await simpleStorage.retrieve()
// console.log(Current Value is: ${currentValue})

// update current value
const transactionResponse = await simpleStorage.store(7)
await transactionResponse.wait(1)
const updatedValue = await simpleStorage.retrieve()
console.log(`Updated value is:${updatedValue}`)

}

// async function verify(contractAddress, args) {
const verify = async (contractAddress, args) => {
console.log("Verifying contract...")
try {
await run("verify: verify", {
address: contractAddress,
constuctorAddress: args,
})
} catch (e) {
if (e.message.toLowerCase().inlcudes("already verified")) {
console.log("Already Verified")
} else {
console.log(e)
}
}
}

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

for some reason my deploy script doesnt even attempt to verify. can anyone help?

issue with deployment using hardhat

TypeError: no matching function (argument="key", value="address", code=INVALID_ARGUMENT, version=6.6.2)
at makeError (/root/hardhat-core/node_modules/ethers/src.ts/utils/errors.ts:670:21)
at assert (/root/hardhat-core/node_modules/ethers/src.ts/utils/errors.ts:694:25)
at assertArgument (/root/hardhat-core/node_modules/ethers/src.ts/utils/errors.ts:706:5)
at Interface.getFunctionName (/root/hardhat-core/node_modules/ethers/src.ts/abi/interface.ts:542:23)
at buildWrappedMethod (/root/hardhat-core/node_modules/ethers/src.ts/contract/contract.ts:334:34)
at BaseContract.getFunction (/root/hardhat-core/node_modules/ethers/src.ts/contract/contract.ts:849:22)
at Object.get (/root/hardhat-core/node_modules/ethers/src.ts/contract/contract.ts:747:39)
at main (/root/hardhat-core/scripts/deploy.js:7:54)
at processTicksAndRejections (node:internal/process/task_queues:95:5) {
code: 'INVALID_ARGUMENT',
argument: 'key',
value: 'address'
}

My code is giving this error and here is the code

const { ethers } = require("hardhat");

async function main() {
  const SimpleStorageFactory = await ethers.getContractFactory("SimpleStorage");
  console.log("deploying contract");
  const simpleStorage = await SimpleStorageFactory.deploy();
  await simpleStorage.deployed();
  console.log(`Deployed contract to: ${simpleStorage.address}`);
}

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

I keep getting this error while running tests for the simple storage contract in hardhat in lesson 6

SimpleStorage

    1) Should start with a fav no of zero


  0 passing (2s)
  1 failing

  1) SimpleStorage
       Should start with a fav no of zero:

      ```
AssertionError: expected 'function () {\n        var args = [];…' to equal '0'
      + expected - actual

      -function () {
      -        var args = [];
      -        for (var _i = 0; _i < arguments.length; _i++) {
      -            args[_i] = arguments[_i];
      -        }
      -        return __awaiter(this, void 0, void 0, function () {
      -            var blockTag, overrides, tx, result, value;
      -            return __generator(this, function (_a) {
      -                switch (_a.label) {
      -                    case 0:
      -                        blockTag = undefined;
      -                        if (!(args.length === fragment.inputs.length + 1 && typeof (args[args.length - 1]) === "object")) return [3 /*break*/, 3];   
      -                        overrides = (0, properties_1.shallowCopy)(args.pop());
      -                        if (!(overrides.blockTag != null)) return [3 /*break*/, 2];
      -                        return [4 /*yield*/, overrides.blockTag];
      -                    case 1:
      -                        blockTag = _a.sent();
      -                        _a.label = 2;
      -                    case 2:
      -                        delete overrides.blockTag;
      -                        args.push(overrides);
      -                        _a.label = 3;
      -                    case 3:
      -                        if (!(contract.deployTransaction != null)) return [3 /*break*/, 5];
      -                        return [4 /*yield*/, contract._deployed(blockTag)];
      -                    case 4:
      -                        _a.sent();
      -                        _a.label = 5;
      -                    case 5: return [4 /*yield*/, populateTransaction(contract, fragment, args)];
      -                    case 6:
      -                        tx = _a.sent();
      -                        return [4 /*yield*/, signerOrProvider.call(tx, blockTag)];
      -                    case 7:
      -                        result = _a.sent();
      -                        try {
      -                            value = contract.interface.decodeFunctionResult(fragment, result);
      -                            if (collapseSimple && fragment.outputs.length === 1) {
      -                                value = value[0];
      -                            }
      -                            return [2 /*return*/, value];
      -                        }
      -                        catch (error) {
      -                            if (error.code === logger_1.Logger.errors.CALL_EXCEPTION) {
      -                                error.address = contract.address;
      -                                error.args = args;
      -                                error.transaction = tx;
      -                            }
      -                            throw error;
      -                        }
      -                        return [2 /*return*/];
      -                }
      -            });
      -        });
      -    }
      +0

      at Context.<anonymous> (test\test-deploy.js:14:16)
      at processTicksAndRejections (node:internal/process/task_queues:96:5)
      at runNextTicks (node:internal/process/task_queues:65:3)
      at listOnTimeout (node:internal/timers:528:9)
      at processTimers (node:internal/timers:502:7)


error Command failed with exit code 1.


Can anyone please help me 

Error when running deploy.js with function "deployTransaction"

Hi all!
I've been following the steps from the video and with this code:

const { ethers, run, network } = require("hardhat")

// async main
async function main() {
  const SimpleStorageFactory = await ethers.getContractFactory("SimpleStorage")
  console.log("Deploying contract...")
  const simpleStorage = await SimpleStorageFactory.deploy()
  await simpleStorage.deployed()
  console.log(`Deployed contract to: ${simpleStorage.address}`)
  }

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

I get the following error:

yarn run v1.22.19
$ /home/user/Documents/learning/blockchain/smart-contracts-learning/hardhat-simple-storage/node_modules/.bin/hardhat run scripts/deploy.js --network sepolia
Deploying contract :)
TypeError: no matching function (argument="key", value="deployed", code=INVALID_ARGUMENT, version=6.6.1)
    at makeError (/home/user/Documents/learning/blockchain/smart-contracts-learning/hardhat-simple-storage/node_modules/ethers/src.ts/utils/errors.ts:670:21)
    at assert (/home/user/Documents/learning/blockchain/smart-contracts-learning/hardhat-simple-storage/node_modules/ethers/src.ts/utils/errors.ts:694:25)
    at assertArgument (/home/user/Documents/learning/blockchain/smart-contracts-learning/hardhat-simple-storage/node_modules/ethers/src.ts/utils/errors.ts:706:5)
    at Interface.getFunctionName (/home/user/Documents/learning/blockchain/smart-contracts-learning/hardhat-simple-storage/node_modules/ethers/src.ts/abi/interface.ts:542:23)
    at buildWrappedMethod (/home/user/Documents/learning/blockchain/smart-contracts-learning/hardhat-simple-storage/node_modules/ethers/src.ts/contract/contract.ts:334:34)
    at BaseContract.getFunction (/home/user/Documents/learning/blockchain/smart-contracts-learning/hardhat-simple-storage/node_modules/ethers/src.ts/contract/contract.ts:849:22)
    at Object.get (/home/user/Documents/learning/blockchain/smart-contracts-learning/hardhat-simple-storage/node_modules/ethers/src.ts/contract/contract.ts:747:39)
    at main (/home/user/Documents/learning/blockchain/smart-contracts-learning/hardhat-simple-storage/scripts/deploy.js:7:23)
    at processTicksAndRejections (node:internal/process/task_queues:95:5) {
  code: 'INVALID_ARGUMENT',
  argument: 'key',
  value: 'deployed'
}
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

After googling I discovered that there is a new version of hardhat (or ethers?) so those functions had been changed, so I updated my code to this:


async function main() {
    console.log("Deploying contract :)")
    const simpleStorage = await ethers.deployContract("SimpleStorage")
    await simpleStorage.waitForDeployment()
    console.log(`Deployed contract to: ${await simpleStorage.getAddress()}`)
    if (network.config.chainId === 11155111 && process.env.ETHERSCAN_API_KEY) {
        await simpleStorage.deployTransaction.wait(6)
        await verify(await simpleStorage.getAddress(), [])
    }
}

async function verify(contractAddress, args) {
    console.log("Verifying contract :)")
    try {
        await run("verify:verify", {
            address: contractAddress,
            constructorArgsParams: args,
        })
    } catch (e) {
        if (e.message.toLowerCase().includes("already verified")) {
            console.log("Already verified!")
        } else {
            console.log(e)
        }
    }
}

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

But then I get the following error:

yarn hardhat run scripts/deploy.js --network sepolia
yarn run v1.22.19
$ /home/user/Documents/learning/blockchain/smart-contracts-learning/hardhat-simple-storage/node_modules/.bin/hardhat run scripts/deploy.js --network sepolia
Deploying contract :)
Deployed contract to: 0x3d3Cf67b7E2110f934a56A8020252421079b1120
TypeError: no matching function (argument="key", value="deployTransaction", code=INVALID_ARGUMENT, version=6.6.1)
    at makeError (/home/user/Documents/learning/blockchain/smart-contracts-learning/hardhat-simple-storage/node_modules/ethers/src.ts/utils/errors.ts:670:21)
    at assert (/home/user/Documents/learning/blockchain/smart-contracts-learning/hardhat-simple-storage/node_modules/ethers/src.ts/utils/errors.ts:694:25)
    at assertArgument (/home/user/Documents/learning/blockchain/smart-contracts-learning/hardhat-simple-storage/node_modules/ethers/src.ts/utils/errors.ts:706:5)
    at Interface.getFunctionName (/home/user/Documents/learning/blockchain/smart-contracts-learning/hardhat-simple-storage/node_modules/ethers/src.ts/abi/interface.ts:542:23)
    at buildWrappedMethod (/home/user/Documents/learning/blockchain/smart-contracts-learning/hardhat-simple-storage/node_modules/ethers/src.ts/contract/contract.ts:334:34)
    at BaseContract.getFunction (/home/user/Documents/learning/blockchain/smart-contracts-learning/hardhat-simple-storage/node_modules/ethers/src.ts/contract/contract.ts:849:22)
    at Object.get (/home/user/Documents/learning/blockchain/smart-contracts-learning/hardhat-simple-storage/node_modules/ethers/src.ts/contract/contract.ts:747:39)
    at main (/home/user/Documents/learning/blockchain/smart-contracts-learning/hardhat-simple-storage/scripts/deploy.js:9:29)
    at processTicksAndRejections (node:internal/process/task_queues:95:5) {
  code: 'INVALID_ARGUMENT',
  argument: 'key',
  value: 'deployTransaction'
}
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

So my question would be, is there a new version of deployTransaction that I should be using? Or which version of hardhat/ethers should I specify with yarn so I can use the code from the course?
Thanks :)

Error: could not decode result data (value="0x", info={ "method": "retrieve", "signature": "retrieve()" }, code=BAD_DATA, version=6.7.1)

When I run the following command, there is an error, and the address given cannot query the transaction information, but the ether of the testnet has decreased, how to solve the following error?

npx hardhat run scripts/deploy.js --network sepolia
Deploying contract...
Deployed contract to: 0x07Dd85d9E00e9C8dB0200ace73ec66C11f4e2f44
Error: could not decode result data (value="0x", info={ "method": "retrieve", "signature": "retrieve()" }, code=BAD_DATA, version=6.7.1)
at makeError (C:\Users\Jamscs\solidity\hardhat-simple-storage-fcc\node_modules\ethers\src.ts\utils\errors.ts:685:21)
at assert (C:\Users\Jamscs\solidity\hardhat-simple-storage-fcc\node_modules\ethers\src.ts\utils\errors.ts:702:25)
at Interface.decodeFunctionResult (C:\Users\Jamscs\solidity\hardhat-simple-storage-fcc\node_modules\ethers\src.ts\abi\interface.ts:916:15)
at staticCallResult (C:\Users\Jamscs\solidity\hardhat-simple-storage-fcc\node_modules\ethers\src.ts\contract\contract.ts:332:35)
at processTicksAndRejections (node:internal/process/task_queues:95:5)
at staticCall (C:\Users\Jamscs\solidity\hardhat-simple-storage-fcc\node_modules\ethers\src.ts\contract\contract.ts:289:24)
at Proxy.retrieve (C:\Users\Jamscs\solidity\hardhat-simple-storage-fcc\node_modules\ethers\src.ts\contract\contract.ts:337:41)
at main (C:\Users\Jamscs\solidity\hardhat-simple-storage-fcc\scripts\deploy.js:16:24) {
code: 'BAD_DATA',
value: '0x',
info: { method: 'retrieve', signature: 'retrieve()' }
}

While i added tasks/block-number.js i face this error

`ratalviper@DESKTOP-MFGC82P:~/hh-fcc/hardhat-simple-storage-fcc$ yarn hardhat
yarn run v1.22.15
$ /home/ratalviper/hh-fcc/hardhat-simple-storage-fcc/node_modules/.bin/hardhat
An unexpected error occurred:

Error: Cannot find module 'hardhart/config'
Require stack:

  • /home/ratalviper/hh-fcc/hardhat-simple-storage-fcc/tasks/block-number.js
  • /home/ratalviper/hh-fcc/hardhat-simple-storage-fcc/hardhat.config.js
  • /home/ratalviper/hh-fcc/hardhat-simple-storage-fcc/node_modules/hardhat/internal/core/config/config-loading.js
  • /home/ratalviper/hh-fcc/hardhat-simple-storage-fcc/node_modules/hardhat/internal/cli/cli.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object. (/home/ratalviper/hh-fcc/hardhat-simple-storage-fcc/tasks/block-number.js:1:18)
    at Module._compile (node:internal/modules/cjs/loader:1103:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19) {
    code: 'MODULE_NOT_FOUND',
    requireStack: [
    '/home/ratalviper/hh-fcc/hardhat-simple-storage-fcc/tasks/block-number.js',
    '/home/ratalviper/hh-fcc/hardhat-simple-storage-fcc/hardhat.config.js',
    '/home/ratalviper/hh-fcc/hardhat-simple-storage-fcc/node_modules/hardhat/internal/core/config/config-loading.js',
    '/home/ratalviper/hh-fcc/hardhat-simple-storage-fcc/node_modules/hardhat/internal/cli/cli.js'
    ]
    }`

block-number
hardhat configPNG

Both screenShots attached for block-number.js & hardhat.cponfig.js
terminal

Coverage plugin broken

I installed the coverage plugin, I even did a hardhat clean but I am still receiving this error:

I googled a bit, but I was unable to find a working solution (even tried installed the 0.8.0-beta.1 coverage plugin did not help.

Please advise.
Thank you!

yarn run v1.22.15
$ /home/sv/hh-fcc/hardhat-simple-storage-fcc/node_modules/.bin/hardhat coverage --show-stack-traces

Version
=======
> solidity-coverage: v0.8.0-beta.1

Instrumenting for coverage...
=============================

> SimpleStorage.sol

Compilation:
============

Nothing to compile
Error in plugin solidity-coverage: TypeError: cur._node._vm.on is not a function

HardhatPluginError: TypeError: cur._node._vm.on is not a function
    at SimpleTaskDefinition.action (/home/sv/hh-fcc/hardhat-simple-storage-fcc/node_modules/solidity-coverage/plugins/hardhat.plugin.js:245:35)
    at Environment._runTaskDefinition (/home/sv/hh-fcc/hardhat-simple-storage-fcc/node_modules/hardhat/src/internal/core/runtime-environment.ts:308:14)
    at Environment.run (/home/sv/hh-fcc/hardhat-simple-storage-fcc/node_modules/hardhat/src/internal/core/runtime-environment.ts:156:14)
    at main (/home/sv/hh-fcc/hardhat-simple-storage-fcc/node_modules/hardhat/src/internal/cli/cli.ts:269:7)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.```

Error: incorrect number of arguments to constructor at ContractFactory.getDeployTransaction

ethers version "6.10.0"
hardhat version "2.19.4"

There seems to be a problem with this piece of code: await SimpleStorageFactory.deploy();

I don't know how to resolve it

const { ethers, run } = require("hardhat");

async function main() {
  const SimpleStorageFactory = await ethers.getContractFactory("SimpleStorage");
  const simpleStorage = await SimpleStorageFactory.deploy();
}

main().catch(error => {
  console.error(error);
  process.exitCode = 1;
});

JsonRpcProvider is not found

the error i got

node deploy.js
TypeError: Cannot read properties of undefined (reading 'JsonRpcProvider')
    at main (/home/santhiya_1321/hh-fcc/ethers-simple-storage-fcc/deploy.js:6:41)
    at Object.<anonymous> (/home/santhiya_1321/hh-fcc/ethers-simple-storage-fcc/deploy.js:27:1)
    at Module._compile (node:internal/modules/cjs/loader:1103:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47
const { ethers } = require("ethers");
const fs = require("fs-extra");

// async main
async function main() {
  const provider = new ethers.providers.JsonRpcProvider(
    "HTTP://127.0.0.1:7545"
  );

  const wallet = new ethers.Wallet(
    "0x284ede9545b2639b2ec29a5bc7a78cade4d320470a7a99eb560a700017dc591b",
    provider
  );
  const abi = fs.readFileSync("./SimpleStorage_sol_SimpleStorage.abi", "utf-8");
  const binary = fs.readFileSync(
    "./SimpleStorage_sol_SimpleStorage.bin",
    "utf-8"
  );

  const contractFactory = new ethers.ContractFactory(abi, binary, wallet);
  console.log("Please wait we are deploying our contract");
  //code to deploy our contract
  const contract = await contractFactory.deploy();
}

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

Solution: Error when running Deploy.JS with verify function

Hi all,

Posting this here just in case you run into the same problem and require a solution:

If you follow along with the code for the verification step (09:06:20 in the video) you'll notice that Patrick skips over the actual testing of the verification step. However, if you are running the code anyway to try and verify by deploying the script as it stands (running "yarn hardhat run scripts/deploy.js --network rinkeby" with the verify function in your code) you might run into the following error:

[Error: ENOENT: no such file or directory, open 'C:\Users.....
errno: -4058,
code: 'ENOENT',
syscall: 'open',
path: 'C:\Users....

Should this happen to you there is an easy fix. Try "yarn hardhat clean" in your terminal and then once again proceed to run "yarn hardhat run scripts/deploy.js --network rinkeby". This should resolve the issue.

Thanks Patrick for the great course and for anyone and everyone else: good luck on your coding endeavors.

Can't retrive contract address

Hi everyone

I am in chapter 6 and currently deploying on the sepolia test network.
The deployment is working but veryfing is failing.

The problem lies in these two lines:

  console.log(`Deployed contract to: ${simpleStorage.address}`); &
  await verify(simpleStorage.address, []);

The console gives a hint:
Deployed contract to: undefined

For some reason, I can't read the address of the deployed contract.

The rest of the code:

const { ethers, run, network } = require("hardhat");

async function main() {
  const SimpleStorageFactory = await ethers.getContractFactory("SimpleStorage");
  console.log("Deploying contract...");
  const simpleStorage = await SimpleStorageFactory.deploy();
  await simpleStorage.waitForDeployment();
  console.log(`Deployed contract to: ${simpleStorage.address}`);
  if (network.config.chainId === 11155111 && process.env.ETHERSCAN_API_KEY) {
    await simpleStorage.deploymentTransaction().wait(6);
    await verify(simpleStorage.address, []);
    console.log(network.config);
  }
}

async function verify(contractAddress, args) {
  console.log("Verifiying contract...");
  try {
    await run("verify:verify", {
      address: contractAddress,
      constructorArguments: args,
    });
  } catch (e) {
    // e = any error
    if (e.message.toLowerCase().includes("already verified")) {
      console.log("Already verified!");
    } else {
      console.log(e);
    }
  }
}

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

Received error TypeError: simpleStorage.deployed is not a function

The error you encountered is due to a change in the Ethers.js library. Let’s address this step by step:

The function deployed() has been deprecated and is no longer available.
Instead, you should use waitForDeployment().

Corrected Code:
Replace await simpleStorage.deployed(); with await simpleStorage.waitForDeployment();.
This change should resolve the issue.

Hope this helps someone!

unable to run the script

An unexpected error occurred:

Error: Cannot find module './tasks/block-number'
Require stack:

  • C:\Users\rs851\OneDrive\Desktop\ether-simple-storage\hardhat-simple-storage\hardhat.config.js
  • C:\Users\rs851\OneDrive\Desktop\ether-simple-storage\hardhat-simple-storage\node_modules\hardhat\internal\core\config\config-loading.js
  • C:\Users\rs851\OneDrive\Desktop\ether-simple-storage\hardhat-simple-storage\node_modules\hardhat\internal\cli\cli.js
  • C:\Users\rs851\OneDrive\Desktop\ether-simple-storage\hardhat-simple-storage\node_modules\hardhat\internal\cli\bootstrap.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:1075:15)
    at Function.Module._load (node:internal/modules/cjs/loader:920:27)
    at Module.require (node:internal/modules/cjs/loader:1141:19)
    at require (node:internal/modules/cjs/helpers:110:18)
    at Object. (C:\Users\rs851\OneDrive\Desktop\ether-simple-storage\hardhat-simple-storage\hardhat.config.js:3:1)
    at Module._compile (node:internal/modules/cjs/loader:1254:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1308:10)
    at Module.load (node:internal/modules/cjs/loader:1117:32)
    at Function.Module._load (node:internal/modules/cjs/loader:958:12)
    at Module.require (node:internal/modules/cjs/loader:1141:19) {
    code: 'MODULE_NOT_FOUND',
    requireStack: [
    'C:\Users\rs851\OneDrive\Desktop\ether-simple-storage\hardhat-simple-storage\hardhat.config.js',
    'C:\Users\rs851\OneDrive\Desktop\ether-simple-storage\hardhat-simple-storage\node_modules\hardhat\internal\core\config\config-loading.js',
    'C:\Users\rs851\OneDrive\Desktop\ether-simple-storage\hardhat-simple-storage\node_modules\hardhat\internal\cli\cli.js',
    'C:\Users\rs851\OneDrive\Desktop\ether-simple-storage\hardhat-simple-storage\node_modules\hardhat\internal\cli\bootstrap.js'
    ]
    }
    error Command failed with exit code 1.
    info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

yarn hardhat run scripts/deploy.js --network rinkeby

Error HH801: Plugin @nomicfoundation/hardhat-toolbox requires the following dependencies to be installed: @nomicfoundation/hardhat-network-helpers, @nomicfoundation/hardhat-chai-matchers, @types/mocha, @typechain/ethers-v5, @typechain/hardhat, ts-node, typescript.

Error HH8: There's one or more errors in your config file:

After adding Etherscan ABI to hardhat.config, i was trying to verify with yarn hardhat, then i ran into this error,

  • Invalid value undefined for HardhatConfig.networks.rinkeby.url - Expected a value of type string.
    • Invalid account: #0 for network: rinkeby - Expected string, received undefined

To learn more about Hardhat's configuration, please go to https://hardhat.org/config/

below is my hardhat.config
require("@nomiclabs/hardhat-waffle");
require("dotenv").config()
require("@nomiclabs/hardhat-etherscan")
// This is a sample Hardhat task. To learn how to create your own go to
// https://hardhat.org/guides/create-task.html
task("accounts", "Prints the list of accounts", async (taskArgs, hre) => {
const accounts = await hre.ethers.getSigners();

for (const account of accounts) {
console.log(account.address);
}
});

// You need to export an object to set up your config
// Go to https://hardhat.org/config/ to learn more

/**

  • @type import('hardhat/config').HardhatUserConfig
    */
    const RINKEBY_RPC_URL=process.env.RINKEBY_RPC_URL
    const PRIVATE_KEY=process.env.PRIVATE_KEY
    const ETHERSCAN_API_KEY=process.env.ETHERSCAN_API_KEY

module.exports = {
defaultNetwork:"hardhat",
networks:{
rinkeby:{
url:RINKEBY_RPC_URL,
accounts:[PRIVATE_KEY],
chainId:4,

},

},
solidity: "0.8.8",
etherscan:{
apikey:ETHERSCAN_API_KEY,
}
};

Chaper 8: Error: Cannot find module './tasks/block-number'

yarn hardhat run scripts/deploy.js
when ever I am running this command, it's shows this Error

An unexpected error occurred:

Error: Cannot find module './tasks/block-number'
Require stack:
- /root/folder/hardhat-simple-storage-fcc/hardhat.config.js
- /root/folder/hardhat-simple-storage-fcc/node_modules/hardhat/internal/core/config/config-loading.js
- /root/folder/hardhat-simple-storage-fcc/node_modules/hardhat/internal/cli/cli.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (/root/folder/hardhat-simple-storage-fcc/hardhat.config.js:3:1)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/root/folder/hardhat-simple-storage-fcc/hardhat.config.js',
    '/root/folder/hardhat-simple-storage-fcc/node_modules/hardhat/internal/core/config/config-loading.js',
    '/root/folder/hardhat-simple-storage-fcc/node_modules/hardhat/internal/cli/cli.js'
  ]
}
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

TypeError: Test argument "title" should be a string. Received type "undefined"

I'm trying to run

yarn hardhat test

here is my code

const { assert } = require("chai")
const { ethers } = require("hardhat")

describe("SimpleStorage", function () {
 
    let simpleStorageFactory, simpleStorage

    beforeEach(async function () {
        simpleStorageFactory = await ethers.getContracttFactory(
            "SinmpleStorage"
        )
        simpleStorage = await simpleStorageFactory.deploy()
    })
    it("Shoule start with a favorite number of 0", async function () {
        const currentValue = await simpleStorage.retrieve()
        const expectedValue = "0"
        // expect
        assert.equal(currentValue.toString(), expectedValue)
    })
    // it()
})

And this is the error

yarn run v1.22.19
$ /home/minomeis/hh-fcc/hardhat-simple-storage-fcc/node_modules/.bin/hardhat test
An unexpected error occurred:

TypeError: Test argument "title" should be a string. Received type "undefined"
    at createInvalidArgumentTypeError (/home/minomeis/hh-fcc/hardhat-simple-storage-fcc/node_modules/mocha/lib/errors.js:268:13)
    at new Test (/home/minomeis/hh-fcc/hardhat-simple-storage-fcc/node_modules/mocha/lib/test.js:23:11)
    at context.it.context.specify (/home/minomeis/hh-fcc/hardhat-simple-storage-fcc/node_modules/mocha/lib/interfaces/bdd.js:87:18)
    at Suite.<anonymous> (/home/minomeis/hh-fcc/hardhat-simple-storage-fcc/test/test-deploy.js:25:5)
    at Object.create (/home/minomeis/hh-fcc/hardhat-simple-storage-fcc/node_modules/mocha/lib/interfaces/common.js:148:19)
    at context.describe.context.context (/home/minomeis/hh-fcc/hardhat-simple-storage-fcc/node_modules/mocha/lib/interfaces/bdd.js:42:27)
    at Object.<anonymous> (/home/minomeis/hh-fcc/hardhat-simple-storage-fcc/test/test-deploy.js:9:1)
    at Module._compile (node:internal/modules/cjs/loader:1112:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1166:10)
    at Module.load (node:internal/modules/cjs/loader:988:32) {
  code: 'ERR_MOCHA_INVALID_ARG_TYPE',
  argument: 'title',
  expected: 'string',
  actual: 'string'
}
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

I've already search on Google but doesn't find the solution,could somebody can help me thanks!

PLEASE HELP! Cannot find module '@nomicfoundation/hardhat-toolbox

const {ethers} = require("hardhat")
    //**my package.json doesnt look same as patrick's as well, it's lacking a lot of files**
async function main() {
    const SimpleStorageFactory = await ethers.getContractFactory("SimpleStorage")
    console.log("DEploying COntract..")

    const simpleStorage= await SimpleStorageFactory.deploy();
    await simpleStorage.deployed()


}

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

  

yarn hardhat run scripts/deploy.js
yarn run v1.22.19
warning ../../../package.json: No license field
$ /Users/pranjay/Desktop/etherr/hardhat-simple-storage-fcc/node_modules/.bin/hardhat run scripts/deploy.js
An unexpected error occurred:

Error: Cannot find module '@nomicfoundation/hardhat-toolbox'
Require stack:

  • /Users/pranjay/Desktop/etherr/hardhat-simple-storage-fcc/hardhat.config.js
  • /Users/pranjay/Desktop/etherr/hardhat-simple-storage-fcc/node_modules/hardhat/internal/core/config/config-loading.js
  • /Users/pranjay/Desktop/etherr/hardhat-simple-storage-fcc/node_modules/hardhat/internal/cli/cli.js
  • /Users/pranjay/Desktop/etherr/hardhat-simple-storage-fcc/node_modules/hardhat/internal/cli/bootstrap.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:1077:15)
    at Function.Module._load (node:internal/modules/cjs/loader:922:27)
    at Module.require (node:internal/modules/cjs/loader:1143:19)
    at require (node:internal/modules/cjs/helpers:110:18)
    at Object. (/Users/pranjay/Desktop/etherr/hardhat-simple-storage-fcc/hardhat.config.js:1:1)
    at Module._compile (node:internal/modules/cjs/loader:1256:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
    at Module.load (node:internal/modules/cjs/loader:1119:32)
    at Function.Module._load (node:internal/modules/cjs/loader:960:12)
    at Module.require (node:internal/modules/cjs/loader:1143:19) {
    code: 'MODULE_NOT_FOUND',
    requireStack: [
    '/Users/pranjay/Desktop/etherr/hardhat-simple-storage-fcc/hardhat.config.js',
    '/Users/pranjay/Desktop/etherr/hardhat-simple-storage-fcc/node_modules/hardhat/internal/core/config/config-loading.js',
    '/Users/pranjay/Desktop/etherr/hardhat-simple-storage-fcc/node_modules/hardhat/internal/cli/cli.js',
    '/Users/pranjay/Desktop/etherr/hardhat-simple-storage-fcc/node_modules/hardhat/internal/cli/bootstrap.js'
    ]
    }
    error Command failed with exit code 1.
    info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Error while running the deploy.js file

Code:

require("@nomicfoundation/hardhat-toolbox")
require("dotenv").config()

const SEPOLIA_RPC_URL = process.env.SEPOLIA_RPC_URL
const PRIVATE_KEY = process.env.PRIVATE_KEY

/** @type import('hardhat/config').HardhatUserConfig */

module.exports = {
    defaultNetwork: "hardhat",
    networks: {
        sepolia: {
            URL: SEPOLIA_RPC_URL,
            account: [PRIVATE_KEY],
            chainId: 11155111,
        },
    },
    solidity: "0.8.8",
}

Error:

~/folder/hardhat-fcc$ yarn hardhat run ignition/deploy.js --network sepolia
yarn run v1.22.22
$ /home/chakra/folder/hardhat-fcc/node_modules/.bin/hardhat run ignition/deploy.js --network sepolia
Error HH8: There's one or more errors in your config file:

  * Invalid value undefined for HardhatConfig.networks.sepolia.url - Expected a value of type string.

To learn more about Hardhat's configuration, please go to https://hardhat.org/config/

For more info go to https://hardhat.org/HH8 or run Hardhat with --show-stack-traces
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Verifying contract... Verification failed: UnexpectedError: An unexpected error occurred during the verification process. Please report this issue to the Hardhat team. Error Details: Invalid API Key

const { ethers, run, network } = require("hardhat")
require("@nomicfoundation/hardhat-verify")

async function verifyContract() {
const chainId = network.config.chainId

const simpleStorageFactory =
    await ethers.getContractFactory("SimpleStorage")

const args = []

console.log(`Deploying...`)
const simpleStorage = await simpleStorageFactory.deploy(...args)
await simpleStorage.waitForDeployment()
console.log(`Deployed!`)
console.log(`Simple Storage Address: ${simpleStorage.target}`)

console.log(`Waiting for block confirmations...`)
await simpleStorage.waitForDeployment() // Wait for 1 confirmation
console.log(`Confirmed!`)

// Only verify on testnets or mainnets.
if (chainId != 31337 && process.env.ETHERSCAN_API_KEY) {
    await simpleStorage.waitForDeployment(6)
    await verify(simpleStorage.target, args) // Passing the target for verification
}

const currentValue = await simpleStorage.retrieve()
console.log(`Current Value is: ${currentValue}`)

const transactionResponse = await simpleStorage.store(7)
await transactionResponse.wait(1)
const updatedValue = await simpleStorage.retrieve()
console.log(`Updated Value is: ${updatedValue}`)

}

const verify = async (contractTarget, args) => {
// Changed parameter name from contractAddress to contractTarget
console.log("Verifying contract...")
try {
await run("verify:verify", {
address: contractTarget, // Changed from address to contractTarget
constructorArguments: args,
})
console.log("Verification successful!")
} catch (e) {
if (e.message.toLowerCase().includes("already verified")) {
console.log("Already verified!")
} else {
console.log("Verification failed:", e)
}
}
}

verifyContract()
.then(() => process.exit(0))
.catch((error) => {
console.error("Error:", error)
process.exit(1)
})

Calling addPerson function in deploy.js and writing its test case in test.js

Hello,
I've just opened this issue to show, how to call addPerson function in deploy.js and writing its test case in test.js, in order to test all the lines of SimpleStorage.sol.

deploy.js

console.log("Adding person...")
    await addPerson(simpleStorage, "Bilge Kaan Gençdoğan", 7)

    async function addPerson(contract, name, favoriteNumber) {
        const transaction = await contract.addPerson(name, favoriteNumber)
        await transaction.wait()
        console.log("Person added successfully.")
    }

test.js

    it("Adding people and their favorite number to Mapping", async function () {
        const expectedPerson = {
            name: "Bilge Kaan Gençdoğan",
            favoriteNumber: "7",
        }

        // Call the addPerson function
        await addPerson(expectedPerson.name, expectedPerson.favoriteNumber)

        // Retrieve the favorite number for the added person
        const favoriteNumber = await simpleStorage.nameToFavoriteNumber(
            expectedPerson.name,
        )

        // Assert that the favorite number matches the expected value
        assert.equal(favoriteNumber.toString(), expectedPerson.favoriteNumber)

        // Retrieve the person's details from the contract
        const person = await getPerson(expectedPerson.name)

        // Assert that the retrieved person's details match the expected values
        assert.equal(person.name, expectedPerson.name)
        assert.equal(
            person.favoriteNumber.toString(),
            expectedPerson.favoriteNumber,
        )
    })

    // Function to add a person
    async function addPerson(name, favoriteNumber) {
        const transaction = await simpleStorage.addPerson(name, favoriteNumber)
        await transaction.wait()
        console.log("Person added successfully.")
    }

    // Function to retrieve a person's details from the contract
    async function getPerson(name) {
        const favoriteNumber = await simpleStorage.nameToFavoriteNumber(name)
        return { name, favoriteNumber }
    }
}

With these line of code, if you run "yarn hardhat coverage" you will see that you test all your code.

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.