GithubHelp home page GithubHelp logo

hardhat-smartcontract-lottery-fcc's Introduction

Update: Head to Cyfrin Updraft

ℹ️ Important: This repo is no longer maintained, we invite all people learning Solidtiy to head to Cyfrin Updraft! The 100% free #1 smart contract education platform on earth.

Hardhat Smartcontract Lottery (Raffle) FCC

This repo has been updated to work with Sepolia over Goerli.

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

⌨️ (13:41:02) Lesson 9: Hardhat Smart Contract Lottery

Full Repo

This project is apart of the Hardhat FreeCodeCamp video.

Checkout the full blockchain course video here.

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
      • It'll need to be at least 18.16.0 of node
  • 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-smartcontract-lottery-fcc
cd hardhat-smartcontract-lottery-fcc
yarn

Typescript

If you want to get to typescript and you cloned the javascript version, just run:

git checkout typescript
yarn 

Usage

Deploy:

yarn hardhat deploy

Testing

yarn hardhat test

Test Coverage

yarn hardhat coverage

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 testnet ETH & LINK. You should see the ETH and LINK show up in your metamask. You can read more on setting up your wallet with LINK.

  1. Setup a Chainlink VRF Subscription ID

Head over to vrf.chain.link and setup a new subscription, and get a subscriptionId. You can reuse an old subscription if you already have one.

You can follow the instructions if you get lost. You should leave this step with:

  1. A subscription ID

  2. Your subscription should be funded with LINK

  3. Deploy

In your helper-hardhat-config.js add your subscriptionId under the section of the chainId you're using (aka, if you're deploying to sepolia, add your subscriptionId in the subscriptionId field under the 11155111 section.)

Then run:

yarn hardhat deploy --network sepolia

And copy / remember the contract address.

  1. Add your contract address as a Chainlink VRF Consumer

Go back to vrf.chain.link and under your subscription add Add consumer and add your contract address. You should also fund the contract with a minimum of 1 LINK.

  1. Register a Chainlink Keepers Upkeep

You can follow the documentation if you get lost.

Go to keepers.chain.link and register a new upkeep. Choose Custom logic as your trigger mechanism for automation. Your UI will look something like this once completed:

Keepers

  1. Enter your raffle!

Your contract is now setup to be a tamper proof autonomous verifiably random lottery. Enter the lottery by running:

yarn hardhat run scripts/enter.js --network sepolia

Estimate gas cost in USD

To get a USD estimation of gas cost, you'll need a COINMARKETCAP_API_KEY environment variable. You can get one for free from CoinMarketCap.

Then, uncomment the line coinmarketcap: COINMARKETCAP_API_KEY, in hardhat.config.js to get the USD estimation. Just note, everytime you run your tests it will use an API call, so it might make sense to have using coinmarketcap disabled until you need it. You can disable it by just commenting the line back out.

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 its current state, if you have your api key set, it will auto verify sepolia contracts!

However, you can manual verify with:

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

Typescript differences

  1. .js files are now .ts
  2. We added a bunch of typescript and typing packages to our package.json. They can be installed with:
    1. yarn add @typechain/ethers-v5 @typechain/hardhat @types/chai @types/node ts-node typechain typescript
  3. The biggest one being typechain
    1. This gives your contracts static typing, meaning you'll always know exactly what functions a contract can call.
    2. This gives us factories that are specific to the contracts they are factories of. See the tests folder for a version of how this is implemented.
  4. We use imports instead of require. Confusing to you? Watch this video
  5. Add tsconfig.json

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-smartcontract-lottery-fcc's People

Contributors

aayush-gupta-coder avatar akinsikuoluwafemi avatar alymurtazamemon avatar buikhacnam avatar harendra-shakya avatar ippy1997 avatar joonakauranen avatar krakxn avatar labib147 avatar mikechaban avatar moayaan1911 avatar nagrarohit avatar nicphang1011 avatar nubshark avatar othaime-en avatar patrickalphac avatar ramansb avatar rin-st avatar robocrypter avatar rohitks7 avatar salaimuniselvam-s avatar sebastianovide avatar sjcodebook avatar soos3d avatar stevegee1 avatar timi-t avatar uday03meh avatar zeitseeing 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  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  avatar  avatar  avatar  avatar  avatar

hardhat-smartcontract-lottery-fcc's Issues

Error HH606: The project cannot be compiled, see reasons below.

Hey guys can anyone help? each time I run "yarn hardhat test," I get the below response.. PS: I have tried changing my Raffle.sol to ^0.8.0, but I guess that's not the way to to around this.

The Solidity version pragma statement in these files doesn't match any of the configured compilers in your config. Change the pragma or configure additional compiler versions in your hardhat config.

contracts/Raffle.sol (^0.8.7)
@chainlink/contracts/src/v0.8/interfaces/KeeperCompatibleInterface.sol (^0.8.0)
@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol (^0.8.0)
@chainlink/contracts/src/v0.8/mocks/VRFCoordinatorV2Mock.sol (^0.8.4)
@chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol (^0.8.4)
@chainlink/contracts/src/v0.8/interfaces/LinkTokenInterface.sol (^0.8.0)
contracts/test/VRFCoordinatorV2Mock.sol (^0.8.0)
To learn more, run the command again with --verbose
Read about compiler configuration at https://hardhat.org/config

ERROR processing skip func of Error: value must be a string

I'm trying to deploy the VRFCoordinator but getting this error
Error: ERROR processing skip func D:\blockchain-dev\hardhat-lottery\deploy\00-deploy-mocks.js:
Error: value must be a string (argument="value", value=0.01, code=INVALID_ARGUMENT, version=units/5.7.0)

My VRFCoordinatorMockV2 deploy is:

`const { developmentChains } = require('../helper-hardhat-config');
const { network, ethers } = require("hardhat");

const BASE_FEE = ethers.utils.parseEther("0.25");
const GAS_PRICE_LINK = 1e9;

module.exports = async function ({ getNamedAccounts, deployments }) {
const { deploy, log } = deployments;
const { deployer } = await getNamedAccounts();

const args = [BASE_FEE, GAS_PRICE_LINK];

if (developmentChains.includes(network.name)) {
    log("Localhost detected");
    //Deploy mock
    await deploy("VRFCoordinatorV2Mock", {
        from: deployer,
        log: true,
        args: args,

    });
    log("Mock Deployed");
    log("---------------------------------");
}

}
`

Here I'm parsing the ether and tried GAS_PRICE_LINK with 100000000 but still getting the same error with no luck.

I tried to replicate the same with Remix and got successfully deployed. but in deployment it's getting stuck on the same error.

Why do we use "public" instead of "external" for our getters?

Hi everyone, great course, congrats Patrick!
I do have a question related to our getters. Why do we use "public" keyword instead of "external". From my knowledge, external is more gas efficient than public.
Code exemple from course:

    function getEntrenceFee() public view returns (uint256) {
        return i_entrenceFee;
    }

    function getPlayer(uint256 index) public view returns (address) {
        return s_players[index];
    }

    function getRecentWinner() public view returns (address) {
        return s_recentWinner;
    }

    function getRaffleState() public view returns (RaffleState){
        return s_raffleState;
    }

unit test fail

I clone this repo,then i run unit test,I got error:

Raffle Unit Tests
    constructor
