Sign an Ethereum transaction off-line

N F
Coinmonks
4 min readMar 30, 2018

--

In this post we will look at how to sign an Ethereum transaction off line using ethereumjs-tx and Node.js. Repo available here.

Set up your local instance

Clone the repo to your local machine:

Install it:

$ npm install

You are also going to need Ganache.

Sending Ether

Let’s see how this works. First start your local Ganache instance:

First couple blocks in Ganache.

After starting Ganache you should see blocks starting to populate. I set my block time to 3 seconds but you can set it to whatever you like.

Next up let’s start the node menu, cd into your project folder and:

Node.js menu.

Great! Let’s try to send a transaction now. Press 1 to send Ether from one Ganache account to another:

Send Ether receipt.

If you get this screen it means that the transaction was successfully sent! You are seeing the receipt of your transaction which includes block hash, transaction hash, gas used, etc.

You can also inspect your transaction in Ganache:

Ganache showing tx.

Click on the transaction for more details:

Ganache tx details.

Cool, let’s look at the code.

Sign Transaction Off-line

The heavy lifting is done by ethereumjs-tx which allows you to easily create raw transactions, sign them, and serialize them. Let’s go over the logic.

First we need web3 to connect to the local Ganache instance:

We can now import our web3 instance anywhere we need to use it.

Next let’s look at how the transaction is prepared and sent:

There are three imports:

  • Ganache connected instance of web3
  • accounts from our accounts file
  • transaction builder file to pass our transaction data

Our function then gets all the required values for our transaction: estimate gas, gas price, transaction count, etc. The amount to send is set to 20 eth but you could easily set it to be dynamically accepted by the menu if you like. We then build a transaction data structure and pass it to our transaction builder:

There are three imports:

  • Ganache connected instance of web3
  • Tx instance from ethereumjs-tx
  • dotenv for our private key

We grab our private key via:

then we get set our values to hex using the web3 util:

Now we can build a raw transaction object:

You can add more cases for any transaction you like to perform.

Finally, we can sign our transaction and return it for sending:

Great, now we can simply send it via the web3 method:

And that’s it! As you can see ethereumjs-tx is an awesome little module.

Thank you very much for reading this post! If you found this post useful please clap on this article and make sure to follow me for more regular content, also check out my Github as I regularly post sample code and projects. If you have any questions feel free to reply below this post or shoot me an email.

Get Best Software Deals Directly In Your Inbox

Happy coding!

--

--