Tip: Mining only when there are transactions

Project Source Code

Get the project source code below, and follow along with the lesson material.

Download Project Source Code

To set up the project on your local machine, please follow the directions provided in the README.md file. If you run into any issues with running the project source code, then feel free to reach out to the author in the course's Discord channel.

This lesson preview is part of the Million Ether Homepage course and can be unlocked immediately with a \newline Pro subscription or a single-time purchase. Already have access to this course? Log in here.

This video is available to students only
Unlock This Course

Get unlimited access to Million Ether Homepage, plus 70+ \newline books, guides and courses with the \newline Pro subscription.

Thumbnail for the \newline course Million Ether Homepage

In this video, I want to give you a quick tip on how to only mind blocks when there are transactions. More generally, this will show you how to load utility scripts into your Geth console. Here's the problem. When we're developing smart contracts, every time we want to make a change, we have to issue a transaction, and that transaction has to be picked up by a miner. Eventually, we'll deploy contracts to live test networks or to the production network, but for testing, we just run a local node. Ethereum miners, by default, mind blocks very quickly, regardless of whether there are transactions or not. The mining process can be CPU intensive. The problem for me is that I'm generally developing on my personal laptop, and I don't have a lot of extra CPU to spare. Fortunately, we can use the script, which can be found on the Ethereum wiki, which will start and stop our miners automatically, depending on if they're transactions to be mined. Let's copy and paste this code into a file. Now, you could just copy and paste this directly into your Geth console. That would work. But Geth also has a load script helper function that we can use to load this and any other helper functions we might want. So here I'll type load script, and then the path to our script. If you get the path wrong, this will return false. If you have the correct path, you should see no transactions mining stopped, and it will return true. Now let's try this out. Let's send Ether from one account to another. We'll type eth.sendTransaction, and specify a from account, a to account, and a value. Great, it works! Our miner automatically starts and stops saving our precious CPU. One thing to note is that this script added in listening hooks, and it didn't save a handle to turn them off. If for some reason you don't want this behavior, the easiest way to get rid of it is just restart Geth.