Solidity get contract balance showing different value than during HartHat

Viewed 1592

I'm running into an issue where my Solidity contract balance isn't matching my Chai test contract balance. Running my contract on a local instance of HardHat

using solidity ^0.8.0

My contract gets the current contract balance with:

uint balance = address(this).balance;

0

My Chai test gets the contract balance with:

const contractBalance = await provider.getBalance(contractAddress);

BigNumber { value: "42278041630000000001" }

I verified the contract addresses are the same with my trust console

Chai Test --
contractAddress: 0x5FbDB2315678afecb367f032d93F642f64180bb3
contractBalance: BigNumber { value: "42278041630000000001" }

Contract Execution --
contractAddress 0x5fbdb2315678afecb367f032d93f642f64180bb3
contractBalance 0

What could I be missing to cause these balances to be not identical? There's no additional test logic being ran before this

-- here's the full contract code contracts/Contract.sol

pragma solidity ^0.8.0;

import "hardhat/console.sol";

contract Contract {

  function getBalance() public view returns (uint) {

    uint balance = address(this).balance;

    console.log("\nContract Execution -- ");
    console.log("contractAddress", address(this));
    console.log("contractBalance", balance);

    return balance;
  }
}

-- full test file code test/index.js

const { expect } = require("chai");

describe("Contract", function () {
  let contract;
  let provider;
  let contractAddress;

  beforeEach(async function () {
    const _Contract = await ethers.getContractFactory("Contract");
    const _contract = await _Contract.deploy();
    await _contract.deployed();
    contract = _contract;
    contractAddress = contract.address;
    provider = await ethers.getDefaultProvider();
  });

  it("should have a consistent account balance", async function () {
    const contractBalance = await provider.getBalance(contractAddress);

    console.log("\nChai Test -- ");
    console.log("contractAddress:", contractAddress);
    console.log("contractBalance:", contractBalance);

    expect(await contract.getBalance()).to.equal(contractBalance);
  });
});

-- full hardhat.config.js

require("@nomiclabs/hardhat-waffle");

/**
 * @type import('hardhat/config').HardhatUserConfig
 */
module.exports = {
  solidity: "0.8.0",
};

-- and to help you get running if you want to test yourself package.json devDependencies

"devDependencies": {
  "@nomiclabs/hardhat-ethers": "^2.0.4",
  "@nomiclabs/hardhat-waffle": "^2.0.1",
  "bignumber.js": "^9.0.2",
  "chai": "^4.3.4",
  "chai-bignumber": "^3.0.0",
  "ethereum-waffle": "^3.4.0",
  "ethers": "^5.5.3",
  "hardhat": "^2.8.2"
},

so just organize the files as such and npx hardhat, copy devDependencies, npm i, npx hardhat test

1 Answers
Related