Learn to create a blockchain explorer utilizing JavaScript (NodeJS and NextJS) in simply over one hour by following alongside on this article. The explorer shall be an Etherscan clone that may fetch parsed on-chain information utilizing the Moralis Web3 Information API. As we progress, you’ll see how simple it’s to work with this API to cowl our blockchain explorer’s blockchain-related backend points. Now, earlier than we transfer into the tutorial part, let’s take a look at the endpoints we’ll use:
- The Token API’s
getTokenPrice
endpoint to get the ERC-20 token worth:
const response = await Moralis.EvmApi.token.getTokenPrice({ tackle: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", chain: "0x1", });
- The Block API’s
getDateToBlock
andgetBlock
endpoints to get the block by date and hash:
const latestBlock = await Moralis.EvmApi.block.getDateToBlock({ date: Date.now(), chain: "0x1", });
const previousBlockNrs = await Moralis.EvmApi.block.getBlock({ chain: "0x1", blockNumberOrHash: blockNrOrParentHash, });
- The Transaction API’s
getWalletTransactionsVerbose
endpoint to get decoded transactions by pockets:
const response = await Moralis.EvmApi.transaction.getWalletTransactionsVerbose({ tackle: question.tackle, chain, });
Odds are you have already got some expertise with frontend growth, so we determined to give attention to the backend points of a blockchain explorer. That mentioned, we’ll be sure to learn to implement the above code snippets accurately. So far as the frontend goes, you may depend on the video on the prime because it explores that half in additional element.
So, in the event you want to create a blockchain explorer following our lead, make certain to enroll with Moralis now! You can begin with a free plan, because it provides you entry to all Moralis Web3 API endpoints. Nevertheless, in the event you anticipate your dapps to obtain a bigger quantity of customers, the Moralis Professional plan is the go-to selection.
Overview
Blockchain explorers, also referred to as “block explorers”, allow devs and different blockchain customers to discover on-chain information. We’ve beforehand touched on this matter as we created a easy information displaying how you can simply construct a block explorer. That article can also be an ideal place to be taught what blockchain explorers are and their advantages. Nevertheless, this text is extra of a whole, detailed information on how you can create an Etherscan-grade blockchain explorer.
All through the next sections, we’ll give attention to displaying you how you can create a blockchain explorer backend with NodeJS and Moralis. We’ll additionally do a fast demo, serving to you resolve whether or not or not you need to construct the frontend half and create your individual occasion of our Etherscan clone. Beneath the backend tutorial and our demo, it’s also possible to discover the reply to the “what’s a blockchain explorer?” query.
Tutorial: Create a Blockchain Explorer Backend with NodeJS and Moralis
The above screenshot reveals our Etherscan dapp operating on “localhost: 3000”. It marks among the on-chain information that the backend must fetch. Other than the present Ethereum worth, the newest blocks, and the newest transactions, our block explorer additionally permits customers to seek for transactions by the pockets tackle. Additionally, our backend queries all of the associated on-chain information with the endpoints offered within the intro. Nevertheless, earlier than we present you how you can implement these snippets of code to create a blockchain explorer backend, let’s be sure to set issues up accurately.
Backend Setup
Begin by creating a brand new undertaking listing. You possibly can observe our lead and title it “etherscan-moralis-clone”. In actual fact, you need to use your terminal and enter the next command to do precisely that:
mkdir etherscan-moralis-clone
Then, that you must cd
into that listing to create a “backend” folder with this command:
mkdir backend
Subsequent, cd
into the “backend” folder and initialize a brand new NodeJS app:
npm init -y
Lastly, set up all of the required dependencies with the next command:
npm i cors moralis categorical dotenv
Transferring on, open your undertaking in Visible Studio Code (VSC). First, give attention to the “bundle.json” script and add begin
below scripts
like so:
"scripts": { "begin": "node index.js", "check": "echo "Error: no check specified" && exit 1"
With the above line of code added to your script, reserve it and create a brand new “.env” file:
Contained in the “.env” file, create an environmental variable and name it MORALIS_API_KEY
. As for this variable’s worth, that you must acquire your Web3 API key and use that worth. That is the place that you must use your Moralis account. As soon as signed in, go to the “Web3 APIs” web page of your admin space and replica your API key:
Lastly, return to the “.env” file and paste the above-copied key subsequent to the MORALIS_API_KEY
variable.
Coding Your Blockchain Explorer’s Backend Script
Inside your “backend” folder, create a brand new “index.js” file and first import the above-installed dependencies and decide an area port on your backend:
const categorical = require("categorical"); const app = categorical(); const port = 5001; const Moralis = require("moralis").default; const cors = require("cors"); require("dotenv").config({ path: ".env" });
Subsequent, you additionally must instruct your app to make use of CORS and Categorical:
app.use(cors()); app.use(categorical.json());
Earlier than you truly begin implementing the Moralis Web3 Information API endpoints, make certain to additionally outline a brand new variable that shops your API key on this script:
const MORALIS_API_KEY = course of.env.MORALIS_API_KEY;
Add the Moralis.begin
operate to initialize Moralis utilizing your API key. This must also be the cue to begin listening to your backend port:
Moralis.begin({ apiKey: MORALIS_API_KEY, }).then(() => { app.pay attention(port, () => { console.log(`Listening for API Calls`); }); });
With the above traces of code in place, you might be prepared to begin implementing the endpoints from the intro.
Fetch ETH Value
The primary endpoint we’ll implement is without doubt one of the Moralis Token API endpoints: getTokenPrice
. This endpoint fetches the token worth denominated within the blockchain’s native token and USD. In our case, we’ll use this endpoint to fetch the worth of ETH, which is Ethereum’s native coin, in USD. We have to go two parameters: the token’s contract tackle and the chain ID. So, listed here are the traces of code querying the worth of ETH:
app.get("/getethprice", async (req, res) => { attempt { const response = await Moralis.EvmApi.token.getTokenPrice({ tackle: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", chain: "0x1", }); return res.standing(200).json(response); } catch (e) { console.log(`One thing went unsuitable ${e}`); return res.standing(400).json(); } });
Wanting on the traces of code above, you may see that we additionally catch potential errors and reply to them with “One thing went unsuitable”.
Fetch Block Particulars
The above endpoint will allow our dapp to show the ETH worth; nevertheless, we additionally need it to show the newest block and the newest transactions. For that objective, we’ll use the next two Moralis endpoints: getDateToBlock
and getBlock
. The previous takes within the unix date in milliseconds and returns the closest block to that date. As such, it offers us with the newest block and a few of its particulars, together with its date, block quantity, timestamp, hash, and guardian hash. Then, we are able to use that block’s block quantity or hash as a parameter for the getBlock
endpoint. In return, the latter offers us with the main points of that block, together with the on-chain transactions. Right here’s how we make the most of the 2 endpoints in a brand new /getblockinfo
endpoint:
app.get("/getblockinfo", async (req, res) => { attempt { const latestBlock = await Moralis.EvmApi.block.getDateToBlock({ date: Date.now(), chain: "0x1", }); let blockNrOrParentHash = latestBlock.toJSON().block; let previousBlockInfo = []; for (let i = 0; i < 5; i++) { const previousBlockNrs = await Moralis.EvmApi.block.getBlock({ chain: "0x1", blockNumberOrHash: blockNrOrParentHash, }); blockNrOrParentHash = previousBlockNrs.toJSON().parent_hash; if (i == 0) { previousBlockInfo.push({ transactions: previousBlockNrs.toJSON().transactions.map((i) => { return { transactionHash: i.hash, time: i.block_timestamp, fromAddress: i.from_address, toAddress: i.to_address, worth: i.worth, }; }), }); } previousBlockInfo.push({ blockNumber: previousBlockNrs.toJSON().quantity, totalTransactions: previousBlockNrs.toJSON().transaction_count, gasUsed: previousBlockNrs.toJSON().gas_used, miner: previousBlockNrs.toJSON().miner, time: previousBlockNrs.toJSON().timestamp, }); } const response = { latestBlock: latestBlock.toJSON().block, previousBlockInfo, }; return res.standing(200).json(response); } catch (e) { console.log(`One thing went unsuitable ${e}`); return res.standing(400).json(); } });
Wanting on the above traces of code, you may see that you simply get to create a blockchain explorer that shows particulars for the newest block and the earlier 4 blocks. That is what the above for
loop is chargeable for. The latter ensures that our script makes use of the Moralis.EvmApi.block.getBlock
technique on the final 5 blocks. Additionally, utilizing the guardian hash (t.i., earlier block hash), our code can acquire blocks’ particulars (transactionHash
, time
, fromAddress
, toAddress
, and worth
). Lastly, it pushes these particulars to the previousBlockInfo
array. Nonetheless, we additionally test for potential errors.
Fetch Decoded Transaction Particulars
We additionally need to create a blockchain explorer backend that’s able to acquiring transaction particulars for any pockets tackle. Luckily, Moralis gives a strong endpoint that may acquire these particulars and decode them on our behalf. That is the place the getWalletTransactionsVerbose
endpoint enters the scene.
Since we’re focusing our blockchain explorer on the Ethereum chain, our chain parameter should once more match Ethereum (0x1
). The second required parameter is a pockets tackle. On this case, we don’t need to use a set tackle. As an alternative, we wish the endpoint to make use of the tackle customers enter within the search area on the consumer facet. Plus, similar to with the earlier two app.get
capabilities, we additionally need to catch any potential errors. As such, these are the traces of code that acquire decoded transactions particulars:
app.get("/tackle", async (req, res) => { attempt { const { question } = req; const chain = "0x1"; const response = await Moralis.EvmApi.transaction.getWalletTransactionsVerbose({ tackle: question.tackle, chain, }); return res.standing(200).json(response); } catch (e) { console.log(`One thing went unsuitable ${e}`); return res.standing(400).json(); } });
Be aware: For those who want to be taught extra about or check the Moralis Web3 API endpoints, make certain to go to the API reference pages (as indicated in screenshots above every of the final three subsections). Yow will discover the pages available in the market’s industry-leading Web3 documentation.
The above-outlined endpoints deal with all of the blockchain-related backend points of our Etherscan clone. As such, all that’s left to do is to create a correct frontend that neatly makes use of the above-built backend. For that objective, you get to create a NextJS app and a number of other JavaScript parts. For those who want to observe our lead and create a blockchain explorer frontend as properly, make certain to make use of the video a the highest of the article, beginning at 20:49. That will help you resolve if our frontend is worthy of your time, make certain to take a look at a demo under.
Our Etherscan Clone Blockchain Explorer Demo
The next screenshot reveals all the main points of our blockchain explorer dapp:
All the underlined particulars within the above screenshots are fetched by the highly effective endpoints from Moralis. These embody the ETH worth, newest transactions, block variety of the final finalized block, particulars of the final 5 blocks, and particulars of the newest transactions. In fact, there may be additionally a search field, which is the core of our blockchain explorer. That is the place customers can paste any pockets tackle to discover all its transactions:
Our frontend shows all of the transactions and their particulars in a neat desk that follows Etherscan’s appears to be like:
For those who want to take our instance blockchain explorer dapp for a spin however don’t want to code it from scratch, merely clone the code that awaits you on our “etherscan-clone” GitHub repo web page. Other than all of the frontend scripts, that is additionally the place you’ll find the whole “index.js” backend script lined above.
Be aware: In case you’re questioning what “Moralis Beans” are, make certain to take a look at the main specialised blockchain explorer: Moralis Cash. That is the place you may discover true crypto alpha tokens and gather 500 Moralis Beans day by day.
What’s a Blockchain Explorer?
A blockchain explorer is a particular form of decentralized software (dapp) enabling you to discover the publicly accessible on-chain information. With a correct blockchain explorer, you may view token particulars, transactions, tackle balances, and extra.
You most likely know that there are various programmable blockchains up and operating, and every blockchain has its personal official blockchain explorer. Main examples embody Etherscan for Ethereum, PolygonScan for Polygon, BscScan for BNB Chain, SnowTrace for Avalanche, FTMScan for Fantom, and so forth. Other than Ethereum and EVM-compatible chains, there are additionally blockchain explorers for non-EVM-compatible chains. An amazing instance of that’s the Solana explorer Solscan.
Since all chains have their official blockchain explorers, why must you create a blockchain explorer your self? Effectively, the 2 foremost causes are simplification and person retention. For those who’ve used any of the aforementioned block explorers, you realize that their UX expertise isn’t nice, particularly not for crypto freshmen. Thus, it is smart to create blockchain explorers with nice UIs that simplify the expertise. Maybe you may obtain that by focusing solely on particular options. Furthermore, by including a user-friendly blockchain explorer to your dapps, you may be sure that your customers keep round whereas checking if their transactions went by means of.
How you can Create a Blockchain Explorer – Abstract
In at present’s article, you had an opportunity to observe our lead and create a blockchain explorer backend. For those who determined to stay round and full our tutorial, you created a NodeJS dapp powered by an “index.js” script. Inside that script, you carried out 4 highly effective Moralis Web3 Information API endpoints. You additionally realized how you can acquire your Web3 API key and retailer it in a “.env” file. Moreover, you had a possibility to get impressed by our demo to create a frontend on your blockchain explorer. Now, in the event you determined to create a NextJS app that handles the frontend, you had two choices:
- You can construct it from scratch following the video tutorial on the prime of this text.
- Or, you may’ve merely cloned our frontend script from our GitHub repository.
All in all, you now know how you can create a moderately advanced dapp utilizing JavaScript and Moralis. As such, you might be able to sort out different kinds of dapps.
In case you have your individual dapp concepts, simply dive into the Moralis docs and begin BUIDLing. Nevertheless, in the event you want inspiration, motivation, and/or need to be taught extra about Web3 growth, go to the Moralis YouTube channel and weblog. That is the place you’ll find quite a few glorious tutorials and blockchain growth subjects. A number of the newest articles dive into the Solana devnet, Web3 market growth, constructing a Polygon portfolio tracker, exploring the main Goerli faucet, and way more. In case you want help with the technical points of scaling your dapps, make certain to achieve out to our gross sales staff!