Skip to content
Home » Answers » How does web3.eth.gasPrice() work?

How does web3.eth.gasPrice() work?

A poster saying how does web3 eth_gasprice work?

web3.eth_gasPrice() is a function provided by the web3.js library, which is a JavaScript library that allows you to interact with the Ethereum blockchain using a web3 provider (such as an Ethereum node).

Different aspects of the process

1. Determination of gas price

Gas price is determined by the Ethereum network and is based on supply and demand. When there are more transactions than available block space, the gas price goes up. When there is more block space than transactions, the gas price goes down. Gas price is set by the Ethereum miners and they can choose to mine transactions with higher gas prices first because they will be more profitable.

2. Gas limit

Each transaction on the Ethereum network requires a certain amount of gas. Gas is used to pay for the computational resources used to process a transaction or execute a smart contract. The web3.eth.gasPrice() function returns the price of one unit of gas in wei. The total cost of a transaction is the gas price multiplied by the gas limit.

3. Wei unit

web3.eth.gasPrice() returns the current gas price in wei, which is the smallest unit of ether. It is important to note that the gas price is returned in wei because the gas limit is also expressed in wei. The gas price is set by the Ethereum network and is used to determine how much Ether a user needs to spend in order to execute a given transaction on the Ethereum blockchain. The higher the gas price, the more priority a transaction is given by miners when it is included in a block.

4. Nonce

Nonce is a number that is unique per account. It is incremented with every transaction from an account. web3.eth.gasPrice() does not take into account the nonce, it only returns the current gas price.

5. Network dependent

The gas price returned by web3.eth.gasPrice() is dependent on the network you are connected to via the web3 provider. If you are connected to the Ethereum mainnet, you will get the gas price for the mainnet. If you are connected to a testnet, you will get the gas price for that testnet.

It is worth noting that the returned promise from web3.eth.getGasPrice() will resolve to a string representing the gas price in wei. If you need to convert it to Gwei (another unit of gas) or ether, you can use the web3.utils.fromWei() function.

How you can use web3.eth.gasPrice()

This is an example in JavaScript:

const Web3 = require('web3');
const web3 = new Web3(new Web3.providers.HttpProvider("https://mainnet.infura.io/v3/YOUR-PROJECT-ID"));

web3.eth.getGasPrice().then(console.log);

In the example above, we first import the web3.js library and create a new instance of the web3 object, which is configured to connect to the Ethereum mainnet using an Infura node.

Then we call the web3.eth.getGasPrice() function, which returns a promise that resolves to the current gas price in wei. Finally, we log the gas price to the console.

In this example, The HttpProvider is connecting to the Ethereum node via HTTP and therefore can access the JSON-RPC API of the node.

Please keep in mind, this is a simple and general example and the actual implementation can be more complex and might differ according to use case.

Use of web3.eth.gasPrice() in a more complete use case

Let’s say you have a simple smart contract that allows users to transfer ether to other users. You want to create a front-end application that lets users interact with this contract using JavaScript.

Here’s some example code that demonstrates how you might use web3.eth.gasPrice() when calling the transfer() function of the contract.

const Web3 = require('web3');
const web3 = new Web3(new Web3.providers.HttpProvider("https://mainnet.infura.io/v3/YOUR-PROJECT-ID"));

const contractAddress = "0x..."; // address of the deployed smart contract
const contractAbi = [/* ABI of the contract */];
const contract = new web3.eth.Contract(contractAbi, contractAddress);

const fromAddress = "0x..."; // address of the sender
const privateKey = "0x..."; // private key of the sender
const toAddress = "0x..."; // address of the recipient
const amount = "1"; // amount of ether to send

// Get the current gas price in wei
web3.eth.getGasPrice().then(gasPrice => {
    // Estimate the gas needed for the transfer transaction
    contract.methods.transfer(toAddress, web3.utils.toWei(amount, 'ether')).estimateGas({from: fromAddress}).then(estimatedGas => {
        // Build the raw transaction
        const rawTransaction = {
            "from": fromAddress,
            "to": contractAddress,
            "value": "0x0",
            "gasPrice": web3.utils.toHex(gasPrice),
            "gas": web3.utils.toHex(estimatedGas),
            "data": contract.methods.transfer(toAddress, web3.utils.toWei(amount, 'ether')).encodeABI()
        };

        // Sign and send the transaction
        web3.eth.accounts.signTransaction(rawTransaction, privateKey).then(signedTransaction => {
            web3.eth.sendSignedTransaction(signedTransaction.rawTransaction).then(console.log);
        });
    });
});

Step 1.

In this example, we first create a new instance of the web3 object and connect it to the Ethereum mainnet using an Infura node. Then we create a new instance of the contract object using the ABI and address of the deployed contract.

Step 2.

After that, we define the addresses, private key and the amount of ether to be transferred.

Step 3.

Then we call web3.eth.getGasPrice() to get the current gas price in wei. We pass the gas price, the address to be transferred to, the amount of ether and the address of the sender, to the contract.methods.transfer(toAddress, web3.utils.toWei(amount, 'ether')).estimateGas({from: fromAddress}) to estimate the gas required for the transaction.

Step 4.

After that we can now build the rawTransaction object, where we put all the details required by Ethereum to execute the transaction.

Step 5.

Finally, we can sign the transaction using the private key of the sender and send it using web3.eth.sendSignedTransaction(signedTransaction.rawTransaction) which returns the transaction receipt and logs it to the console.

We have covered the basic flow of using web3.eth_gasPrice() in a more complete use case. But here are some further notes.

⚡️ Additional notes that might be useful to you

Keep in mind that the above example is simplified and doesn’t include any error handling or input validation. In a real-world application, you should always handle errors and validate user inputs to ensure that the transactions are executed as expected.

Also, keep in mind that this example is for sending transactions on the Ethereum mainnet which incurs real cost, and testnet should be used for testing.

The returned promise from web3.eth.getGasPrice() will resolve to a string representing the gas price in wei. If you need to convert it to Gwei (another unit of gas) or ether, you can use the web3.utils.fromWei() function.

The estimateGas() method returns the estimated gas cost of the given transaction in the form of a promise, which can be useful to make sure that you set the gas limit for the transaction correctly, otherwise the transaction will fail.

web3.eth.accounts.signTransaction(rawTransaction, privateKey) method will sign the transaction using the private key and returns a promise that will resolve to a SignedTransaction object that you can use to send the transaction via web3.eth.sendSignedTransaction(signedTransaction.rawTransaction).

The web3.eth.sendSignedTransaction() method returns a promise that will resolve to the transaction receipt object which contains the details of the executed transaction.