31337
      ✔ intitiallizes the raffle correctly
    enterRaffle
      ✔ reverts when you don't pay enough
      ✔ records player when they enter
      ✔ emits event on enter
      1) doesn't allow entrance when raffle is calculating
    checkUpkeep
      ✔ returns false if people haven't sent any ETH
      2) returns false if raffle isn't open
      ✔ returns false if enough time hasn't passed
      ✔ returns true if enough time has passed, has players, eth, and is open
    performUpkeep
      3) can only run if checkupkeep is true
      ✔ reverts if checkup is false
      4) updates the raffle state and emits a requestId
    fulfillRandomWords
      ✔ can only be called after performupkeep
      5) picks a winner, resets, and sends money


  9 passing (3m)
  5 failing

  **1) Raffle Unit Tests
       enterRaffle
         doesn't allow entrance when raffle is calculating:
     Error: VM Exception while processing transaction: reverted with custom error 'InvalidConsumer()'
    at VRFCoordinatorV2Mock.onlyValidConsumer (@chainlink/contracts/src/v0.8/mocks/VRFCoordinatorV2Mock.sol:72)
    at VRFCoordinatorV2Mock.requestRandomWords (@chainlink/contracts/src/v0.8/mocks/VRFCoordinatorV2Mock.sol:147)
    at Raffle.performUpkeep (contracts/Raffle.sol:127)
    at async HardhatNode._mineBlockWithPendingTxs (node_modules/.pnpm/[email protected]_6oasmw356qmm23djlsjgkwvrtm/node_modules/hardhat/src/internal/hardhat-network/provider/node.ts:1773:23)
    at async HardhatNode.mineBlock (node_modules/.pnpm/[email protected]_6oasmw356qmm23djlsjgkwvrtm/node_modules/hardhat/src/internal/hardhat-network/provider/node.ts:466:16)
    at async EthModule._sendTransactionAndReturnHash (node_modules/.pnpm/[email protected]_6oasmw356qmm23djlsjgkwvrtm/node_modules/hardhat/src/internal/hardhat-network/provider/modules/eth.ts:1504:18)
    at async HardhatNetworkProvider.request (node_modules/.pnpm/[email protected]_6oasmw356qmm23djlsjgkwvrtm/node_modules/hardhat/src/internal/hardhat-network/provider/provider.ts:118:18)
    at async EthersProviderWrapper.send (node_modules/.pnpm/[email protected]_72jgnctblym52z6vqt46lbuldu/node_modules/hardhat-deploy-ethers/src/internal/ethers-provider-wrapper.ts:13:20)
  

  2) Raffle Unit Tests
       checkUpkeep
         returns false if raffle isn't open:
     Error: VM Exception while processing transaction: reverted with custom error 'InvalidConsumer()'
    at VRFCoordinatorV2Mock.onlyValidConsumer (@chainlink/contracts/src/v0.8/mocks/VRFCoordinatorV2Mock.sol:72)
    at VRFCoordinatorV2Mock.requestRandomWords (@chainlink/contracts/src/v0.8/mocks/VRFCoordinatorV2Mock.sol:147)
    at Raffle.performUpkeep (contracts/Raffle.sol:127)
    at async HardhatNode._mineBlockWithPendingTxs (node_modules/.pnpm/[email protected]_6oasmw356qmm23djlsjgkwvrtm/node_modules/hardhat/src/internal/hardhat-network/provider/node.ts:1773:23)
    at async HardhatNode.mineBlock (node_modules/.pnpm/[email protected]_6oasmw356qmm23djlsjgkwvrtm/node_modules/hardhat/src/internal/hardhat-network/provider/node.ts:466:16)
    at async EthModule._sendTransactionAndReturnHash (node_modules/.pnpm/[email protected]_6oasmw356qmm23djlsjgkwvrtm/node_modules/hardhat/src/internal/hardhat-network/provider/modules/eth.ts:1504:18)
    at async HardhatNetworkProvider.request (node_modules/.pnpm/[email protected]_6oasmw356qmm23djlsjgkwvrtm/node_modules/hardhat/src/internal/hardhat-network/provider/provider.ts:118:18)
    at async EthersProviderWrapper.send (node_modules/.pnpm/[email protected]_72jgnctblym52z6vqt46lbuldu/node_modules/hardhat-deploy-ethers/src/internal/ethers-provider-wrapper.ts:13:20)
  

  3) Raffle Unit Tests
       performUpkeep
         can only run if checkupkeep is true:
     Error: VM Exception while processing transaction: reverted with custom error 'InvalidConsumer()'
    at VRFCoordinatorV2Mock.onlyValidConsumer (@chainlink/contracts/src/v0.8/mocks/VRFCoordinatorV2Mock.sol:72)
    at VRFCoordinatorV2Mock.requestRandomWords (@chainlink/contracts/src/v0.8/mocks/VRFCoordinatorV2Mock.sol:147)
    at Raffle.performUpkeep (contracts/Raffle.sol:127)
    at async HardhatNode._mineBlockWithPendingTxs (node_modules/.pnpm/[email protected]_6oasmw356qmm23djlsjgkwvrtm/node_modules/hardhat/src/internal/hardhat-network/provider/node.ts:1773:23)
    at async HardhatNode.mineBlock (node_modules/.pnpm/[email protected]_6oasmw356qmm23djlsjgkwvrtm/node_modules/hardhat/src/internal/hardhat-network/provider/node.ts:466:16)
    at async EthModule._sendTransactionAndReturnHash (node_modules/.pnpm/[email protected]_6oasmw356qmm23djlsjgkwvrtm/node_modules/hardhat/src/internal/hardhat-network/provider/modules/eth.ts:1504:18)
    at async HardhatNetworkProvider.request (node_modules/.pnpm/[email protected]_6oasmw356qmm23djlsjgkwvrtm/node_modules/hardhat/src/internal/hardhat-network/provider/provider.ts:118:18)
    at async EthersProviderWrapper.send (node_modules/.pnpm/[email protected]_72jgnctblym52z6vqt46lbuldu/node_modules/hardhat-deploy-ethers/src/internal/ethers-provider-wrapper.ts:13:20)
  

  4) Raffle Unit Tests
       performUpkeep
         updates the raffle state and emits a requestId:
     Error: VM Exception while processing transaction: reverted with custom error 'InvalidConsumer()'
    at VRFCoordinatorV2Mock.onlyValidConsumer (@chainlink/contracts/src/v0.8/mocks/VRFCoordinatorV2Mock.sol:72)
    at VRFCoordinatorV2Mock.requestRandomWords (@chainlink/contracts/src/v0.8/mocks/VRFCoordinatorV2Mock.sol:147)
    at Raffle.performUpkeep (contracts/Raffle.sol:127)
    at async HardhatNode._mineBlockWithPendingTxs (node_modules/.pnpm/[email protected]_6oasmw356qmm23djlsjgkwvrtm/node_modules/hardhat/src/internal/hardhat-network/provider/node.ts:1773:23)
    at async HardhatNode.mineBlock (node_modules/.pnpm/[email protected]_6oasmw356qmm23djlsjgkwvrtm/node_modules/hardhat/src/internal/hardhat-network/provider/node.ts:466:16)
    at async EthModule._sendTransactionAndReturnHash (node_modules/.pnpm/[email protected]_6oasmw356qmm23djlsjgkwvrtm/node_modules/hardhat/src/internal/hardhat-network/provider/modules/eth.ts:1504:18)
    at async HardhatNetworkProvider.request (node_modules/.pnpm/[email protected]_6oasmw356qmm23djlsjgkwvrtm/node_modules/hardhat/src/internal/hardhat-network/provider/provider.ts:118:18)
    at async EthersProviderWrapper.send (node_modules/.pnpm/[email protected]_72jgnctblym52z6vqt46lbuldu/node_modules/hardhat-deploy-ethers/src/internal/ethers-provider-wrapper.ts:13:20)
  

  5) Raffle Unit Tests
       fulfillRandomWords
         picks a winner, resets, and sends money:
     Error: Timeout of 200000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/Users/sh06010ml2/Documents/workspaces/learns/lottery-test/test/unit/Raffle.test.ts)
      at listOnTimeout (node:internal/timers:559:17)
      at processTimers (node:internal/timers:502:7)**


Lesson 9: unittesting checkUpkeep.not_enough_time_passed failing

The "returns false if not enough time has passed" test fails, because upkeepNeeded returns true for time changes to close to the chosen interval.
With

await network.provider.send("evm_increaseTime", [interval - 3])

it works. It also works if I use [interval - 3] and comment out

await network.provider.request({ method: "evm_mine", params: [] })

Any ideas on how this might be caused?
Could it maybe be that it takes too long locally, so that 2 blocks are mined and the state already changes before assertion?

it("returns false if not enough time has passed", async () => {
            await raffle.enterRaffle({ value: raffleEntranceFee })
            await network.provider.send("evm_increaseTime", [interval - 1])
            await network.provider.request({ method: "evm_mine", params: [] })
            const { upkeepNeeded } = await raffle.callStatic.checkUpkeep("0x")
            //console.log(upkeepNeeded)
            assert(!upkeepNeeded)
        })

Peer dependency issue with Hardhat and Chainlink/Contracts

There is a peer dependency issue between Hardhat-ethers version and @chainlink/contracts package. I tried using --force but now hardhat is not compatible and getting a Error HH12: Trying to use a non-local installation of Hardhat, which is not supported. Please install Hardhat locally using npm or Yarn, and try again. error. How can I resolve this?

image

Error: Timeout of 300000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

i am facing this error i try many times , compare with other repositories but i am stuck on this error
its show perfom keepup but show pending on Vrf Subscription
i want to continue but stuck on this
my subscription id : 6212
keeper address : 0xD7205DF9b824248BA5EEec17DD7Bb21f658E5658
my contract address : https://rinkeby.etherscan.io/address/0xD7205DF9b824248BA5EEec17DD7Bb21f658E5658
my repo : https://github.com/mubashirhussainkhadim/hardhat-lottery
` Raffle Unit Tests
fulfillRandomWords
Setting up test...
Setting up Listener...
Entering Raffle...
Ok, time to wait...
1) works with live Chainlink Keepers and Chainlink VRF, we get a random winner

0 passing (5m)
1 failing

  1. Raffle Unit Tests
    fulfillRandomWords
    works with live Chainlink Keepers and Chainlink VRF, we get a random winner:
    Error: Timeout of 300000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/Users/mubashirkhadim/Downloads/hardhat-smartcontract-lottery-main/test/staging/Raffle.staging.test.js)
    at listOnTimeout (node:internal/timers:559:17)
    at processTimers (node:internal/timers:502:7)`

Screenshot 2022-06-10 at 5 12 55 AM

Screenshot 2022-06-10 at 5 13 37 AM

Screenshot 2022-06-10 at 5 16 34 AM

Lottery.staging.test.js AssertionError

When I run
hh test --network rinkeby
on my Lottery.staging.test.js file, I get the following output:

 Lottery Unit Tests
    fulfillRandomWords
Setting up test...
Setting up Listener...
Entering Lottery...
Ok, time to wait...
WinnerPicked event fired!
AssertionError: expected '781901563946176163' to equal '791970612949076221'
    at FragmentRunningEvent.<anonymous> (/home/greaver/FullStack/hardhat-smartcontract-lottery-fcc/test/staging/Lottery.staging.test.js:49:38)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  showDiff: true,
  actual: '781901563946176163',
  expected: '791970612949076221',
  operator: 'strictEqual'
}

After the error, it hangs, until the Mocha 500 second timeout in my hardhat.config.js file kicks in with:
Error: Timeout of 500000ms exceeded.

My Lottery.staging.test.js code is the same as Patrick's atm because I wanted it to work (mine is below this code commented out (not included here)...:

const { assert, expect } = require("chai");
const { getNamedAccounts, deployments, ethers, network } = require("hardhat");
const {
    developmentChains,
    networkConfig,
} = require("../../helper-hardhat-config");

