Quick Start

Get your first dapp up and running with Moralis.

Create a Moralis server instance

To get started, sign up for a free account at Moralis.io. Once you log in click "Create a new App".

Mainnet vs Testnet vs Local

There are 3 environment choices when a new instance is created. Moralis can sync transactions from multiple blockchains simultaneously but only from Mainnet or only from Testnet... not both at the same time.

  • YES ✅: Polygon Mainnet + Binance Smart Chain Mainnet

  • YES ✅: Polygon Testnet (Mumbai) + Binance SmartChain Testnet

  • NO❌: Etherem Mainnet + Polygon Testnet (Mumbai)

  • NO❌: Ganache (Local) + Ethereum Testnet (Ropsten)

To use both Mainnet AND Testnet requires creating 2 separate server instances.

Mainnet Server

Choosing Mainnet will connect your Moralis Server to the production "for keeps" blockchain. Transactions on Mainnet have real financial consequences.

For dapps that only read from the blockchain- like a portfolio app- it's perfectly safe to create a server directly on Mainnet.

Testnet Server

Exactly like Mainnet, but for testing. All tokens on Testnets are worthless. In fact there are faucets where developers can get tokens to test with for free. Testnet is a great "staging" environment for final testing before deploying to Mainnet.

Local Devchain Server

This is a blockchain that runs locally on your computer. When building your smart contracts you'll probably want to start with a Local Devchain like Ganache or Hardhat as these are really fast. You have full control over a local chain, which comes in handy for creating unit tests.

Choose Chains

Choose a name, select your desired location, and choose which networks (blockchains) your app needs to connect to (or all of them!).

You can some or all blockchains!

It will take a few minutes for the server to spin up. Once it's finished it will look something like this.

Moralis Server instance

Expand the server instance to view more details by pressing the "..." button

Expanded server view
  • The Dashboard is the "nuts and bolts" view where you can see all the database tables and logs

  • Install Plugins to extend the functionality of your Moralis Server

  • Cloud Functions are custom functions that run on the server instead of the client

  • The Update/Restart button is to update to the latest server version... or to "turn it off and on again"!

Setting Up Local Dev Chain (optional)

When building new smart contracts you need a fast and controlled testing environment. This is where hosting your own local blockchain is extremely useful. If you're new to Web3 development this part can be skipped- use Mainnet or Testnet instead there's plenty you can do with Moralis with existing smart contracts, transactions, and authentication.

To connect Moralis to Ganache or Hardhat check out the video tutorials in the "Setting Up Local Dev Chain" guide.

Email Configuration (optional)

Moralis supports sending emails to users. Click the "View Details" button on your server instance then the "Email Configuration" tab. You will need to sign up for a SendGrid account and provide the following:

  • API key

  • From Email. This will appear as the "from" address on emails received by users.

Sending an email must be done on the server-side via Cloud Code as it requires the MasterKey. This is to help prevent the domain from being blacklisted for spam by bad actors.

// in Cloud Code
Moralis.Cloud.define("sendEmailToUser", function (request) {
Moralis.Cloud.sendEmail({
to: request.user.get("email"),
subject: "Fundamentals",
html: "Pampamentally it does make sense https://youtu.be/xXrkgWDcd7c"
});
});

Install the SDK

Via CDN

The fastest way to get the Moralis SDK into your JavaScript project is through npmcdn available at https://unpkg.com/moralis/dist/moralis.js.

<head>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/web3.min.js"></script>
<script src="https://unpkg.com/moralis/dist/moralis.js"></script>
</head>

DON'T USE "LATEST" IN PRODUCTION, ALWAYS SPECIFY THE VERSION

In production, make sure to specify the specific version to guard against malicious package updates.

You can use npm info moralis versions to obtain a list of the available versions and replace <VERSION> below with the latest value.

<head>
<script src="https://cdn.jsdelivr.net/npm/[email protected]<VERSION>/dist/web3.min.js"></script>
<script src="https://unpkg.com/[email protected]<VERSION>/dist/moralis.js"></script>
</head>

Via NPM

For larger projects use the npm module

npm install moralis

Browser

Then include it as usual.

const Moralis = require('moralis');

NodeJs

For server-side applications or NodeJs command line tools, include:

// In a node environment
const Moralis = require('moralis/node');

Moralis Snippets

To help you code fast you can make use of Moralis snippets available as an extension to Visual Studio Code.

With the extension installed, begin by typing: "moralis" anywhere inside a javascript file.

You will get IntelliSense for the available snippets.

Initialize Moralis

In order to use Moralis in your code it needs to be initialized. You'll need the Server URL and APP ID. These can be found by pressing the "View Details" button on the server instance created above.

Moralis.initialize("YOUR_APP_ID");
Moralis.serverURL = 'https://YOUR_MORALIS_SERVER:1337/server'

⚠️ If the Masterkey needs to be provided, use the following. Please note that the master key should only be used in safe environments and never on the client side‼️

Moralis.initialize("YOUR_APP_ID", "", "YOUR_MASTERKEY");
Moralis.serverURL = 'http://YOUR_MORALIS_SERVER:1337/server'

