WEB3 QUICK DIVE with Moralis Web3 SDK
Table of contents
What is Web3? There is no doubt that WEB3 is the latest technology buzz word and we will all agree that every developer out there would love to venture into this space. Now we should know what really is web3 once and for all.
Web3 is a shift from the web architecture we are accustomed to where we get our data and other resources from a central server, there is only a single source of truth. Rather, it is an architecture where we have several nodes/ computers playing the role of the server where they all store the same data, hence we have a decentralized system which is the key point of web3.
With WEB3 we are able to develop dAPPs (Decentralised Applications) which are capable of interacting with blockchain servers, asides being in tune with the new skill in our domain as developers we also get to make money since WEB3 developers are highly sought after by big tech companies and startups too.
There are a plethora free resources in the wild to learn about the story behind this technology but here we are going to quickly dymistify dAPP and build one. Yes! you heard that right. And what this means is that we are going to build an application that interacts with the almighty Ethereum blockchain network to get account and transaction information example account balance (ethers), transaction dates, block e.t.c.
We have number of languages that can be used to build dAPP among which are Rust, JavaScript, Pyhton. But as developers we know how cumbersome it can be trying to build a robust web application with Vanilla JavaScript which is why we now have ReactJs, VueJs, Svelte and the likes to provide structure and sanity. Likewise in this project we are going to make use of a sdk which is built on top of a JavaScript package called web3.js. We will be using the Moralis web3 sdk and according to the documentation it says
Moralis is the easiest and most reliable way to add web3 capabilities into any tech stack. Moralis is cross-chain by default supporting many chains and L2s such as Ethereum, BNB Chain, Polygon, Avalanche, Fantom, Solana and Elrond.
LET'S GET STARTED
As you may have guessed, we will be building a nodejs %[ nodejs.org ] backend using the Moralis sdk to communicate with the ethereum blockchain. This means you need to
have nodejs installed on your machine whether mac or pc.
create a moralis %[ moralis.io ] account and
download %[ metamask.io ] or install google chrome extension if you are using chrome (like me). The metamask creates our crypto wallet and address and links our account to the blockchain which is the ethereum blockchain in this case. We can also get free test ethers from %[ rinkebyfaucet.com ] credited to our account and visible on both metamask and etherscan [ rinkeby.etherscan.io ]. Etherscan is a platform that documents every transaction on the ethereum blockchain network.
- have your editor setup, i will be using vscode %[ code.visualstudio.com ]
STEP ONE
Initialize a nodejs application: open up your terminal and navigate to the directory where you would love to create your project, run:
npm init -y
Install the dependencies express and moralis, run:
npm install express moralis @moralisweb3/evm-utils
Install dotenv inorder to use node environment variables to be declared in our .env file, run:
npm install dotenv
After this step we will have a package.json file that looks like so:
//package.json
{
"name": "moralis_server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"start": "node app.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@moralisweb3/evm-utils": "^2.0.1",
"dotenv": "^16.0.1",
"express": "^4.18.1",
"moralis": "^2.0.1"
}
}
As you can see in the json I have set the type field to module so we can use es6 syntax, I have also set the start script.
STEP TWO
Set up an express server as you normally would and have it running. Go to your moralis.io account and get the api key from the Keys tab under Account Settings and copy the Web3 Api Key
STEP THREE
//app.js
import dotenv from 'dotenv'
dotenv.config()
import express from'express'
import Moralis from 'moralis'
import { EvmChain} from '@moralisweb3/evm-utils'
const port = process.env.PORT || 3000
const web3api = process.env.MORALIS_API_KEY
const chain = EvmChain.RINKEBY
const app = express()
app.get('/', (req,res)=> {
return res.send('Hello world.')
})
async function startServer(_params) {
app.listen(port, ()=> console.log(`Server running on port ${port}`))
await Moralis.default.start({apiKey: web3api}).then(() => console.log('Successfully connected to Moralis
server.'))
}
startServer()
Open your terminal in the root directory of this project and run
npm run start
you should get this output in the terminal
mac@mac-MacBook-Pro moralis_server % npm run start
> moralis_server@1.0.0 start
> node app.js
Successfully connected to Moralis server.
Server running on port 3000
STEP FOUR
Now let us try to get our account balance from the ethereum blockchain. Remember that we got some free test ethers from %[rinkebyfaucet.com] which was 0.1ethers. This balance can be seen on our metamask dashboard and by following the etherscan link on our metamask. In order to get this balance from our app we will create a helper function in util.js and import it in our app.js
//util.js
import Moralis from "moralis";
export default async function getEtherBalance(address, chain) {
const nativeBalance = await Moralis.default.EvmApi.account.getNativeBalance({address,chain})
const native = nativeBalance.result.balance.ether
return { native }
}
//app.js
import dotenv from 'dotenv'
dotenv.config()
import express from'express'
import Moralis from 'moralis'
import { EvmChain} from '@moralisweb3/evm-utils'
import getEtherBalance from './utils.js'
const port = process.env.PORT || 3000
const web3api = process.env.MORALIS_API_KEY
const chain = EvmChain.RINKEBY
const app = express()
app.use(express.json())
app.get('/', (req,res)=> {
return res.send('Hello world.')
})
app.post('/ether-balance', async (req, res) => {
const { address } = req.body
try {
const data = await getEtherBalance(address, chain)
res.status(200).json({data})
} catch (error) {
res.status(500).json({error: error.message})
}
})
async function startServer(_params) {
app.listen(port, ()=> console.log(`Server running on port ${port}`))
await Moralis.default.start({apiKey: web3api}).then(() => console.log('Successfully connected to Moralis server.'))
}
startServer()
As we can see from the code snippet above, we need to pass the address we got from metamask (or any other) in the request body
Conclusion In this article we have excercised the easy way to building a web3 application which gets wallet balance from the Ethereum blockchain using the moralis web3 sdk.
This article was written by following the official moralis web3 documentation at %[ https://docs.moralis.io/docs/nodejs-dapp-from-scratch ] I hope this article helps you to take that step into web3. The complete source code can be found here %[ https://github.com/kennie-larkson/moralis-web3 ] Do leave your comment and reviews. Thanks
PS: you can also reach me on twitter @ %[ https://twitter.com/kennie_larkson ] for further engagements :)
Subscribe to my newsletter
Read articles from Abdulrafiu Kehinde Lawal directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Abdulrafiu Kehinde Lawal
Abdulrafiu Kehinde Lawal
I am web developer specializing in backend technologies. I have over 3 years experience writing Nodejs backend solutions of varying scale and purposes. Learning new technologies and expanding my skill set is my goal.