13

How to get last block information in a Hardhat Waffle test?

I checked here https://hardhat.org/hardhat-network/#json-rpc-methods-support

And here https://hardhat.org/hardhat-network/reference/

it seems eth_blockNumber is what I need, but how can I use it to get the last block timestamp?

3 Answers 3

18

If you are using @nomiclabs/hardhat-ethers (and you are if you have @nomiclabs/hardhat-waffle installed and imported in your config), then:

const latestBlock = await hre.ethers.provider.getBlock("latest")

Notice that ethers.provider is something added by the @nomiclabs/hardhat-ethers plugin, it's not part of ethers itself. It's a provider that is connected to the network that Hardhat is using.

1
  • 1
    Franco, thank you so much. I think "hre." is not needed :)
    – Russo
    Oct 4, 2021 at 8:24
5

To answer:

how can I use it to get the last block timestamp?

And adding to the previous answer to get the timestamp just read the property from the returned block information:

const timeStamp = (await ethers.provider.getBlock("latest")).timestamp
1

If you're using Hardhat and doing tests, you can get the timestamp of a block where a specific transaction was included

 it('should succeed - verify the timestamp when a token was minted', function () {
   const accounts = await ethers.getSigners()

   //mint something ~ the contract stores the block.timestamp during the mint

   expect(yourTx = await yourContract.connect(accounts[1]).mintNFT(
                randomParameters,
                moreRandomParameters,
                {value: yourMintPrice})).to.be.ok

   //Print timestamp from the specific block where a TX was included

   const foo = await ethers.provider.getBlock(yourTx.blockHash!)
   console.log(`timestamp of the tx ${foo.timestamp}`)

   //this function returns the token details stored in the contract

   const mintedToken = await yourContract.getTokenDetails(mintedTokenId)
   console.log(`tokenstoredTimestamp ${mintedToken.timestamp}`)


   expect(mintedToken.timestamp).to.be.equal(foo.timestamp)

        });

The previous answers are correct, this is just a different approach to get a bit more control if you are running parallel tests and your functions are time sensitive

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.