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?

Russo
  • 1,784
  • 1
  • 21
  • 30

3 Answers3

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.

Franco Victorio
  • 2,862
  • 17
  • 27
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
Julissa DC
  • 1,888
  • 1
  • 8
  • 21
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

Casareafer
  • 648
  • 2
  • 12