developmentChains.includes(network.name)
    ? describe.skip
    : describe("Lottery Unit Tests", function () {
          let lottery, LotteryEntranceFee, deployer;

          beforeEach(async function () {
              deployer = (await getNamedAccounts()).deployer;
              lottery = await ethers.getContract("Lottery", deployer);
              lotteryEntranceFee = await lottery.getEntranceFee();
          });

          describe("fulfillRandomWords", function () {
              it("works with live Chainlink Keepers and Chainlink VRF, we get a random winner", async function () {
                  // enter the lottery
                  console.log("Setting up test...");
                  const startingTimeStamp = await lottery.getLatestTimeStamp();
                  const accounts = await ethers.getSigners();

                  console.log("Setting up Listener...");
                  await new Promise(async (resolve, reject) => {
                      // setup listener before we enter the raffle
                      // Just in case the blockchain moves REALLY fast
                      lottery.once("WinnerPicked", async () => {
                          console.log("WinnerPicked event fired!");
                          try {
                              // add our asserts here
                              const recentWinner =
                                  await lottery.getRecentWinner();
                              const lotteryState =
                                  await lottery.getLotteryState();
                              const winnerEndingBalance =
                                  await accounts[0].getBalance();
                              const endingTimeStamp =
                                  await lottery.getLatestTimeStamp();

                              await expect(lottery.getPlayer(0)).to.be.reverted;
                              assert.equal(
                                  recentWinner.toString(),
                                  accounts[0].address
                              );
                              assert.equal(lotteryState, 0);
                              assert.equal(
                                  winnerEndingBalance.toString(),
                                  winnerStartingBalance
                                      .add(lotteryEntranceFee)
                                      .toString()
                              );
                              assert(endingTimeStamp > startingTimeStamp);
                              resolve();
                          } catch (error) {
                              console.log(error);
                              reject(e);
                          }
                      });
                      // Then entering the lottery
                      console.log("Entering Lottery...");
                      await lottery.enterLottery({ value: lotteryEntranceFee });
                      console.log("Ok, time to wait...");
                      const winnerStartingBalance =
                          await accounts[0].getBalance();

                      // and this code WONT complete until our listener has finished listening!
                  });
              });
          });
      });

The failing math code on the assert at Lottery.staging.test.js:49:38, as you can see is:
assert.equal(winnerEndingBalance.toString(), winnerStartingBalance.add(lotteryEntranceFee).toString());

I am thinking the assert is being called before the promise is being returned, but do not know EXACTLY what is wrong.
The code runs and is error free, but the math isn't working out.

Does someone have a clue, unlike me?

Chainlink Keepers Interface changed

Hello,
It looks like the interface for creating a Keeper interface has changed since you made the video. It doesn't ask for e-mail and has some other questions in there. I have tried to search online, but couldn't find a page describing the changes or how to Register a new keeper now

It start by not recognising the ABI of my contract and asks to manually input, but the biggest problem is that it now asks to select which function to be looked for and for an Input on the performUpkeep function, which I cannot leave in Blank. I tried putting 0x, but it also doesn't work and stay fixed on that page with no answer after clicking the button NEXT.

Can anybody help, please?

Thank you

Error in Raffle.test.js

1> Error: call revert exception; VM Exception while processing transaction: reverted with panic code 17
This error is for

it("returns false if enough time hasn't passed", async () => {
                  await raffle.enterRaffle({ value: raffleEntranceFee })
                  await network.provider.send("evm_increaseTime", [interval.toNumber() - 10]) // use a higher number here if this test fails
                  await network.provider.request({ method: "evm_mine", params: [] })
                  const { upkeepNeeded } = await raffle.callStatic.checkUpkeep([])
                  assert(!upkeepNeeded.toNumber())
              })

2> Timeout Error in "picks a winner, resets, and sends money"

it("picks a winner, resets, and sends money", async () => {
                  const additionalEntrances = 3 // to test
                  const startingIndex = 1
                  const accounts = await ethers.getSigners()
                  for (let i = startingIndex; i < startingIndex + additionalEntrances; i++) {
                      raffle = raffle.connect(accounts[i])
                      await raffle.enterRaffle({ value: raffleEntranceFee })
                  }

                  const startingTimeStamp = await raffle.getLastTimeStamp() // stores starting timestamp (before we fire our event)

                  // This will be more important for our staging tests...
                  await new Promise(async (resolve, reject) => {
                      raffle.once("WinnerPicked", async () => {
                          // event listener for WinnerPicked
                          log("WinnerPicked event fired!")
                          // assert throws an error if it fails, so we need to wrap
                          // it in a try/catch so that the promise returns event
                          // if it fails.

                          // Now lets get the ending values...
                          const recentWinner = await raffle.getRecentWinner()
                          log(recentWinner)
                          const raffleState = await raffle.getRaffleState()
                          const winnerBalance = await accounts[3].getBalance()
                          const endingTimeStamp = await raffle.getLastTimeStamp()
                          await expect(raffle.getPlayer(0)).to.be.reverted
                          // Comparisons to check if our ending values are correct:
                          assert.equal(recentWinner.toString(), accounts[3].address)
                          assert.equal(raffleState, 0)
                          assert.equal(
                              winnerBalance.toString(),
                              startingBalance // startingBalance + ( (raffleEntranceFee * additionalEntrances) + raffleEntranceFee )
                                  .add(
                                      raffleEntranceFee
                                          .mul(additionalEntrances)
                                          .add(raffleEntranceFee)
                                  )
                                  .toString()
                          )
                          assert(endingTimeStamp > startingTimeStamp)
                          resolve() // if try passes, resolves the promise
                      })

                      // kicking off the event by mocking the chainlink keepers and vrf coordinator
                      const tx = await raffle.performUpkeep("0x")
                      const txReceipt = await tx.wait(1)
                      const startingBalance = await accounts[3].getBalance()
                      await vrfCoordinatorV2Mock.fulfillRandomWords(
                          txReceipt.events[1].args.requestId,
                          raffle.address
                      )
                  })
              })

I think there is some problem in this part because while debugging my program was stopping here

await vrfCoordinatorV2Mock.fulfillRandomWords(
                          txReceipt.events[1].args.requestId,
                          raffle.address
                      )

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

Hi,

I am getting a error when I try to deploy, followed the code to the word and have searched and have not able to seem to solve it, rather than copying the repository I'd like to see if I can find solutions on my own.

Error: ERROR processing ***/hardhat-smartcontract-lottery/deploy/00-deploy-mocks.js: TypeError: Cannot read properties of undefined (reading 'length')

Original code from my deploy-mocks.js error states is at line 14, line 14 is at "await":

const { developmentChains } = require("../helper-hardhat-config")

const BASE_FEE = ethers.utils.parseEther("0.25") // 0.25 premier, 0.25 link per request
const GAS_PRICE_LINK = 1e9 //calc value, link per gas

module.exports = async function ({ getNamedAccounts, deployments }) {
const { deploy, log } = deployments
const { deployer } = await getNamedAccounts()
const args = [BASE_FEE, GAS_PRICE_LINK]

if (developmentChains.includes(network.name)) {
    log("Local network detected, Deploying Mocks")
    //deploy mock vrfcoordinator
    await deploy("VRFCoordinatorV2Mock", {
        from: deployer,
        logs: true,
        args: args,
    })
    log("Mocks deployed!")
    log("--------------------------------")
}

}

module.exports.tags = ["all", "mocks"]

Any help would be greatly appreciated thanks.

Lesson 8: HTML / Javascript Fund Me (Full Stack / Front End) - My unit test are not found

Hello

Hope I can get some help, I am following along the video here: https://youtu.be/gyMwXuJrbJQ?t=55624

When I run "hh test" in the terminal I just get:

  0 passing (1ms)

I tried all different things, and in the end found out it has to be in my code for Raffle.test.js
If I change to be the code from the repo LINK the test will run.

Here is my code:

const { assert, expect } = require("chai")
const { getNamedAccounts, deployments, ethers } = require("hardhat")
const { developmentChains, networkConfig } = require("../../helper-hardhat-config")

!developmentChains.includes(network.name)
    ? describe.skip
    : describe("Raffle Unit Test", async function () {
          let raffle, vrfCoordinatorV2Mock
          const chainId = network.config.chainId

          beforeEeach(async function () {
              const { deployer } = await getNamedAccounts()
              await deployments.fixture(["all"])
              raffle = await ethers.getContract("Raffle", deployer)
              vrfCoordinatorV2Mock = await ethers.getContract("VRFCoordninatorV2Mock", deployer)
          })

          describe("constructor", async function () {
              it("initializes the raffle correctly", async function () {
                  // Ideally we make our test have just 1 assert per "it"
                  const raffleState = await raffle.getRaffleState()
                  const interval = await raffle.getInterval()
                  assert.equal(raffleState.toString(), "0")
                  assert.equal(interval.toString(), networkConfig[chainId]["interval"])
              })
          })
          describe("enterRaffle", async function () {
              it("reverts when you don't pay enough", async function () {
                  await expect(raffle.enterRaffe()).to.be.revertedWith(
                      "Raffle__SendMoreToEnterRaffle"
                  )
              })
          })
      })

I was trying to look at the REPO and see the difference but it looks so different from the video.
Not sure what to do and what I have done wrong?

EDIT: Changed typo "descibe.skip" to be "decsribe.skip".

Unexpepected error when i tried to deploy.

Code 01-deploy-raffle.js:

const { getNamedAccounts, network, ethers } = require("hardhat")
const { developmentChains, networkConfig } = require("../helper-hardhat-config")
const { verify } = require("../helper-hardhat-config")

const VRF_SUB_FUND_AMOUNT = ethers.utils.parseEther("2")

