PatrickAlphaC / hardhat-fund-me-fcc

82 stars 182 forks source link

"before each" hook for "sets the aggregator addresses correctly": TypeError: (0 , ethers_1.getAddress) is not a function #180

Closed kartik01112004 closed 5 months ago

kartik01112004 commented 8 months ago

I am getting TypeError: (0 , ethers_1.getAddress) is not a function when i run yarn hardhat test on the first part of unit testing

here is FundMe.tets.js

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

describe("FundMe", async function () {
    let fundMe
    let deployer
    let mockV3Aggregator
    beforeEach(async function () {
        //depoying all contracts using fixture

        deployer = (await getNamedAccounts()).deployer
        await deployments.fixture(["all"])
        fundMe = await ethers.getContractAt("FundMe", deployer)
        mockV3Aggregator = await ethers.getContractAt(
            "MockV3Aggregator",
            deployer,
        )
    })
    describe("constructor", function () {
        it("sets the aggregator addresses correctly", async () => {
            const response = await fundMe.getPriceFeed()
            assert.equal(response, mockV3Aggregator.target)
        })
    })
})

here is 01-deploy-fund-me.js

// function deployFunc() {
//     console.log("hello")
// }

const { network } = require("hardhat")
const { verify } = require("../utils/verify")
// module.exports.default = deployFunc

// module.exports = async (hre) => {
//     const { getNamedAccounts, deployments } = hre
//same thing!

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

//adding pricefeeds as per the network we are on

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

    // const ethUsdPriceFeedAddress =
    //     networkConfig(chainId)["ethUsdPriceFeedAddress"]
    let ethUsdPriceFeedAddress
    if (developmentChains.includes(network.name)) {
        const ethUsdAggregator = await deployments.get("MockV3Aggregator")
        ethUsdPriceFeedAddress = ethUsdAggregator.address
    } else {
        ethUsdPriceFeedAddress =
            networkConfig[chainId]["ethUsdPriceFeedAddress"]
    }
    const args = [ethUsdPriceFeedAddress]
    const fundMe = await deploy("FundMe", {
        from: deployer,
        args: args,
        log: true,
        waitConfermations: network.config.blockConfirmations || 1,
    })
    if (
        !developmentChains.includes(network.name) &&
        process.env.ETHERSCAN_API_KEY
    ) {
        await verify(fundMe.address, args)
    }

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

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

here is FundM.sol

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

import "./PriceConverter.sol";

//we wanna widhraw funds
//we wanna get funds
//say a minimun funding value in USD

// constant, immutable === using them saves gas
//after using constant 944,608 gas, before using constant 966,825 gas

//error codes
error FundMe__NotOwner();

// interfaces, libraries, contracts

/** @title A contract for crowd funding
 * @author Kartik Goel
 * @notice it is to demo a sample funding contract
 * @dev implimets pricefeeds as our library
 */
contract FundMe {
    //type declarations
    using PriceConverter for uint256;

    address[] public funders;
    mapping(address => uint256) public addressToAmountFunded;
    uint256 public constant MINIMUM_USD = 50 * 1e18;

    address public immutable i_owner;
    AggregatorV3Interface public priceFeed;

    modifier onlyOwner() {
        //require(msg.sender==i_owner,"sender is not owner");
        if (msg.sender != i_owner) {
            revert FundMe__NotOwner();
        }
        _; //do rest of the code present in the function that uses it
    }

    constructor(address priceFeedAddress) {
        i_owner = msg.sender;
        priceFeed = AggregatorV3Interface(priceFeedAddress);
    }

    receive() external payable {
        fund();
    }

    fallback() external payable {
        fund();
    }

    /// @notice Funds our contract based on the ETH/USD price
    function fund() public payable {
        //we wanna be able to set a minimum fund amount in USD
        //after this lesson try to make in rupees
        //1. how do we send ETH to this contract?
        require(
            msg.value.getConversionRate(priceFeed) >= MINIMUM_USD,
            "didnt send enough"
        ); // 1e18 == 1* 10**18 wei or 1 ETH
        //18 decimals
        funders.push(msg.sender);
        addressToAmountFunded[msg.sender] += msg.value;
        //what is reverting?
        //Undo any action before,and send remaining gas back
    }

    function withdraw() public onlyOwner {
        //require( msg.sender==owner,"sender is ot owner"); //this makes the withraw function only accessible to the owner but there is a better way
        for (
            uint256 funderIndex = 0;
            funderIndex < funders.length;
            funderIndex = funderIndex + 1
        ) {
            address funder = funders[funderIndex];
            addressToAmountFunded[funder] = 0;
        }
        funders = new address[](0); //resets the array

        // actually withraw the funds

        //transfer
        //msg.sender= address type
        //payable(msg.sender) = paybale address type. Transfer only works with payable address
        //payable(msg.sender).transfer(address(this).balance);

        //send
        //bool sendSuccess= payable (msg.sender).send(address(this).balance);
        //require(sendSuccess, "send failed");

        //call
        (bool callSuccess, ) = payable(msg.sender).call{
            value: address(this).balance
        }("");
        require(callSuccess, "call failed");
    }
}

here is packge.json

