You can write a JavaScript script that controls geth's behavior related to mining.
There is a simple script that mines only nonempty blocks on go-ethereum wiki. Another one is mine.js script from Embark Framework. This one is feature-rich and configurable for periodic mining, mining reward cap, number of mining threads and more (via glider).
Scripts are loaded with js
command, for example:
geth --rpc js mining.js
Basically, you need to deploy the contract to your local hardhat net just as you would to any other. That means currently you have to set up a deploy.js
like in the official hardhat tutorial. I'm assuming you followed the official tutorial at least until Chapter 7: Deploying to a live network and e.g. @nomiclabs/hardhat-ethers
is already properly installed.
Preparations
❶ Run:
npx hardhat node
❷ Open a new console window at your project directory. Deploy your smart contract by using the previously mentioned deploy.js
. You need the --network
parameter to specify that you want to deploy to localhost.
npx hardhat run --network localhost scripts/deploy.js
The script will throw back some useful information. Keep an eye on the second address (designated by the contract's name) – you will need it in Step 4.
❸ Connect to the hardhat console at localhost with:
npx hardhat console --network localhost
❹ Get the ethers.js contract factory and attach to it.
Use the proper name in getContractFactory()
and paste the address from step 2 in attach()
const Token = await ethers.getContractFactory("Token")
const token = await Token.attach("0x5FbDB2315678afecb367f032d93F642f64180aa3")
Or in one command:
const token = await (await ethers.getContractFactory("Token")).attach("0x5FbDB2315678afecb367f032d93F642f64180aa3")
Interact with contract
You're in a JavaScript environment. E.g. call the transfer
method of the hardhat tutorial. For the complete API, see ethers.js API Docs
Two more tips:
- Use
await
to avoid Promise
objects.
.toString()
helps you to display uint256
numbers (which are too big for JS).
For a more detailed read, refer to the excellent OpenZeppelin tutorial for hardhat.
> await token.transfer("0xdd2fd4581271e230360230f9337d5c0430bf44c0", 42069)
{
hash: '0xdc0493ce8ed950b4d4558deb65605ba773067804eacfefd7fc64274a8a805dea',
...
> (await token.balanceOf("0xdd2fd4581271e230360230f9337d5c0430bf44c0")).toString()
'42069'
Best Answer
I ended up modifying the
block.number
by mining multiple blocks as it was suggested in the comment by Franco Victorio.This is the code:
Then it is called with:
It was a bit slow, but it worked quite well for what I needed it.