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:
$ npm run start
Great! Let’s try to send a transaction now. Press 1 to send Ether from one Ganache account to another:
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:
Click on the transaction for more 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:
import Web3 from 'web3';var web3 = new Web3(new Web3.providers.HttpProvider('http://127.0.0.1:7545'));export default web3;
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:
var privateKey = new Buffer(process.env["PRIVATE_KEY"], "hex");
then we get set our values to hex using the web3 util:
const nonceHex = web3.utils.toHex(nonce);
const valueHex = web3.utils.toHex(value);
const limitHex = web3.utils.toHex(gasLimit);
const priceHex = web3.utils.toHex(gasPrice);
Now we can build a raw transaction object:
switch (method) {
case 'sendEther':
rawTx = {
nonce: nonceHex,
gasPrice: priceHex,
gasLimit: limitHex,
to: toAddress,
value: valueHex
};
break;
}
You can add more cases for any transaction you like to perform.
Finally, we can sign our transaction and return it for sending:
var tx = new Tx(rawTx);
tx.sign(privateKey);
var serializedTx = tx.serialize();return serializedTx;
Great, now we can simply send it via the web3 method:
await web3.eth.sendSignedTransaction('0x' + rawTx.toString('hex'));
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.
Happy coding!