module.exports = async function ({ getNamedAccount, deployments }) {
const { deploy, log } = deployments
const { deployer } = await getNamedAccounts()
const chainId = network.config.chainId
let vrfCoordinatorV2Address, subscriptionId, vrfCoordinatorV2Mock

if (chainId == 31337) {
    const vrfCoordinatorV2Mock = await ethers.getContract(
        "VRFCoordinatorV2Mock"
    )
    vrfCoordinatorV2Address = vrfCoordinatorV2Mock.address
    const transactionResponse =
        await vrfCoordinatorV2Mock.createSubscription()
    const transactionReceipt = await transactionResponse.wait(1)
    subscriptionId = transactionReceipt.events[0].args.subId
    await vrfCoordinatorV2Mock.fundSubscription(
        subscriptionId,
        VRF_SUB_FUND_AMOUNT
    )
} else {
    vrfCoordinatorV2Address = networkConfig[chainId]["vrfCoordinatorV2"]
    subscriptionId = networkConfig[chainId]["subscriptionId"]
}
const entranceFee = networkConfig[chainId]["entranceFee"]
const gasLane = networkConfig[chainId]["gasLane"]
const callbackGasLimit = networkConfig[chainId]["callbackGasLimit"]
const interval = networkConfig[chainId]["interval"]

const args = [
    vrfCoordinatorV2Address,
    entranceFee,
    gasLane,
    subscriptionId,
    callbackGasLimit,
    interval,
]
const raffle = await deploy("Raffle", {
    from: deployer,
    args: args,
    log: true,
    waitConfirmations: network.config.blockConfirmations || 1,
})

if (
    !developmentChain.includes(network.name) &&
    process.env.ETHERSCAN_API_KEY
) {
    log("Verifying...")
    await verify(raffle.address, args)
}
log("________________________")

}

module.exports.tags = ["all", "raffle"]

Error:
yarn run v1.22.15
warning package.json: No license field
$ /home/filip/hardhat-smartcontract-lottery/node_modules/.bin/hardhat deploy
Nothing to compile
Local network detected! Deploying mocks...
deploying "VRFCoordinatorV2Mock" (tx: 0x568782af0a079d0bc6f4e4e40b0e5953a1299aa5fd7a0eccc01ff0568a422e43)...: deployed at 0x5FbDB2315678afecb367f032d93F642f64180aa3 with 1803090 gas
Mocks Deployed!


deploying "Raffle" (tx: 0xf759543e44e0ced2da1f7eeaffcdcf790bff3abf197a49669f9d872422b0ccc0)...: deployed at 0xCf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9 with 1197444 gas
An unexpected error occurred:

Error: ERROR processing /home/filip/hardhat-smartcontract-lottery/deploy/01-deploy-raffle.js:
ReferenceError: developmentChain is not defined
at Object.module.exports [as func] (/home/filip/hardhat-smartcontract-lottery/deploy/01-deploy-raffle.js:50:5)
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)
at DeploymentsManager.executeDeployScripts (/home/filip/hardhat-smartcontract-lottery/node_modules/hardhat-deploy/src/DeploymentsManager.ts:1219:22)
at DeploymentsManager.runDeploy (/home/filip/hardhat-smartcontract-lottery/node_modules/hardhat-deploy/src/DeploymentsManager.ts:1052:5)
at SimpleTaskDefinition.action (/home/filip/hardhat-smartcontract-lottery/node_modules/hardhat-deploy/src/index.ts:438:5)
at Environment._runTaskDefinition (/home/filip/hardhat-smartcontract-lottery/node_modules/hardhat/src/internal/core/runtime-environment.ts:219:14)
at Environment.run (/home/filip/hardhat-smartcontract-lottery/node_modules/hardhat/src/internal/core/runtime-environment.ts:131:14)
at DeploymentsManager.executeDeployScripts (/home/filip/hardhat-smartcontract-lottery/node_modules/hardhat-deploy/src/DeploymentsManager.ts:1222:19)
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)
at DeploymentsManager.runDeploy (/home/filip/hardhat-smartcontract-lottery/node_modules/hardhat-deploy/src/DeploymentsManager.ts:1052:5)
at SimpleTaskDefinition.action (/home/filip/hardhat-smartcontract-lottery/node_modules/hardhat-deploy/src/index.ts:438:5)
at Environment._runTaskDefinition (/home/filip/hardhat-smartcontract-lottery/node_modules/hardhat/src/internal/core/runtime-environment.ts:219:14)
at Environment.run (/home/filip/hardhat-smartcontract-lottery/node_modules/hardhat/src/internal/core/runtime-environment.ts:131:14)
at SimpleTaskDefinition.action (/home/filip/hardhat-smartcontract-lottery/node_modules/hardhat-deploy/src/index.ts:584:32)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

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

I'v tried to solve this issue but I couldn't
What I tried to do is to fix "const { deployer } = getNamedAccounts();" this one,
Becuase when I test as console.log(deployer), it came out "undefined"
Maybe that's why TypeError: Cannot read properties of undefined (reading 'length')
If anybody know how to fix this issue, Please let me know

Thanks

 │  ~/Doc/hardhat-sc-lottery  hh deploy  1 ✘ │ 23:13:47 
Nothing to compile
Local network detected! Deploying mocks...
deploying "VRFCoordinatorV2Mock" (tx: 0x1319418ccc7f88788f4cc6c636585b9e49e87dafc1fca4cccb96f87be089ac55)...: deployed at 0x5FbDB2315678afecb367f032d93F642f64180aa3 with 1803306 gas
Mocks Deployed!

You are deploying to a local network, you'll need a local network running to interact
Please run yarn hardhat console --network localhost to interact with the deployed smart contracts!

An unexpected error occurred:

Error: ERROR processing /Users/glory/Documents/hardhat-sc-lottery/deploy/01-deploy-raffle.js:
TypeError: Cannot read properties of undefined (reading 'length')
at getFrom (/Users/glory/Documents/hardhat-sc-lottery/node_modules/hardhat-deploy/src/helpers.ts:1713:14)
at _deploy (/Users/glory/Documents/hardhat-sc-lottery/node_modules/hardhat-deploy/src/helpers.ts:533:9)
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)
at _deployOne (/Users/glory/Documents/hardhat-sc-lottery/node_modules/hardhat-deploy/src/helpers.ts:1004:16)
at Object.module.exports [as func] (/Users/glory/Documents/hardhat-sc-lottery/deploy/01-deploy-raffle.js:46:20)
at DeploymentsManager.executeDeployScripts (/Users/glory/Documents/hardhat-sc-lottery/node_modules/hardhat-deploy/src/DeploymentsManager.ts:1219:22)

------- 01-deploy-raffle.js -----------

const { network, getNamedAccounts, deployments, run, ethers } = require("hardhat")
const { developmentChains, networkConfig,
    VERIFICATION_BLOCK_CONFIRMATIONS }
    = require("../helper-hardhat-config")
const { verify } = require("../utils/verify")

const FUND_AMOUNT = ethers.utils.parseEther("2")

module.exports = async function({getNamedAccounts, deployments}) {
    const { deploy, log } = deployments
    const { deployer } = getNamedAccounts();
    console.log("deployer :1", deployer)        <<<<<<<<<<<<<<<<<<<<----- it turned out "undefined"
    console.log("deploy : 2", deploy)
    const chainId = network.config.chainId
    let vrfCoordinatorV2Address, subscriptionId

    if (chainId == 31337) {
        // create VRFV2 Subscription
        const vrfCoordinatorV2Mock = await ethers.getContract("VRFCoordinatorV2Mock")
        vrfCoordinatorV2Address = vrfCoordinatorV2Mock.address
        const transactionResponse = await vrfCoordinatorV2Mock.createSubscription()
        const transactionReceipt = await transactionResponse.wait()
        subscriptionId = transactionReceipt.events[0].args.subId
        // Fund the subscription
        // Usually, you'd need the link token on a real network
        // await vrfCoordinatorV2Mock.fundSubscription(subscriptionId, FUND_AMOUNT)
    } else {
        vrfCoordinatorV2Address = networkConfig[chainId]["vrfCoordinatorV2"]
        subscriptionId = networkConfig[chainId]["subscriptionId"]
    }

    const waitBlockConfirmations = (chainId == 31337)
        ? 1
        : VERIFICATION_BLOCK_CONFIRMATIONS

    log("----------------------------------------------------")

    const entranceFee = networkConfig[chainId]["entranceFee"]
    const gasLane = networkConfig[chainId]["gasLane"]
    const callbackGasLimit = networkConfig[chainId]["callbackGasLimit"]
    const interval = networkConfig[chainId]["interval"]
    const args = [vrfCoordinatorV2Address,
        entranceFee, gasLane, subscriptionId,
        callbackGasLimit, interval]

    const raffle = await deploy("Raffle", {
        from: deployer,
        args: args,
        log: true,
        waitConfirmations: waitBlockConfirmations
    })

    if(!developmentChains.includes(network.name) && process.env.ETHERSCAN_API_KEY) {
        log("Verifying...")
        await verify(raffle.address, args)
    }
    log("-----------------------------------")
}

module.exports.tags = ["all", "raffle"]

UNIT Test Error: No Contract deployed with name Raffle

This is the section of my unit testing... I've been working on this problem for the last few hours. I couldn't, however... I think the error is at

const { deployer } = await getNamedAccounts()

this line. Raffle contract isn't recognising... (Note- All the deployments are working correctly... )