The JavaScript SDK is originally based on the popular Backbone.js framework, but it provides flexible APIs that allow it to be paired with your favorite JS libraries. Our goal is to minimize configuration and let you quickly start building your JavaScript and HTML5 app on Moralis.

The SDK supports Firefox 23+, Chrome 17+, Safari 5+, and IE 10. IE 9 is supported only for apps that are hosted with HTTPS.

Authentication

Authenticating new users with Web3 is as simple as:

Moralis.Web3.authenticate().then(function (user) {
console.log(user.get('ethAddress'))
})

This will prompt the user to connect a Web3 wallet like Metamask and request a signature. Once the signature has been verified the promise will resolve with a User object.

Logout

await Moralis.User.logOut();

How to Authenticate With Metamask, Web3 Development - Ivan on Tech

How to Merge MetaMask Addresses? Web3 Programming Tutorial - Ivan on Tech

User

Current

Once the user has been authenticated the User object can be retrieved from anywhere with

const user = Moralis.User.current();

The current user will always be authenticated. If there is no logged-in user Moralis.User.current() will return null.

Getting Attributes

The User object itself looks like the following.

{
className: "_User",
id: "EFurGjRPhl",
_objCount: 0,
attributes: {
ACL: ParseACL {permissionsById: {}},
accounts: ["0xda...cb83"],
authData: {moralisEth: {}},
createdAt: Date,
ethAddress: "0xda...cb83",
sessionToken: "r:3be8c91cb4db8fe2f154021f96496f49",
updatedAt: Date,
username: "Y9jPGr0H1TcMFHUpYZPjj9xhE",
}
}

There are 2 methods for getting user attributes

const user = Moralis.User.current();
const userAddress = user.get("ethAddress");
const username = user.attributes.username;

Setting Attributes

Always use the set() method to change user attributes. Then call save(). Any new attributes will be created automatically.

user.set("phone", "555-555-1234");
user.set("birthDate", "2000-01-01");
await user.save();

For more details see the Users Section.

Queries

Creating

Once you have data stored in Moralis, you'll probably want to use it! The foundation of retrieving data is the Query. A query describes what data to retrieve and from where.

// set the collection to query
const collectionName = "EthTokenBalance";
const query = new Moralis.Query(collectionName);

Constraints

To filter the data returned by a query all the usual constraints like equalTo, notEqualTo, greaterThan, lessThanOrEqualTo, containedIn, and limit are available. The query object uses similar syntax as MongoDB queries.

// users with DOGE tokens
query.equalTo("symbol", "DOGE");
// where the balance > 0
query.greaterThan("balance", 0);
// at most 10 results
query.limit(10);
const results = await query.find();

Sorting

The data can also be sorted according to specific attributes using the ascending and descending functions.

// highest to lowest balance
query.descending("balance");

Results

Once the query is constructed the results can be obtained using find.

const results = await query.find();
// [EthTokenBalance, EthTokenBalance, ...]

Or only the first

// get a specific user by email
const query = new Moralis.Query(Moralis.User);
query.equalTo("email", "[email protected]");
const user = await query.first();
// {id: "23r2r2qawsdf", attributes: {...} }

For more details see the Queries page

Historical Transaction Data

Whenever a new user is authenticated via Web3, all of their transactions are synced by Moralis into the EthTransactions collection. This data can then be queried.

// get all ETH transactions made by the user
const user = Moralis.User.current();
const transQuery = new Moralis.Query("EthTransactions");
transQuery.equalTo("from_address", user.get("ethAddress"));
const results = await transQuery.find();
console.log(results);
// [EthTransaction, EthTransaction, ...]

Note that querying user-related data like transactions requires permissions governed by the Access Control List (ACL). This means any data private to a specific user, like transactions, can only be queried by that user. Querying data from other users (like finding someone's profile) requires using the MasterKey. For security reasons, the master key should only be used on the server inside Cloud Functions.

Real-Time Data

Historical data is great, but what if you're building a blog site and want to display a special message whenever a new user buys your BLOG token? This is where Live Queries come in. In addition to grabbing the historical results with find(), a query can be subscribed to!

// BLOG token holders
const query = new Moralis.Query("EthTokenBalance");
query.equalTo("symbol", "BLOG");
query.greaterThan("balance", 0);
// subscribe for real-time updates
const subscription = await query.subscribe();
// handle events
subscription.on("create", function(data) {
console.log(data.attributes.address, " has joined the BLOG army!");
});

This will cause an event to be fired whenever the dataset defined by the query changes.

  • create: when a new object is created and fulfills the query

  • update: when an existing object in the query is updated and both the old and new values satisfy the query

  • enter: when an existing object's old values did not satisfy the query but the new values do

  • leave: when an existing object's old values satisfied the query but new values do not

  • delete: when an existing object is deleted

Live queries can be created for any other collection as well. See the Live Query page for more details. To receive real-time updates on smart contract events see the Plugins section of the Web 3 page.

Ethereum Real-Time and Historic Transactions - Web3 Programming