Moralis - Getting Started

Moralis - Getting Started

  • Step 1: Sign up for Moralis and create your free account

  • Step 2: Get the API Key from the dashboard

Remember you can use Moralis, both, on the front end as well as the backed

Quickstart: Node.js (Backend)

After you've created your account, installed node.js, and opened the editor of your choice.

npm init //acts as a gateway to the project you are building.

install the required dependencies:

 npm install moralis express @moralisweb3/common-evm-utils

Moralis: is the library that we'll be using to connect and interact with the smart contract.
express: is your wrapper around node.js that helps you write efficient API calls.
@moralisweb3/common-evm-utils: provides a set of helper functions that help developers interact with the Ethereum Virtual Machine (EVM), which is a kind of "engine" that runs programs on the Ethereum network.

Now that's out of the way. we create a index.js file which when running acts as a server.

const express = require('express');
const app = express();
port = 3000;

app.get("/",(req,res)=>{
   res.send("Hello World")
})

app.listen(port,()=>{console.log("Listening on port 3000")});

There is no moralis connected there, just wanted to jog your memory if you forgot how to write an express server.

Add Moralis to the server
const express = require("express");
const Moralis = require("moralis").default;
//EvmChain basically helps us to point to the chain we want to use.
const { EvmChain } = require("@moralisweb3/common-evm-utils");

const app = express();
const port = 3000;

// Add a variable for the api key, address and chain
const MORALIS_API_KEY = "replace_me";
const address = "replace_me";
const chain = EvmChain.ETHEREUM;

//just basic node stuff
app.get("/", (req, res) => {
  res.send("Hello World!");
});

//Initializing moralis

// Add this a startServer function that initialises Moralis
const startServer = async () => {
  await Moralis.start({
    apiKey: "xxx", //get this from the dashboard
  });

  app.listen(port, () => {
    console.log(`Example app listening on port ${port}`);
  });
};

// Call startServer()
startServer();
Now lets deal with small code snippets to understand better.
  • Get the balance of a given address for a specific chain

      async function getBalance(){
    
      //this value depends on the chain you are working with, is it BNB, or MATIC? depends on the chain ID
      const balance = await Moralis.EvmApi.balance.getNativeBalance({
      address,
      chain
      })
    
      // Format the native balance formatted in ether via the .ether getter
      const NativeBalance = balance.result.balance.ether //BNB in Ethers
    
      return NativeBalance
    
      }
    
  • what if I want to know the balance of all the tokens presents in a given address?

    
        // Get all the tokens assocaiated to a given public address
        const tokenBalances = await Moralis.EvmApi.token.getWalletTokenBalances({
          address, //for that address
          chain, //on that given chain
        });
    
      const token = tokenBalance.result.map(token=>token.display());
    

    Now you're probably wondering if this above function displays all the tokens associated with a given address, why do we need to specify the chain Id?
    The answer is the BNB contract can have multiple ERC20 tokens associated with it. as well as so is any other chain on the Ethereum network.

  • Fetching NFTs
    The getWalletNFTs() function is a part of the Moralis.EvmApi API and is used to retrieve the non-fungible tokens (NFTs) owned by a particular Ethereum address on a specific blockchain network.

  •       // Get the nfts associated to that addesss. 
          const nftsBalances = await Moralis.EvmApi.nft.getWalletNFTs({
            address,//address of the contract owning the NFT's
            chain,//which chain is it on.
            limit: 10,
          });
    
          // Format the output to return name, amount and metadata
          const nfts = nftsBalances.result.map((nft) => ({
            name: nft.result.name,
            amount: nft.result.amount,
            metadata: nft.result.metadata,
          }));
    
          // Add nfts to the output
          return {nfts };
    

Congratulations 🥳 you just got all the NFTs owned by an address with just a few lines of code using Moralis NFT API!

chain in the above parameter can be an array holding as many chains as you want

` const chain = [EvmChain.ETHEREUM, EvmChain.BSE, EvmChain.POLYGON]`

if you wish you can use a for loop to run across each chain and find them individually