!developmentChains.includes(network.name)
    ? describe.skip()
    : describe("Raffle UNIT test", async () => {
          let raffle, vrfCoordinatorV2Mock
          const chainId = network.config.chainId
          beforeEach(async () => {
              const { deployer } = await getNamedAccounts()
              await deployments.fixture(["all"])
              raffle = await ethers.getContract("Raffle", deployer)
              vrfCoordinatorV2Mock = await ethers.getContract("VRFCoordinatorV2Mock", deployer)
          })
          describe("Constructor function", async () => {
              it("Initializes the raffle correctly.", async () => {
                  const raffleState = await raffle.getRaffleState()
                  const interval = await raffle.getInterval()

                  assert.equal(raffleState.toString(), "0")
                  assert.equal(interval.toString(), networkConfig[chainId]["interval"])
              })
          })
      })

ERROR that I'm geting...

 ~/b/JSweb3_2/smart-contract_lottery  on main !2  hh test                                                      ✔  took 5s  system    at 07:27:25 am 


  Raffle UNIT test
    Constructor function
Development chain detected! Deploying mocks
Mocks deployed!!!...
---------------------!--!--!---------------------
      1) "before each" hook for "Initializes the raffle correctly."
  0 passing (428ms)
  1 failing

  1) Raffle UNIT test
       "before each" hook for "Initializes the raffle correctly.":
     Error: No Contract deployed with name Raffle
      at Object.getContract (node_modules/@nomiclabs/hardhat-ethers/src/internal/helpers.ts:447:11)
      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)
      at Context.<anonymous> (test/unit/Raffle.test.js:16:24)

hardhat test does not see my my deployed contracts.

Hello im at 15:26:00 of the tutorial. writing tests for my raffle.sol.
For some reason when i type in hh test, after the contracts are compiled it shows me a chart - thats empty and does not show my raffle.sol and vrfcoordinatorv2mock.sol. It also shows - 0 passing in the end.

Thats my Rffle.test.sol

const { getNamedAccounts, deployments, ethers, network } = require("hardhat")
const { developmentChains, networkConfig } = require("../helper-hardhat-config")
const { assert } = require("chai")

!developmentChains.includes(network.name)
    ? describe.skip
    : describe("Lottery Unit Tests", async function () {
          let raffle, VRFCoordinatorV2Mock
          const chainId = network.config.chainId

          beforeEach(async function () {
              const { deployer } = await getNamedAccounts()
              await deployments.fixture(["all"])
              raffle = await ethers.getContract("Raffle", deployer)
              VRFCoordinatorV2Mock = await ethers.getContract("VRFCoordinatorV2Mock", deployer)
          })

          describe("constructor", async function () {
              it("initializes the raffle correctly", async function () {
                  const raffleState = await raffle.getRaffleState()
                  const interval = await raffle.getInterval()
                  assert.equal(raffleState.toString(), "0")
                  assert.equal(interval.toString(), networkConfig[chainId]["interval"])
              })
          })
      })

Please help me so i can progress further :) thanks!
here is a link to my repo if someone wants to check it out for themselves!
https://github.com/olekmorawski/hardhat-smartcontract-lottery-fcc

Error: value out-of-bounds (argument="callbackGasLimit", value={"type":"BigNumber","hex":"0x2386f26fc10000"}, code=INVALID_ARGUMENT, version=abi/5.7.0)

Description

Hey guys, I can't solve this issue by myself, currently asking for your help.

I also tried to play with callbackGasLimit value using 3000000, 2500 and 50000, but got the same result.

I will be grateful for your advice!

Error output

Nothing to compile
Local network detected! Deploying mocks...
deploying "VRFCoordinatorV2Mock" (tx: 0x11b9dfa83e5a81e783d8d818bd6499fa1504a937113eca5f07b8cfafe70751ea)...: deployed at 0x5FbDB2315678afecb367f032d93F642f64180aa3 with 1797707 gas
Mocks Deployed!
------------------------------------------
You are deploying to a local network, you'll need a local network running to interact
Please run `yarn hardhat console --network localhost` to interact with the deployed smart contracts!
------------------------------------------
------------------------------------------
An unexpected error occurred:

Error: ERROR processing /home/hilaymanai-133676/Work/hh-fcc/hardhat-lottery-fcc/deploy/01-deploy-raffle.js:
Error: value out-of-bounds (argument="callbackGasLimit", value={"type":"BigNumber","hex":"0x2386f26fc10000"}, code=INVALID_ARGUMENT, version=abi/5.7.0)
    at Logger.makeError (/home/hilaymanai-133676/Work/hh-fcc/hardhat-lottery-fcc/node_modules/@ethersproject/logger/src.ts/index.ts:269:28)
    at Logger.throwError (/home/hilaymanai-133676/Work/hh-fcc/hardhat-lottery-fcc/node_modules/@ethersproject/logger/src.ts/index.ts:281:20)
    at Logger.throwArgumentError (/home/hilaymanai-133676/Work/hh-fcc/hardhat-lottery-fcc/node_modules/@ethersproject/logger/src.ts/index.ts:285:21)
    at NumberCoder.Coder._throwError (/home/hilaymanai-133676/Work/hh-fcc/hardhat-lottery-fcc/node_modules/@ethersproject/abi/src.ts/coders/abstract-coder.ts:68:16)
    at NumberCoder.encode (/home/hilaymanai-133676/Work/hh-fcc/hardhat-lottery-fcc/node_modules/@ethersproject/abi/src.ts/coders/number.ts:35:18)
    at /home/hilaymanai-133676/Work/hh-fcc/hardhat-lottery-fcc/node_modules/@ethersproject/abi/src.ts/coders/array.ts:71:19
    at Array.forEach (<anonymous>)
    at pack (/home/hilaymanai-133676/Work/hh-fcc/hardhat-lottery-fcc/node_modules/@ethersproject/abi/src.ts/coders/array.ts:54:12)
    at TupleCoder.encode (/home/hilaymanai-133676/Work/hh-fcc/hardhat-lottery-fcc/node_modules/@ethersproject/abi/src.ts/coders/tuple.ts:54:20)
    at AbiCoder.encode (/home/hilaymanai-133676/Work/hh-fcc/hardhat-lottery-fcc/node_modules/@ethersproject/abi/src.ts/abi-coder.ts:111:15)
    at DeploymentsManager.executeDeployScripts (/home/hilaymanai-133676/Work/hh-fcc/hardhat-lottery-fcc/node_modules/hardhat-deploy/src/DeploymentsManager.ts:1222:19)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at runNextTicks (node:internal/process/task_queues:64:3)
    at listOnTimeout (node:internal/timers:533:9)
    at processTimers (node:internal/timers:507:7)
    at DeploymentsManager.runDeploy (/home/hilaymanai-133676/Work/hh-fcc/hardhat-lottery-fcc/node_modules/hardhat-deploy/src/DeploymentsManager.ts:1052:5)
    at SimpleTaskDefinition.action (/home/hilaymanai-133676/Work/hh-fcc/hardhat-lottery-fcc/node_modules/hardhat-deploy/src/index.ts:438:5)
    at Environment._runTaskDefinition (/home/hilaymanai-133676/Work/hh-fcc/hardhat-lottery-fcc/node_modules/hardhat/src/internal/core/runtime-environment.ts:219:14)
    at Environment.run (/home/hilaymanai-133676/Work/hh-fcc/hardhat-lottery-fcc/node_modules/hardhat/src/internal/core/runtime-environment.ts:131:14)
    at SimpleTaskDefinition.action (/home/hilaymanai-133676/Work/hh-fcc/hardhat-lottery-fcc/node_modules/hardhat-deploy/src/index.ts:584:32)

01-deploy-raffle.js code

const { network, ethers } = require("hardhat")
const {
    networkConfig,
    developmentChains,
    VERIFICATION_BLOCK_CONFIRMATIONS,
} = require("../helper-hardhat-config")
const { verify } = require("../utils/verify")

const FUND_AMOUNT = ethers.utils.parseEther("1")

module.exports = async ({ getNamedAccounts, deployments }) => {
    const { deploy, log } = deployments
    const { deployer } = await getNamedAccounts()
    const chainId = network.config.chainId
    let vrfCoordinatorV2Address, subscriptionId, vrfCoordinatorV2Mock

    if (chainId == 31337) {
        // create VRFV2 Subscription
        vrfCoordinatorV2Mock = await ethers.getContract("VRFCoordinatorV2Mock")
        vrfCoordinatorV2Address = vrfCoordinatorV2Mock.address
        const transactionResponse = await vrfCoordinatorV2Mock.createSubscription()
        const transactionReceipt = await transactionResponse.wait()
        subscriptionId = transactionReceipt.events[0].args.subId
        // Fund the subscription
        // Our mock makes it so we don't actually have to worry about sending fund
        await vrfCoordinatorV2Mock.fundSubscription(subscriptionId, FUND_AMOUNT)
    } else {
        vrfCoordinatorV2Address = networkConfig[chainId]["vrfCoordinatorV2"]
        subscriptionId = networkConfig[chainId]["subscriptionId"]
    }
    const waitBlockConfirmations = developmentChains.includes(network.name)
        ? 1
        : VERIFICATION_BLOCK_CONFIRMATIONS

    log("----------------------------------------------------")
    const arguments = [
        vrfCoordinatorV2Address,
        subscriptionId,
        networkConfig[chainId]["gasLane"],
        networkConfig[chainId]["keepersUpdateInterval"],
        networkConfig[chainId]["raffleEntranceFee"],
        networkConfig[chainId]["callbackGasLimit"],
    ]
    const raffle = await deploy("Raffle", {
        from: deployer,
        args: arguments,
        log: true,
        waitConfirmations: waitBlockConfirmations,
    })

    // Verify the deployment
    if (!developmentChains.includes(network.name) && process.env.ETHERSCAN_API_KEY) {
        log("Verifying...")
        await verify(raffle.address, arguments)
    }

    log("Enter lottery with command:")
    const networkName = network.name == "hardhat" ? "localhost" : network.name
    log(`yarn hardhat run scripts/enterRaffle.js --network ${networkName}`)
    log("----------------------------------------------------")
}

