Ethereum – Using Ethereumjs-tx and Web3

September 13, 2018

Author: Michael Gord

Tutorial - MLG Blockchain

Ethereum – Using Ethereumjs-tx and Web3

You must have node and npm downloaded on your computer. After this tutorial you should have sent an ethereum transaction with test-ether on testrpc.

npm install web3 ethereumjs-tx ethereumjs-utilDownload web3, ethereumjs-tx and ethereumjs-util from your terminal.

nodeGo to your node console.

var Web3 = require("web3")Require web3.

var web3 = new Web3(new Web3.providers.httpsProvider("https://localhost:8545"))Get web3 Instance in Node Console. 8545 is the default port to connect to.

testrpcIn a new terminal window run testrpc.

web3.eth.getBalance(web3.eth.accounts[0])Check balance of account[0] in Wei.

web3.fromWei(web3.eth.getBalance(web3.eth.accounts[0]), 'ether')Check balance of account[0] in Ether.

acct1 = web3.eth.accounts[0]
acct2 = web3.eth.accounts[1]
acct3 = web3.eth.accounts[2]
Create account helper methods.

var balance = (acct) => { return web3.fromWei(web3.eth.getBalance(acct), 'ether').toNumber()}Create balance method.

balance(acct1)Query balance of account[0] to make sure its working.

web3.eth.sendTransaction({from: acct1, to:acct2, value: web3.toWei(1, 'ether'), gasLimit: 21000, gasPrice: 20000000000})Send 1 test ether from acct1 to acct2.

var txHash = _Create variable for txHash output from above.

balance(acct2) balance(acct1)Query balance of acct1 and acct1 to make sure the transaction went through.

web3.eth.getTransaction(txHash)Check transaction data from txHash.

MLG Blockchain is a blockchain development and consulting firm based in Toronto that is focused on building next generation applications using blockchain and smart contract technology. View all our blockchain development tutorials at www.mlgblockchain.com/learn.html.

MLG Blockchain