So basically you have the list of NFTs across multiple chains, owned by an address.

That is pretty much how you use Moralis on Node.js

Understanding Moralis with NFT

Now what if you want to find all the NFTs minted by a given contract? Moralis has you covered.

The getContractNFTs() function works by querying the blockchain network and searching for all the NFTs that have been minted by the specified NFT contract. When the function is called, it returns an array of objects, with each object representing an NFT that has been minted by the specified contract. The object contains various information about the NFT, such as its name, contract address, and token ID.
Since it returns an array, we can filter anything based on what parameters we want.
Below is the code snippet that will help you understand the syntax.

  const response = await Moralis.EvmApi.nft.getContractNFTs({
    address, //address of the contract.
    chain, // the chain you published the contract on.
  });

Nft-Transfer

  • You can get the list of NFTs transfered on a given block

      const response = await Moralis.EvmApi.nft.getNFTTransfersByBlock({
       blockNumberOrHash,
       chain,
       });
    
  • getNFTContractTransfers() - this basically helps to track the transfer of ownership from its mint from the contract to all the addresses it has passed.
    you can also track the value of it over time.
    Using the above we get ALL TRANSFERS of an NFT Collection

        const response = await Moralis.EvmApi.nft.getNFTContractTransfers({
          address,// Ethereum address of the NFT contract whose transfers you want to retrieve
          chain,
        });
    
  • Get all NFTs owned by the address.

        const response = await Moralis.EvmApi.nft.getWalletNFTCollections({
          address, //NFTs owned by this address
          chain, //on this specific chain
        });
    

    The result is an array, so you can run a filter to choose a specific NFTs, if you choose it to be.

  • Now say you want to give all those address's who bought a NFT from your contract an Airdrop NFT. you can get a list of addresses who purchased your NFT by using the `getNFTOwners` function. you'll end up getting a list of addresses, along with some other metadata.

        const response = await Moralis.EvmApi.nft.getNFTOwners({
          address,
          chain,
        });
    
  • Say you want to get the owners who own a specific tokenId, this can be helpful when dealing with ERC1155. In this case we can use the getNFTTokenIdOwners() method.

        const response = await Moralis.EvmApi.nft.getNFTTokenIdOwners({
          address, //address of the contract
          chain, //chain where you deployed the contract
          tokenId, //token Id 
        });
    
  • You can get all the NFT owned by an Address

        const response = await Moralis.EvmApi.nft.getNFTOwners({
            address,
            chain,
        });
    
  • There are times when the meta data is all clustered, and its hard to make sense of it. such meta data is called non normalised meta data, If you want to normalise that metadata, you'll have to do the below.

    Non Normalised metadata

    Normalised meta data will look like this

    Below is the code to transform non-normalised to normalised metadata, so its easy to work with.

      const metadata = {
        name: "My NFT",
        description: "This is my NFT",
        image: "https://ipfs.moralis.io/ipfs/QmW7LmKjG3LfvbSVrtnLVzV7jK6c2zVfnNQUhRJjBYQTyu",
        external_url: "https://mynft.com"
      };
    
      const normalizedMetadata = await Moralis.Web3API.token.normalizeNFTMetadata(metadata);
    
      console.log(normalizedMetadata);
    
  • In order to get an NFT by the address and token_id, Moralis provides you with an getNFTMetadata endpoint to do so.

    Here you'll need two parameters: address and token_id.

        const response = await Moralis.EvmApi.nft.getNFTMetadata({
          address,
          chain,
          tokenId,
          "normalizeMetadata": false, //easy to read metadata
          "mediaItems": true //Image-Preview
        });
    
        console.log(response.toJSON());
    

Lets talk about Image Preview

The Moralis NFT API allows for the generation of low, medium, and high-resolution thumbnails for NFT images, improving the user experience by offering optimized image sizes for various use cases. This allows developers to easily integrate faster-loading images into their applications, reducing page load times and enhancing the overall user experience.

So thats all about using Moralis's APIs to interact with NFT's