module.exports.tags = ["all", "raffle"]

helper-hardhat-config.js code

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

const networkConfig = {
  default: {
    name: "hardhat",
    keepersUpdateInterval: "30",
  },
  5: {
    name: "goerli",
    subscriptionId: "6926",
    gasLane: "0x79d3d8832d904592c0bf9818b621522c988bb8b0c05cdc3b15aea1b6e8db0c15",
    keepersUpdateInterval: "30",
    raffleEntranceFee: ethers.utils.parseEther("0.01"),
    callbackGasLimit: "500000",
    vrfCoordinatorV2: "0x2Ca8E0C643bDe4C2E08ab1fA0da3401AdAD7734D",
},
  80001: {
    name: "mumbai",
    vrfCoordinatorV2: "0x7a1BaC17Ccc5b313516C5E16fb24f7659aA5ebed",
    raffleEntranceFee: ethers.utils.parseEther("0.01"),
    gasLane:
      "0x4b09e658ed251bcafeebbc69400383d49f344ace09b9576fe248bb02c003fe9f",
    subscriptionId: "1874",
    callbackGasLimit: "500000",
    keepersUpdateInterval: "30",
  },
  31337: {
    name: "localhost",
    raffleEntranceFee: ethers.utils.parseEther("0.01"),
    gasLane:
      "0xd89b2bf150e3b9e13446986e571fb9cab24b13cea0a43ea20a6049a85cc807cc",
    subscriptionId: "1874",
    callbackGasLimit: "500000",
    keepersUpdateInterval: "30",
  },
};

const developmentChains = ["hardhat", "localhost"];
const VERIFICATION_BLOCK_CONFIRMATIONS = 6

module.exports = {
    networkConfig,
    developmentChains,
    VERIFICATION_BLOCK_CONFIRMATIONS,
}

Chainlink keepers not running performUpkeep()

Greetings,
I have an issue with the keepers not running the performUpkeep function from the Raffle.sol contract.
To check that it wasn't the contract's fault, I have tried changing my raffle.sol and the deploy script with the code available in this repo, but it doesn't seem to fix the issue.

Here's a link to the contract

I have double-checked that:

  • upkeepNeeded returns True
  • performUpkeep can be called, and works fine, resulting in the winner being picked.
  • The upkeep is funded with 15 LINK
  • The subscriptionId is correct
  • The interval is 30 as per the tutorial

image

Here's my helper-hardhat-config.js :


const { ethers } = require("hardhat")

const networkConfig = {
    4: {
        name: "rinkeby",
        vrfCoordinatorV2: "0x6168499c0cFfCaCD319c818142124B7A15E857ab",
        raffleEntranceFee: ethers.utils.parseEther("0.01"),
        gasLane: "0xd89b2bf150e3b9e13446986e571fb9cab24b13cea0a43ea20a6049a85cc807cc",
        subscriptionId: "19157",
        callbackGasLimit: "500000", //500.000 gas
        keepersUpdateInterval: "30",
    },
    31337: {
        name: "hardhat",

        raffleEntranceFee: ethers.utils.parseEther("0.01"),
        gasLane: "0xd89b2bf150e3b9e13446986e571fb9cab24b13cea0a43ea20a6049a85cc807cc",
        callbackGasLimit: "500000", //500.000 gas
        keepersUpdateInterval: "30",
    },
}
const developmentChains = ["hardhat", "localhost"]

module.exports = {
    networkConfig,
    developmentChains,
}

I have read the chainlink keepers documentation and as far as I've understood the requirements for the keepers to work are:

  1. an upkeep subscription registered with custom logic, enough LINK tokens and connected to the contract where the checkUpkeep and the performUpkeep functions are. 👍
  2. contract inheriting keeperCompatibleInterface 👍
  3. checkUpkeep function being public view override with checkData as an argument(in this case empty), and returning BOOL and performData(in this case empty) 👍
  4. performUpkeep function being external override with performData as an argument(in this case empty) 👍

I don't get why the keepers aren't calling the contract, what am I missing here?
It most probably is something really dumb, thank you in advance for your patience!

DeclarationError: Identifier not found or not unique for msg.sender

My code is pretty much the same as Patrick's at this point in the video (timestamp). Except his code compiles and mine throws the error: "DeclarationError: Identifier not found or not unique" pointing to "event RaffleEnter(msg.sender);" with ^^^^ under msg.sender.

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.7;

import "@chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol";

error Raffle__NotEnoughETHEntered();

contract Raffle is VRFConsumerBaseV2 {
	/* State Variables */
	uint256 private immutable i_entranceFee;
	address payable[] private s_players;

	/*Events*/
	event RaffleEnter(msg.sender);

	constructor(address vrfCoordinatorV2, uint256 entranceFee) VRFConsumerBaseV2(vrfCoordinatorV2) {
		i_entranceFee = entranceFee;
	}

	function enterRaffle() public payable {
		if (msg.value < i_entranceFee) {
			revert Raffle__NotEnoughETHEntered();
		}
		s_players.push(payable(msg.sender));
		emit RaffleEnter(msg.sender);
	}

	function requestRandomWinner() external {}

	function fulfillRandomWords(uint256 requestId, uint256[] memory randomWords) internal override {

	}

	function getEntranceFee() public view returns (uint256) {
		return i_entranceFee;
	}

	function getPlayer(uint256 index) public view returns (address) {
		return s_players[index];
	}
}

Error: VM Exception while processing transaction

hey guys
i try to write the test for the raffle but at the "does not allow entrance when raffle is calculating" in the EnterRaffle descrie
get the following error :

Error: VM Exception while processing transaction: reverted with custom error 'InvalidConsumer()'
at VRFCoordinatorV2Mock.onlyValidConsumer (@chainlink/contracts/src/v0.8/mocks/VRFCoordinatorV2Mock.sol:72)
at VRFCoordinatorV2Mock.requestRandomWords (@chainlink/contracts/src/v0.8/mocks/VRFCoordinatorV2Mock.sol:147)
at Raffle.performUpkeep (contracts/Raffle.sol:142)

when i run the perforUpkeep() method i get this error i don't know how to fix it because i don't understand why InvalidConsumer() get reverted . i would appreciate it if anyone can help ?

Compilation error in checkUpKeep function

Hello, i'm facing this error and the solution dont compile
image

This is my hardhat config and the version of my contract is 0.8.7:

        require("@nomiclabs/hardhat-waffle");
        require("@nomiclabs/hardhat-etherscan");
        require("hardhat-deploy");
        require("solidity-coverage");
        require("hardhat-gas-reporter");
        require("hardhat-contract-sizer");
        require("dotenv").config();
        
        /** @type import('hardhat/config').HardhatUserConfig */
        module.exports = {
          solidity: "0.8.7",
        };

am i doing something wrong?
Thank you!

Error: No Contract deployed with name VRFCoordinatorV2Mock

I'm getting this error after 15:19:00
at command yarn hardhat compile

Nothing to compile
An unexpected error occurred:

