Transactions on Ganache 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 localIt is a personal blockchain that is also mainly used for testing purposes., testnetIt is an instance of blockchain powered by the same underlying code as the actual blockchain network. It is mainly used for testing purposes., and mainnetIt is the actual network of the blockchain..

Ganache

Ganache is a local Ethereum network used to develop decentralized apps (Dapps) rapidly. It is used to deploy smart contracts and test them without cost before deployment on the main net.

As mentioned above, Ganache contains accounts with some Ether tokens for testing purposes. Transactions can be performed between these accounts on the network without any cost.

Example

Let's consider an example where we perform a transaction and transfer one Ether from one account to another in the Ganache local network.

Before we go to the code, we need some information given below:

  • RPC-URL: Remote procedure call (RPC) is used to execute procedures on the server. The server, in this case, is a node on the local network. To connect to it, we need the URL, which we can get from the ganache desktop app under the name “RPC SERVER”.

  • Account addresses: We need the addresses (public keys) of two accounts to perform a transaction.

The highlighted section shows the RPC SERVER URL and the account addresses

Example

The following code shows a transaction being performed between two accounts on the local network:

const Web3 = require('web3')
const web3 = new Web3('http://127.0.0.1:7545')
const account1 = '0xd6Ae00D3c11DD27237D62C9b9e9428C40B6099Ac'
const account2 = '0x9E32980d09ACD7af76C1448A0585B5D0bB0c70D7'
web3.eth.sendTransaction({
from: account1,
to: account2,
value: web3.utils.toWei('1','ether')
})

Explanation

  • Line 2: web3 is connected to the local network.

  • Line 7–11: sendTransaction() transfers one Ether from account1 to account2. Value only takes wei so we convert Ether to wei.

Note: Wei is the smallest subunit of Ether. Consider an Ether to be a dollar and wei a penny. 100 pennies are equal to a dollar; however, in this case, 1,000,000,000,000,000,000 wei is equal to one Ether.

Output

The output of the above code results in the movement of one Ether from one account to another as shown in the image below:

The highlighted section shows the balance of both accounts after the transaction

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved