๐Ÿ–จ
Connect with Node.js
Once you have your Moralis Server launched it's time to connect to it via the Moralis SDK. This guide will show you how you can do it in just a few easy steps.

Installing Moralis SDK

Run the following command to install Moralis SDK
npm
yarn
1
npm install moralis
Copied!
1
yarn add moralis
Copied!

SDK Initialization

You need to initialize Moralis SDK with the following syntax in node.js:
Create a file index.ts and add below code:
index.ts
1
/* import moralis */
2
const Moralis = require("moralis/node");
3
โ€‹
4
/* Moralis init code */
5
const serverUrl = "YOUR-SERVER-URL";
6
const appId = "YOUR-APP-ID";
7
const masterKey = "YOUR-MASTER-KEY";
8
โ€‹
9
await Moralis.start({ serverUrl, appId, masterKey });
Copied!
with masterKey you can directly access the Moralis dashboard without the need for authentication.
Note: With the master key you can use the API, RPC nodes and other features of your Moralis account using the SDK straight from your backend.
Please remember to never leak your master key because once someone gets your master key they will have full access to your Moralis account.

DB query

Saving data

To save object with data copy-paste the following code:
Create a file SaveData.ts and add below code:
SaveData.ts
1
const SaveData = async () => {
2
await Moralis.start({ serverUrl, appId, masterKey });
3
โ€‹
4
const Monster = Moralis.Object.extend("Monster");
5
const monster = new Monster();
6
โ€‹
7
monster.set("strength", 1024);
8
monster.set("ownerName", "Aegon");
9
monster.set("canFly", true);
10
โ€‹
11
await monster.save();
12
};
13
โ€‹
14
SaveData();
Copied!
Run the following command in your terminal:
1
ts-node SaveData.ts
Copied!
Go to your Moralis dashboard and you will see the data saved in the database:

Query

Create a file FindQuery.ts and add below code:
FindQuery.ts
1
const FindQuery = async () => {
2
const Monster = Moralis.Object.extend("Monster");
3
const query = new Moralis.Query("Monster");
4
โ€‹
5
const results = await query.find();
6
console.log(results);
7
};
Copied!
Run:
1
ts-node FindQuery.ts
Copied!
In your console you will see:
1
[
2
ParseObjectSubclass {
3
className: 'Monster',
4
_objCount: 0,
5
id: 'I3tbPplP8T531e0vgBrFVj5O'
6
}
7
]
Copied!
For more info on DB Queries click hereโ€‹

Live Query

Subscribing to Queries to Get Real-Time Alerts Whenever Data in the Query Result Set Changes.
Create a file LiveQuery.ts add the following code in your file:
LiveQuery.ts
1
const LiveQuery = async () => {
2
const Monster = Moralis.Object.extend("Monster");
3
const query = new Moralis.Query(Monster);
4
โ€‹
5
let subscription = await query.subscribe();
6
console.lIog(subscription);
7
};
8
โ€‹
9
LiveQuery();
Copied!
Run:
1
ts-node LiveQuery.ts
Copied!
In your console you will see:
1
Subscription {
2
_events: [Object: null prototype] { error: [Function (anonymous)] },
3
_eventsCount: 1,
4
_maxListeners: undefined,
5
id: 1,
6
query: ParseQuery {
7
className: 'Monster',
8
_where: {},
9
_include: [],
10
_exclude: [],
11
_select: undefined,
12
_limit: -1,
13
_skip: 0,
14
_count: false,
15
_order: undefined,
16
_readPreference: null,
17
_includeReadPreference: null,
18
_subqueryReadPreference: null,
19
_queriesLocalDatastore: false,
20
_localDatastorePinName: null,
21
_extraOptions: {},
22
_hint: undefined,
23
_explain: undefined,
24
_xhrRequest: { task: null, onchange: [Function: onchange] }
25
},
26
sessionToken: undefined,
27
subscribePromise: Promise {
28
undefined,
29
resolve: [Function (anonymous)],
30
reject: [Function (anonymous)]
31
},
32
subscribed: true,
33
[Symbol(kCapture)]: false
34
}
Copied!
For more info on Live Queries click hereโ€‹

Web3API use

Create a file Web3API.ts and add the below code:
Web3API.ts
1
const serverUrl = "YOUR-SERVER-URL";
2
const appId = "YOUR-APP-ID";
3
const moralisSecret = "YOUR MORALIS SECRET";
4
โ€‹
5
const web3API = async () => {
6
await Moralis.start({ serverUrl, appId, moralisSecret });
7
โ€‹
8
const price = await Moralis.Web3API.token.getTokenPrice({
9
address: "0xe9e7cea3dedca5984780bafc599bd69add087d56",
10
chain: "bsc",
11
});
12
console.log(price);
13
};
14
โ€‹
15
web3API();
Copied!
with moralisSecret all API calls go directly to the API instead of passing through the Moralis Server.
To get moralisSecret you need to go to account settings as shown in image below
then API and copy your moralisSecret key
Run:
1
ts-node Web3API.ts
Copied!
You will see the following result:
1
{
2
nativePrice: {
3
value: '2492486316397403',
4
decimals: 18,
5
name: 'Binance Coin',
6
symbol: 'BNB'
7
},
8
usdPrice: 1.000879782388469,
9
exchangeAddress: '0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73',
10
exchangeName: 'PancakeSwap v2'
11
}
Copied!

Enable Moralis with Private key

Moralis.Transfer

We can transfer using a private key in the backend any 'native' | 'erc20' | 'erc721' | 'erc1155' tokens.
Create a file tranx.ts and add below code:
tranx.ts
1
const tranx = async () => {
2
await Moralis.start({ serverUrl, appId, moralisSecret });
3
โ€‹
4
// Enable web3
5
await Moralis.enableWeb3({
6
//BSC mainnet
7
chainId: 0x38,
8
privateKey: "YOUR-PRIVATE KEY",
9
});
10
โ€‹
11
// sending 0.5 DAI tokens with 18 decimals on BSC mainnet
12
const options: Moralis.TransferOptions = {
13
type: "erc20",
14
amount: Moralis.Units.Token("0.5", 18),
15
receiver: "0x93905fd3f9b8732015f2b3Ca6c16Cbcb60ECf895",
16
contractAddress: "0x1AF3F329e8BE154074D8769D1FFa4eE058B1DBc3",
17
};
18
await Moralis.transfer(options).then((result) => {
19
console.log(result);
20
});
21
};
22
โ€‹
23
tranx();
Copied!
with moralisSecret all API calls go directly to the API instead of passing through the Moralis Server.
Note: Private key should never be exposed to front-end or browser or on cloud or else will result in loss of funds
Run:
1
ts-node tranx.ts
Copied!
You will see the result in your terminal:
1
{
2
nonce: 9,
3
gasPrice: BigNumber { _hex: '0x012a05f200', _isBigNumber: true },
4
gasLimit: BigNumber { _hex: '0x8d07', _isBigNumber: true },
5
to: '0x1AF3F329e8BE154074D8769D1FFa4eE058B1DBc3',
6
value: BigNumber { _hex: '0x00', _isBigNumber: true },
7
data: '0xa9059cbb00000000000000000000000093905fd3f9b8732015f2b3ca6c16cbcb60ecf89500000000000000000000000000000000000000000000000006f05b59d3b20000',
8
chainId: 56,
9
v: 147,
10
r: '0x2715e0d05fdf82f7e129c1d0608de4629d15fffa557d43339d78489d80f78a0f',
11
s: '0x12ab674095e18b1e81525e30826b55ebcc24cddfceed855c26819aafdd4f78d3',
12
from: '0x7094F8B1a2a1EeA360D79Be99bAeF18175aa30Ca',
13
hash: '0xc53417f3f584680ad81046195c64edf59f8a2eb6826793765676ebe304f74760',
14
type: null,
15
confirmations: 0,
16
wait: [Function (anonymous)]
17
}
Copied!

Moralis.executeFunction

