Transactions on Ethereum testnet using web3.js
Web3.js is an open source library of JavaScript built by the Ethereum foundation to allow end users to interact with an Ethereum node using HTTP, IPC, or WebSocket.
The web3.js library can be used to write transactions to the Ethereum network. The networks can be
Ethereum testnet
The Ethereum testnet uses nearly identical underlying technology as the Ethereum mainnet. It is primarily used by developers to test their decentralized applications in a live setting without the threat of losing any money as all the tesetnet Ether has no value.
There are multiple testnet networks, each differentiating from the other based on the consensus algorithm used. The most commonly used tesetnets are listed below:
Ropsten
Kovan
Rinkeby
Goerli
In this Answer, we'll learn about the Ropsten network.
Example
Let's consider an example where we perform a transaction and transfer one Ether from one account to another in the Ropsten network. We can simply send a token from one address to another using the MetaMask wallet, but in this example, we will try to build the transaction, sign it, and then broadcast it using web3.js.
To perform the transaction, follow the steps given below:
Create a MetaMask account and create two accounts in it to transfer the tokens.
Switch to the Ropsten Test Network from Ethereum Mainnet.
Add some Ether to your account using a faucet. Now the accounts should look like this.
Now copy the addresses of these accounts and paste them into the code. The addresses are written under the account name which in this case are “Account1” and “Account2”.
Fetch the private key of “Account1” by clicking the three dots next to the account name and clicking on “Account Details” and then enter the password of your MetaMask account. Then copy and paste the private key into the code.
Execute the code. A transaction hash will be generated, copy that and go to
ropsten.etherescan.ioand paste this hash into the search bar. You will be able to see a page like this with "Success" written in front of "Status." You can check “from” and “to” addresses to verify that these are the same addresses you pasted into the code.
Now go back to MetaMask to see the updated balance. One Ether went from “Account1” to “Account2”.
Note: The balance of "Account1" is less than nine because of the deduction of the gas fee.
Code
The code to perform the transaction is written below. However, to perform the transaction, some fields are required, which are given below:
rpcURL: We need a network node to connect to the Ropsten network. However, to avoid this complex task, we can use Infura’s free API key to connect to the testnet.
Addresses: The accounts’ addresses (public keys) can be copied from MetaMask, as explained above.
privateKey: The private key of the sender account can also be copied from MetaMask, as explained above.
Note: The following code is not executable because the Ether in the account is limited and will drain after some transactions.
var Tx = require('ethereumjs-tx')const Web3 = require('web3')rpcURL = 'https://ropsten.infura.io/v3/YOUR_API_KEY'const web3 = new Web3(rpcURL)const account1 = 'Address of Account1' // Senderconst account2 = 'Address of Account2' // Reciever// Private key needs to be converted to Hexadecimalconst privateKey1 = Buffer.from('ACCOUNT_ONE_PRIVATE_KEY', 'hex')async function GetNonce(){// Transaction count is required to build the transactionreturn await web3.eth.getTransactionCount(account1)}async function SendTransaction(){var Nonce = await GetNonce()// Building the transactionconst txObject = {nonce: web3.utils.toHex(Nonce),to: account2,value: web3.utils.toHex(web3.utils.toWei('1', 'ether')),gasLimit: web3.utils.toHex(21000),gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei'))}// Sign the transactionconst tx = new Tx(txObject)tx.sign(privateKey1)const serializedTx = tx.serialize()const raw = '0x' + serializedTx.toString('hex')//Broadcast the transactionweb3.eth.sendSignedTransaction(raw, (err, txHash) => {console.log('txHash:', txHash)})}SendTransaction()
Explanation
Line 24:
txObjectcontains the transaction object with the fields required to perform the transaction. The values of these fields must be in hexadecimal. That is whytoHex()is used.Line 36:
seralize()converts the transaction object into an RLP encoding of the transaction. The encoding ensures that the data can be sent in bytes from one application to another, irrespective of their language.Line 39:
sendSignedTransaction()broadcasts the serialized transaction object to perform the transaction. The transaction hashtxHashis returned, which is printed in the call-back function.
Free Resources