Error: ERROR processing C:\Users\roush\newHardhatLottery\deploy\01-deploy-raffle.js:
Error: No Contract deployed with name VRFCoordinatorV2Mock
at Object.getContract (C:\Users\roush\newHardhatLottery\node_modules\

Prevent Upkeep to be called by anyone

Hello everyone and if you @PatrickAlphaC are reading me, I would like to thank you for the quality of your teaching, your lessons are valuable to me.

I wanted to ask how to deal with the performUpKeep interaction permissions, since Chainlink needs this contract function to be public, everyone can interact with it and anyone can send a transaction with it.
Let’s say the conditions to call the perfomUpKeep are always met, at least 1 player, etc…
So anyone malicious can just call this function as many times as they want, besides that, a winner will be picked up without any need of a chainlink keepUp, and worst is that this could lead to empty your funds from your consumer in Chainlink vrf as random number(s) will be generated every time performUpKeep is called.
Can we rely on chainlink contract address that is making the call to the function? Can we apply a modifier?

Appreciate your time and your help.
Brice

FullFillRandomWords stacks in Raffle.test.ts

Hi there! i am stuck a bit..
Actually my problem is that raffle.once('WinnerPicked' ) never called.

My main question is that i didnt get how should it works.

Because we invoke WinnerPicked inside Raffle contract, but fulfillRandomWords we invoke on vrfCoordinatorV2Mock contract (last row of code ex.) and vrfCoordinatorV2Mock event dont know about 'WinnerPicked' event (as per my understanding). So how come winnerPicket should be emmit here?

it works on video but doesnt works for me, i can not see console.log('pick winner') in console.

tried to debug it as well - instead of my custom WinenrPicker event - fullfillRandomWords emits "RandomWordsFulfilled" event which is stored in VrfCoordV2Mock contract

so this is my contract

contract Raffle {
    function fulfillRandomWords(uint256, uint256[] memory randomWords) internal override {
        uint256 indexOfWinner = randomWords[0] % s_players.length;

        address recentWinner = s_players[indexOfWinner];
        s_prevBlockTimestamp = block.timestamp;
        s_recentWinner = recentWinner;
        s_players = new address[](0);
        s_raffleState = RaffleState.OPEN;
        emit WinnerPicked(recentWinner);

        (bool success,) = recentWinner.call{ value: address(this).balance }("");

        if (!success) {
            revert Raffle__TransferFailed(); 
        }

        emit WinnerPicked(recentWinner);
    }
...
}

And here is tests

        beforeEach(async () => {
          await raffle.enterRaffle({ value: raffleEntranceFee });
          await network.provider.send('evm_increaseTime', [raffleInterval.toNumber() + 1]);
          await network.provider.send('evm_mine', []);
        })

        it('picks a winner, reest the lottery and sends money', async () => {
          const additionalEntrants = 3;
          const startingAccountIndex = 2;
          const accounts = await ethers.getSigners();

          for (let i = startingAccountIndex; i < startingAccountIndex + additionalEntrants; i++) {
            const connectedAccount = raffle.connect(accounts[i]);

            await connectedAccount.enterRaffle({ value: raffleEntranceFee });
          }

          const startingTimeStamp = await raffle.getLatestTimestamp();

          await new Promise<void>(async (resolve, reject) => {
            raffle.once('WinnerPicked', async () => {
              console.log('pick winner');
              try {

              } catch (e) {
                reject(e);
              }

              resolve();
            });

            const tx = await raffle.performUpkeep([]);
            const txReceipt = await tx.wait(1);
            const { requestId } = txReceipt.events![1].args!;

            await vrfCoordinatorV2Mock.fulfillRandomWords(requestId, raffle.address);
          });
        }) 
      })```

Unit & staging test error issue: For async tests and hooks, ensure "done()" is called;

when i run hardhat test ( I tried both hardhat network and rinkeby network)

yarn hardhat test --network hardhat --grep "picks a winner, resets, and sends money"

this error comes out =>

Error: Timeout of 50000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/Users/tujitongxue/Documents/TujiTech/solidity/lottery_hardhat/test/unit/Raffle.test.js)

the test code is (i just pasted from the repository)

it("picks a winner, resets, and sends money", async () => {
      const additionalEntrances = 3 // to test
      const startingIndex = 2
      for (let i = startingIndex; i < startingIndex + additionalEntrances; i++) {
          // i = 2; i < 5; i=i+1
          raffle = raffleContract.connect(accounts[i]) // Returns a new instance of the Raffle contract connected to player
          await raffle.enterRaffle({ value: raffleEntranceFee })
      }
      const startingTimeStamp = await raffle.getLastTimeStamp() // stores starting timestamp (before we fire our event)

      // This will be more important for our staging tests...
      await new Promise(async (resolve, reject) => {
          raffle.once("WinnerPicked", async () => {
              // event listener for WinnerPicked
              console.log("WinnerPicked event fired!")
              // assert throws an error if it fails, so we need to wrap
              // it in a try/catch so that the promise returns event
              // if it fails.
              try {
                  // Now lets get the ending values...
                  const recentWinner = await raffle.getRecentWinner()
                  const raffleState = await raffle.getRaffleState()
                  const winnerBalance = await accounts[2].getBalance()
                  const endingTimeStamp = await raffle.getLastTimeStamp()
                  await expect(raffle.getPlayer(0)).to.be.reverted
                  // Comparisons to check if our ending values are correct:
                  assert.equal(recentWinner.toString(), accounts[2].address)
                  assert.equal(raffleState, 0)
                  assert.equal(
                      winnerBalance.toString(),
                      startingBalance // startingBalance + ( (raffleEntranceFee * additionalEntrances) + raffleEntranceFee )
                          .add(
                              raffleEntranceFee
                                  .mul(additionalEntrances)
                                  .add(raffleEntranceFee)
                          )
                          .toString()
                  )
                  assert(endingTimeStamp > startingTimeStamp)
                  resolve() // if try passes, resolves the promise
              } catch (e) {
                  reject(e) // if try fails, rejects the promise
              }
          })

          const tx = await raffle.performUpkeep("0x")
          const txReceipt = await tx.wait(1)
          const startingBalance = await accounts[2].getBalance()
          await vrfCoordinatorV2Mock.fulfillRandomWords(
              txReceipt.events[1].args.requestId,
              raffle.address
          )
      })
  })

any idea for this ?

I have a serious problem:chainlink keeper not working

I have deployed the raffle contract, and set up chainlink keeper, chainlink vrf, but when I run raffle.staging.test.js, my address sends eth to the contract address, but checkupkeep doesn't work, what could be causing this error
image
image
image

getRaffleState() returning 0 or 1

gm all. Anyone experienced retrieving s_raffleState value from the front-end using the public view getRaffleState() ?

Strangely, I'm getting back 0 or 1. Any thoughts?

Can't verify contract on etherscan rinkeby

Error in plugin @nomiclabs/hardhat-etherscan: The contract verification failed.
Reason: Fail - Unable to verify

This is the message I am being showed and I am sure that I passed the same arguments for contract creation and verification
This is the deploy-raffle.js

    const { deploy, log } = deployments
    const { deployer } = await getNamedAccounts()
    const chainId = network.config.chainId
    let vrfCoordinator, subscriptionId
    if (developmentChains.includes(network.name)) {
        //await deployments.fixture(["VRFCoordinatorV2Mock"])
        const vrfAddress = await ethers.getContract("VRFCoordinatorV2Mock")
        vrfCoordinator = vrfAddress.address
        const transactionResponse = await vrfAddress.createSubscription()
        const transactionReceipt = await transactionResponse.wait(1)
        subscriptionId = transactionReceipt.events[0].args.subId
        await vrfAddress.fundSubscription(subscriptionId, VRF_SUB_FUND_AMOUNT)
    } else {
        vrfCoordinator = networkConfig[chainId]["vrfCoordinatorV2"]
        subscriptionId = networkConfig[chainId]["subscriptionId"]
    }
    const entranceFee = networkConfig[chainId]["entranceFee"]
    const gasLane = networkConfig[chainId]["gasLane"]
    const callbackGasLimit = networkConfig[chainId]["callbackGasLimit"]
    const interval = networkConfig[chainId]["interval"]
    const arguments = [
        vrfCoordinator,
        entranceFee,
        gasLane,
        subscriptionId,
        callbackGasLimit,
        interval,
    ]
    const raffle = await deploy("Raffle", {
        from: deployer,
        args: arguments,
        log: true,
        waitConfirmations: network.config.blockConfirmations || 1,
    })
     if (!developmentChains.includes(network.name) && process.env.ETHERSCAN_API_KEY) {
         log("Verifying...")
         await verify(raffle.address, arguments)
     }
    log("-------------------------------------------------------")
}

And this is the utils/verify.js

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

module.exports = {
    verify,
}

Keeper doesn't run performUpkeep

Hi! I've been writing staging tests for Raffle, but got stuck when I found out that keeper is not calling performUpkeep on my contract.

My Raffle address: 0x00B424EEF7090271304f7A5Fc62e33C3BF0D0249

I checked using hh console --network goerli if performUpkeep function executes correctly, and it does:

> await raffle.checkUpkeep([]);
[ true, '0x', upKeepNeeded: true ]
> const txRes = await raffle.performUpkeep([]);
undefined
> const txRec = await txRes.wait(1);
undefined
> txRec
{
  to: '0x00B424EEF7090271304f7A5Fc62e33C3BF0D0249',
  from: '0x7FCfA189672E7511106B6ff025d55250EEF3f9ef',
  contractAddress: null,
  transactionIndex: 32,
  gasUsed: BigNumber { _hex: '0x016414', _isBigNumber: true },
  logsBloom: '0x02000004000000000000000000000000001004000000000000800000020002020000000000000000000000000040000000000000000000000000000000000000000000000002000000000000000000000000000000000000400002000000000000000000000000000000000000000400000000000000000004000000080000000000000000100000200000000000000000000000000000000000400000000000000080800000000000000000000000000000000000000000000100000000800000000000000000000000000000000000000000000000000000000000000000000008000000000000000100000000000000000000000000000000000000000000',
  blockHash: '0xbb17a63ef53176ae310585867ca61e91c234ddc038a219091db57a4d27eea5ae',
  transactionHash: '0x0fb344a58d1ad7d5205e075481e889559909356cf8074efc8eced39de552f9fe',
  logs: [
    {
      transactionIndex: 32,
      blockNumber: 7446749,
      transactionHash: '0x0fb344a58d1ad7d5205e075481e889559909356cf8074efc8eced39de552f9fe',
      address: '0x2Ca8E0C643bDe4C2E08ab1fA0da3401AdAD7734D',
      topics: [Array],
      data: '0xfa6af316324298574a69285e8320750cde14389bb7257babdff99596d2dd015c9408413c282610df1e8066e7a620bc91866ed9abc81a3d9e2b71586f36af09c80000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000007a1200000000000000000000000000000000000000000000000000000000000000001',
      logIndex: 63,
      blockHash: '0xbb17a63ef53176ae310585867ca61e91c234ddc038a219091db57a4d27eea5ae'
    },
    {
      transactionIndex: 32,
      blockNumber: 7446749,
      transactionHash: '0x0fb344a58d1ad7d5205e075481e889559909356cf8074efc8eced39de552f9fe',
      address: '0x00B424EEF7090271304f7A5Fc62e33C3BF0D0249',
      topics: [Array],
      data: '0x',
      logIndex: 64,
      blockHash: '0xbb17a63ef53176ae310585867ca61e91c234ddc038a219091db57a4d27eea5ae'
    }
  ],
  blockNumber: 7446749,
  confirmations: 1,
  cumulativeGasUsed: BigNumber { _hex: '0x01853fd6', _isBigNumber: true },
  effectiveGasPrice: BigNumber { _hex: '0x3b9aca04', _isBigNumber: true },
  status: 1,
  type: 2,
  byzantium: true,
  events: [
    {
      transactionIndex: 32,
      blockNumber: 7446749,
      transactionHash: '0x0fb344a58d1ad7d5205e075481e889559909356cf8074efc8eced39de552f9fe',
      address: '0x2Ca8E0C643bDe4C2E08ab1fA0da3401AdAD7734D',
      topics: [Array],
      data: '0xfa6af316324298574a69285e8320750cde14389bb7257babdff99596d2dd015c9408413c282610df1e8066e7a620bc91866ed9abc81a3d9e2b71586f36af09c80000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000007a1200000000000000000000000000000000000000000000000000000000000000001',
      logIndex: 63,
      blockHash: '0xbb17a63ef53176ae310585867ca61e91c234ddc038a219091db57a4d27eea5ae',
      removeListener: [Function (anonymous)],
      getBlock: [Function (anonymous)],
      getTransaction: [Function (anonymous)],
      getTransactionReceipt: [Function (anonymous)]
    },
    {
      transactionIndex: 32,
      blockNumber: 7446749,
      transactionHash: '0x0fb344a58d1ad7d5205e075481e889559909356cf8074efc8eced39de552f9fe',
      address: '0x00B424EEF7090271304f7A5Fc62e33C3BF0D0249',
      topics: [Array],
      data: '0x',
      logIndex: 64,
      blockHash: '0xbb17a63ef53176ae310585867ca61e91c234ddc038a219091db57a4d27eea5ae',
      args: [Array],
      decode: [Function (anonymous)],
      event: 'RequestRaffleWinner',
      eventSignature: 'RequestRaffleWinner(uint256)',
      removeListener: [Function (anonymous)],
      getBlock: [Function (anonymous)],
      getTransaction: [Function (anonymous)],
      getTransactionReceipt: [Function (anonymous)]
    }
  ]
}

Than I checked if vrfCoordinator work, it's logs say that request took place, so contract seems not to be the problem.
Screenshot from 2022-08-21 21-05-52

I've decided to increase LINK balance of keeper up to 10, waited 5 minutes more but nothing happend (cron interval is * * * * *, meaning every minute), ran enterRaffle to add some balance to contract, but, unfortunately, it is not working.

So I'm confused with what causes the problem, maybe I have configured chainlink keeper wrong? (I haven't tested it on Rinkeby bacause it seems to be deprecated).

Thanks!

Question: checkUpkeep

If checkUpkeep is called everytime and decides on the basis of bool value to call the performUpkeep or not. Then in our raffle contract does it even make sense to call the checkUpkeep again inside performUpkeep ? will it save gas if we don't call it?

function checkUpkeep(bytes calldata /* checkData */) public  override returns(bool upkeepNeeded, bytes memory /* performData */){}

function performUpkeep(bytes calldata /* performData */) external override {
   (bool upkeepNeeded, ) = checkUpkeep("");
}

A possible attack on the "Raffle".

Contracts cannot accept ETH if they do not have receive or fallback functions. It follows from this that if a smart contract participates in the lottery and wins an error will occur, on the line:
(bool success, ) = recentWinner.call{value: address(this).balance}(""); ,
since it simply will not be able to accept ETH.

To avoid this situation, we can check the presence of a bytecode from a potential participant when he is just trying to enter the lottery, in the following way:
if (msg.sender.code.length > 0) revert Raffle__OnlyForEOA();

In theory, after an error occurs, Chainlink Keeper will call performUpkeep in the next block, since checkUpkeep will still return true. Therefore, it's not too scary, but we will lose our Link tokens, which are spent on VRF v2 and Chainlink Keeper.

PS: I understand that this is an educational course and at such an early stage it would be difficult to explain different types of attacks, but I decided it was worth mentioning)

Error HH606: The project cannot be compiled, see reasons below.

Hey guys can anyone help? each time I run "yarn hardhat test," I get the below response.. PS: I have tried changing my Raffle.sol to ^0.8.0, but I guess that's not the way to to around this.

The Solidity version pragma statement in these files doesn't match any of the configured compilers in your config. Change the pragma or configure additional compiler versions in your hardhat config.

  • contracts/Raffle.sol (^0.8.7)
  • @chainlink/contracts/src/v0.8/interfaces/KeeperCompatibleInterface.sol (^0.8.0)
  • @chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol (^0.8.0)
  • @chainlink/contracts/src/v0.8/mocks/VRFCoordinatorV2Mock.sol (^0.8.4)
  • @chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol (^0.8.4)
  • @chainlink/contracts/src/v0.8/interfaces/LinkTokenInterface.sol (^0.8.0)
  • contracts/test/VRFCoordinatorV2Mock.sol (^0.8.0)

To learn more, run the command again with --verbose
Read about compiler configuration at https://hardhat.org/config

(Question) Why checking `upkeepNeeded` again in `performUpkeep` function?

Hi Patrick @PatrickAlphaC and Team ,

First of all, love your tutorial series, easily the best free solidity course out there!

but i have a question about performUpkeep. since it called once checkUpkeep is returning true, Why we need to check upkeepNeeded again in the performUpkeep? what is the condition that could make upkeepNeeded = false when we call performUpkeep ?

    /**
     * @dev Once `checkUpkeep` is returning `true`, this function is called
     * and it kicks off a Chainlink VRF call to get a random winner.
     */
   function performUpkeep(
        bytes calldata /* performData */
    ) external override {
        (bool upkeepNeeded, ) = checkUpkeep("");
        if (!upkeepNeeded) {
            revert Lottery__UpkeepNotNeeded(
                address(this).balance,
                s_players.length,
                uint256(s_lotteryState)
            );
        }
        s_lotteryState = LotteryState.CALCULATING;
        uint256 requestId = i_vrfCoordinator.requestRandomWords(
            i_gasLane,
            i_subscriptionId,
            REQUEST_CONFIRMATIONS,
            i_callbackGasLimit,
            NUM_WORDS
        );
        // Quiz... is this redundant?
        emit RequestedLotteryWinner(requestId);
    } 

Thanks

Can't compile Raffle.sol because of value type incompatibility

Compiler error, using soldiity version 0.8.7

TypeError: Invalid type for argument in function call. Invalid implicit conversion from literal_string "" to bytes calldata requested.
  --> contracts/Lottery.sol:85:45:
   |
85 |         (bool upKeepNeeded, ) = checkUpkeep("");
   |                                             ^^


Error HH600: Compilation failed

Here are the two functions:

function checkUpkeep(
        bytes calldata /* checkData */
    )
        public
        view
        override
        returns (
            bool upkeepNeeded,
            bytes memory /* performData */
        )
    {
        bool isOpen = s_lotteryState == LotteryState.OPEN;
        bool timePassed = (block.timestamp - s_lastTimestamp) > s_interval;
        bool hasPlayers = s_players.length > 0;
        upkeepNeeded = (isOpen && timePassed && hasPlayers);
    }

    function performUpkeep(
        bytes calldata /* performData */
    ) external override {
        (bool upKeepNeeded, ) = checkUpkeep("");
        if (!upKeepNeeded) {
            revert Lottery__UpKeppNotNeeded(
                address(this).balance,
                s_players.length,
                uint256(s_lotteryState)
            );
        }
        s_lotteryState = LotteryState.CALCULATING_WINNER;
        uint256 requestId = i_vrfCoordinator.requestRandomWords(
            i_gasLane,
            i_subscriptionId,
            REQUEST_CONFIRMATIONS,
            i_callbackGasLimit,
            NUM_WORDS
        );
        emit RequestedRaffleWinner(requestId);
    }

Cannot read properties of undefined (reading 'toNumber')

it("updates the raffle state and emits a requestId", async () => { // Too many asserts in this test! await raffle.enterRaffle({ value: raffleEntranceFee }) await network.provider.send("evm_increaseTime", [interval + 1]) await network.provider.request({ method: "evm_mine", params: [] }) const txResponse = await raffle.performUpkeep([]) const txReceipt = await txResponse.wait(1) const raffleState = await raffle.getRaffleState() const requestId = txReceipt!.events![1].args!.requestId assert(requestId.toNumber() > 0) assert(raffleState == 1) })

When I run the test txReceipt!.events![1].args!.requestId becomes undefined. how to I check inside of the txReceipt in the test folder

Using the VRFCoordinatorV2Mock fulfillRandomWords "random" words

Maybe I missed that part, but I don't understand how the random number is being generated when it comes to testing the VRFCoordinatorV2Mock.

@PatrickAlphaC How did you know that Account 2 was always picked? In my code it seems to be always Account 3. Can you please elaborate how to calculate the winner? Thanks for your support.

Error: No Contract deployed with name VRFCoordinatorV2Mock

Hi Patrick,

Absolutely love your YouTube content. Been working through your latest course featuring this repo and it's been great. I'm stuck at hh deploy at around 15:20:00 and I cannot for the life of me figure it out. I've tried everything for the last 5 hours or so. Here's the error I keep getting:

Screen Shot 2022-06-17 at 11 24 41 PM

I'm stuck to be honest. I've tried everything, uninstalling with package.json, switching around versions. Keep getting this error. If I clone this repo everything compiles as in your lecture, however.

I'm about to give up and just continue with your repo, but it's a shame. Any ideas on what I'm missing here? Thanks sir.

Hardhat shorthand not working

image

I installed the hardhat shorthand as shown, it does installed but when I type "hh compile" in the terminal it says "command hh not found".
Did anyone else face this? Can someone help me fix this issue please!

Can't register upKeep

UI of https://keepers.chain.link/new have changed (it's different from UI shown in tutorial of FreeCodeCamp lesson 9) I can't figure out how to properly register upkeep with this new UI, It always got stuck in this unresponsive page
image_2022-07-14_00-01-05

Please help

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.