Create a file execute.ts and add below code:
execute.ts
1
const execute = async () => {
2
await Moralis.start({ serverUrl, appId, moralisSecret });
3
โ€‹
4
// Enable web3
5
await Moralis.enableWeb3({
6
chainId: 0x1,
7
privateKey:
8
"afcf6a8d1a2b9e20bd322850afb28085693f436427fe8da3d0e40954cfb2d0dc",
9
});
10
โ€‹
11
const options = {
12
// CAPSULE contract
13
contractAddress: "0xfcb1315c4273954f74cb16d5b663dbf479eec62e",
14
// calling tokenURI function
15
functionName: "tokenURI",
16
// contract ABI
17
abi: [
18
{
19
inputs: [{ internalType: "uint256", name: "tokenId", type: "uint256" }],
20
name: "tokenURI",
21
outputs: [{ internalType: "string", name: "", type: "string" }],
22
stateMutability: "view",
23
type: "function",
24
},
25
],
26
// token URI of token ID 700
27
params: { tokenId: 700 },
28
};
29
await Moralis.executeFunction(options).then((result) => {
30
console.log(result);
31
});
32
};
33
โ€‹
34
execute();
Copied!
with moralisSecret all API calls go directly to the API instead of passing through the Moralis Server.
Run:
1
ts-node execute.ts
Copied!
You will see the result in your terminal:
1
https://hatch.capsulehouse.io/api/metadata/700
Copied!
For more info on executeFunction check hereโ€‹

Add New Address Sync From Code

The Sync and Watch Address plugin calls a Cloud Function called watchXxxAddressunder the hood, where "Xxx" are the chain names here. These cloud functions can also be called directly from your own code!
Create a file watchAddr.ts and add below code:
watchAddr.ts
1
const watchAddr = async () => {
2
await Moralis.start({ serverUrl, appId, masterKey });
3
โ€‹
4
await Moralis.Cloud.run(
5
"watchBscAddress",
6
{ address: "0x..." },
7
{ useMasterKey: true }
8
).then((result) => {
9
console.log(result);
10
});
11
};
12
โ€‹
13
watchAddr();
Copied!
Run:
1
ts-node watchAddr.ts
Copied!
in Terminal you will see:
1
{ status: 200, data: { success: true, result: true } }
Copied!
The transaction data is stored in Moralis Dashboard:
By default, only new transactions made by addresses being watched by using this cloud function will be added to the database. If you also want to add historical data for addresses that you want to watch, you can add sync_historical:true
Note: The watch address functions return no value as they start a job. They are still asynchronous though! Once the promise returns the synced transactions, they should be in the XxxTransactions table for the corresponding chain.

Add New Event Sync From Code

Watch new smart contract event

Moralis Server has a special cloud function called watchContractEvent(options). You can call it using the master key.
Note: at the moment the events created via code won't be seen in the admin UI, you can only see them in the database, we are working on connecting the admin UI properly
Create a file watchEvent.ts and add below code:
watchEvent.ts
1
const watchEvent = async () => {
2
await Moralis.start({ serverUrl, appId, masterKey });
3
// code example of creating a sync event from cloud code
4
let options = {
5
chainId: "42",
6
// UniswapV2Factory contract
7
address: "0x5c69bee701ef814a2b6a3edd4b1652cb9cc5aa6f",
8
topic: "PairCreated(address, address, address, uint256)",
9
abi: {
10
anonymous: false,
11
inputs: [
12
{
13
indexed: true,
14
internalType: "address",
15
name: "token0",
16
type: "address",
17
},
18
{
19
indexed: true,
20
internalType: "address",
21
name: "token1",
22
type: "address",
23
},
24
{
25
indexed: false,
26
internalType: "address",
27
name: "pair",
28
type: "address",
29
},
30
{
31
indexed: false,
32
internalType: "uint256",
33
name: "test",
34
type: "uint256",
35
},
36
],
37
name: "PairCreated",
38
type: "event",
39
},
40
limit: 500000,
41
tableName: "UniPairCreated",
42
sync_historical: false,
43
};
44
โ€‹
45
Moralis.Cloud.run("watchContractEvent", options, { useMasterKey: true }).then(
46
(result) => {
47
console.log(result);
48
}
49
);
50
};
51
โ€‹
52
watchEvent();
Copied!
Run:
1
ts-node watchEvent.ts
Copied!
In the terminal you will see:
1
{ success: true }
Copied!
The Event data is succesfully stored in Moralis Dashboard