Fetching the current network gas fee is a critical task for developers working with blockchain transactions, particularly on the Ethereum network. This guide demonstrates how to integrate gas fee fetching into your Node.js project using Alchemy and Web3.js, building upon our existing cryptocurrency transaction API
Prerequisites
Before you begin, ensure you have Node.js installed and have cloned the repository from GitHub. If not, follow these steps:
git clone https://github.com/rick001/crypto-transaction-api-nodejs.git
cd crypto-transaction-api-nodejs
npm install
Add your Ethereum provider URL in a .env
file:
ALCHEMY_MAINNET_URL=https://eth-mainnet.alchemyapi.io/v2/YOUR_ALCHEMY_PROJECT_ID
ALCHEMY_SEPOLIA_URL=https://eth-sepolia.alchemyapi.io/v2/YOUR_ALCHEMY_PROJECT_ID
NETWORK=mainnet
Fetching the Gas Fee
To fetch the current network gas fee, create a file named fetchGasFee.js
in your project directory:
const { Web3 } = require('web3');
require('dotenv').config();
const ALCHEMY_MAINNET_URL = process.env.ALCHEMY_MAINNET_URL;
const ALCHEMY_SEPOLIA_URL = process.env.ALCHEMY_SEPOLIA_URL;
const NETWORK = process.env.NETWORK;
const alchemyUrl = NETWORK === 'testnet' ? ALCHEMY_SEPOLIA_URL : ALCHEMY_MAINNET_URL;
const web3 = new Web3(new Web3.providers.HttpProvider(alchemyUrl));
async function getEthereumGas() {
try {
const gasPriceWei = await web3.eth.getGasPrice();
const gasPriceEth = web3.utils.fromWei(gasPriceWei, 'ether');
return gasPriceEth;
} catch (error) {
console.error('Error fetching Ethereum gas fee:', error);
throw new Error('Failed to fetch Ethereum gas fee');
}
}
module.exports = { getEthereumGas };
Integrating with the API
To integrate gas fee fetching into your API, update server.js
:
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const swaggerJsDoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');
const { getBitcoinGas } = require('./bitcoinGas.js');
const { getDogecoinGas } = require('./dogecoinGas.js');
const { getEthereumGas } = require('./ethereumGas.js');
const { getSolanaGas } = require('./solanaGas.js');
const { getXrpGas } = require('./xrpGas.js');
const app = express();
const port = 3000;
const NETWORK = process.env.NETWORK;
app.use(bodyParser.json());
// Swagger configuration
const swaggerOptions = {
swaggerDefinition: {
openapi: '3.0.0',
info: {
title: 'Crypto Details API',
version: '1.0.0',
description: 'API to fetch details of various cryptocurrencies',
contact: {
name: 'Sayantan Roy'
},
servers: [{ url: `http://localhost:${port}` }]
},
},
apis: [__filename],
};
const swaggerDocs = swaggerJsDoc(swaggerOptions);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs));
/**
* @swagger
* /fetchGasFee:
* post:
* summary: Fetch the gas fee for a given chain
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* chain:
* type: string
* example: "ethereum"
* responses:
* 200:
* description: Successful response
* content:
* application/json:
* schema:
* type: object
* properties:
* gasFee:
* type: string
* example: "100 Gwei"
* 400:
* description: Bad request
* 500:
* description: Internal server error
*/
app.post('/fetchGasFee', async (req, res) => {
const { chain } = req.body;
if (!chain) {
return res.status(400).json({ error: 'Chain is required' });
}
try {
const gasFee = await getGasFee(chain);
res.json({ gasFee });
} catch (error) {
console.error('Error:', error.message);
res.status(500).json({ error: error.message });
}
});
async function getGasFee(chain) {
switch (chain.toLowerCase()) {
case 'bitcoin':
return getBitcoinGas();
case 'dogecoin':
return getDogecoinGas();
case 'ethereum':
return getEthereumGas();
case 'solana':
return getSolanaGas();
case 'xrp':
return getXrpGas();
default:
throw new Error('Unsupported chain');
}
}
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Running the Server
Start your server:
node server.js
You can fetch the gas fee for a specific chain by sending a POST request to http://localhost:3000/fetchGasFee
with a JSON body containing the desired chain. For example:
{
"chain": "ethereum"
}
By following these steps, you can seamlessly integrate gas fee fetching into your existing cryptocurrency transaction API. This enhancement provides real-time gas fee information, improving the usability and efficiency of your application.
For more details, visit our previous blog on creating a cryptocurrency transaction API and check out the complete source code on GitHub.
Discover more from Techbreeze IT Solutions
Subscribe to get the latest posts sent to your email.