{
    "name": "hardhat-fund-me",
    "version": "1.0.0",
    "license": "MIT",
    "devDependencies": {
        "@chainlink/contracts": "^0.3.1",
        "@nomicfoundation/hardhat-chai-matchers": "^2.0.0",
        "@nomicfoundation/hardhat-ethers": "^3.0.0",
        "@nomicfoundation/hardhat-network-helpers": "^1.0.0",
        "@nomicfoundation/hardhat-toolbox": "^3.0.0",
        "@nomicfoundation/hardhat-verify": "^1.0.0",
        "@nomiclabs/hardhat-ethers": "^2.2.3",
        "@nomiclabs/hardhat-waffle": "^2.0.6",
        "@typechain/ethers-v6": "^0.4.0",
        "@typechain/hardhat": "^8.0.0",
        "@types/mocha": ">=9.1.0",
        "@types/sinon-chai": "^3.2.3",
        "chai": "^4.3.4",
        "dotenv": "^16.3.1",
        "ethereum-waffle": "^3.4.0",
        "ethers": "^5.7.2",
        "hardhat": "^2.17.4",
        "hardhat-deploy": "^0.11.37",
        "hardhat-gas-reporter": "^1.0.9",
        "prettier": "^3.0.2",
        "prettier-plugin-solidity": "^1.1.3",
        "solidity-coverage": "^0.8.5",
        "ts-node": ">=8.0.0",
        "typechain": "^8.1.0",
        "typescript": ">=4.5.0",
        "solhint": "^3.6.2"
    }
}

here is hardhat.config.js

require("@nomicfoundation/hardhat-toolbox")
require("hardhat-deploy")
require("hardhat-gas-reporter")
require("dotenv").config()
require("solidity-coverage")

/** @type import('hardhat/config').HardhatUserConfig */
const COINMARKETCAP_API_KEY = process.env.COINMARKETCAP_API_KEY || ""
const SEPOLIA_RPC_URL =
    process.env.SEPOLIA_RPC_URL ||
    "https://eth-sepolia.g.alchemy.com/v2/3FoXafsGZG26BuLiWnplFRIkKv71Chf2"
const PRIVATE_KEY =
    process.env.PRIVATE_KEY ||
    "0x11ee3108a03081fe260ecdc106554d09d9d1209bcafd46942b10e02943effc4a"
const ETHERSCAN_API_KEY = process.env.ETHERSCAN_API_KEY || ""

module.exports = {
    defaultNetwork: "hardhat",
    networks: {
        hardhat: {
            chainId: 31337,
            // gasPrice: 130000000000,
        },
        sepolia: {
            url: SEPOLIA_RPC_URL,
            accounts: [PRIVATE_KEY],
            chainId: 11155111,
            blockConfirmations: 6, // teling how many block we wanna wait
        },
    },
    solidity: {
        compilers: [
            {
                version: "0.8.7",
            },
            {
                version: "0.6.6",
            },
        ],
    },
    etherscan: {
        apiKey: ETHERSCAN_API_KEY,
        // customChains: [], // uncomment this line if you are getting a TypeError: customChains is not iterable
    },
    gasReporter: {
        enabled: true,
        currency: "USD",
        outputFile: "gas-report.txt",
        noColors: true,
        coinmarketcap: COINMARKETCAP_API_KEY,
    },
    namedAccounts: {
        deployer: {
            default: 0, // here this will by default take the first account as deployer
            1: 0, // similarly on mainnet it will take the first account as deployer.
            //Note though that depending on how hardhat network are configured, the account 0 on one network can be different than on another
        },
    },
}

the error comes when i write the 1st it block... i have tried my best to resolve this error by using repo and by using stackexchange and stackoverflow ..

can anyone assist me??

esciiee commented 6 months ago

for hardhat version above 2.15.0 install these dependencies and it must work fine then

yarn add --dev hardhat @nomiclabs/hardhat-ethers@npm:hardhat-deploy-ethers ethers

kartik01112004 commented 6 months ago

for hardhat version above 2.15.0 install these dependencies and it must work fine then

yarn add --dev hardhat @nomiclabs/hardhat-ethers@npm:hardhat-deploy-ethers ethers

TypeError: fundMe.getPriceFeed is not a function error continuous to exists

TARishabh commented 5 months ago

I think, firstly you are using, getContractAt() function rather than getContract, the difference could be: getContract: (name: string, signer?: ethers.Signer | string) => Promise;

getContract takes two arguments name of the contract and the signer, whereas the getContractAt function takes: getContractAt: ( nameOrAbi: string | any[], address: string | ethers.Addressable, signer?: ethers.Signer ) => Promise;

address also, and address is generated after we deploy the contract, secondly, i also tried this: yarn add --dev hardhat @nomiclabs/hardhat-ethers@npm:hardhat-deploy-ethers ethers

but this doesn't worked for me too.

kartik01112004 commented 5 months ago

When I use getContract I get error as it's not a function....

kartik01112004 commented 5 months ago

New error AssertionError: expected '0x5FbDB2315678afecb367f032d93F642f641…' to equal undefined

tqdj commented 5 months ago

When I use getContract I get error as it's not a function.... Me too

kartik01112004 commented 5 months ago

So in order to complete this section of course i have just downgraded all of the dependencies to of the patric's in the course .. i dont think its a god way to go forward but i couldnt seem to arrange all dependencies in a way that they all work and the code work as intended and not give random errors with no relation what so ever ...