Web3 Provider
Web3 Specific Functionality of the Moralis SDK.
Let's talk about Web3 integration!
Moralis comes with a set of plugins to help you focus on the development of your app, leaving the rest to us.
Similar to window.ethereum.enable() but returns a promise that resolves to a web3Provider instance from Ethers.js. Use this when you need a fully functional web3Provider instance, such as for making contract calls.
โ—๏ธ Note: make sure to have v1.0.0 or higher of the SDK installed. Otherwise Moralis.enableWeb3() will return an instance of web3.js instead of ethers.js
Example
1
// Get a (ethers.js) web3Provider
2
const web3Provider = await Moralis.enableWeb3();
Copied!

Web3.js

You might want to use another library, like Web3.js. To do so, you need to include this library to your code.
When you import javascript scripts via html:
1
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/web3.min.js"></script>
Copied!
Or when you use a package manager:
1
npm install web3
Copied!
Then in your code, use Moralis.provider to initialize the web3.js library. Moralis.provider will only be set after calling Moralis.authenticate or Moralis.enableWeb3.
1
import Web3 from "web3"; // Only when using npm/yarn
2
โ€‹
3
// Enable web3 and get the initialized web3 instance from Web3.js
4
await Moralis.enableWeb3();
5
const web3Js = new Web3(Moralis.provider);
Copied!
See for more info on how to use web3.js, in the Web3.js docsโ€‹
Note: Ethers.js is included in the Moralis SDK. So The function responses of Moralis.executeFunction and Moralis.transfer will always be formatted by Ethers.js (see below for more information)

Get the ethers.js library

You can have access to the ethers.js library, that Moralis is using:
1
const ethers = Moralis.web3Library;
Copied!
With this instance, you can use any methods from ethers.js, for example:
1
const ethers = Moralis.web3Library;
2
โ€‹
3
const daiAddress = "dai.tokens.ethers.eth";
4
const daiAbi = [
5
"function name() view returns (string)",
6
"function symbol() view returns (string)",
7
"function balanceOf(address) view returns (uint)",
8
"function transfer(address to, uint amount)",
9
"event Transfer(address indexed from, address indexed to, uint amount)",
10
];
11
const daiContract = new ethers.Contract(daiAddress, daiAbi, provider);
12
โ€‹
13
const name = await daiContract.name();
14
console.log(name);
15
// 'Dai Stablecoin'
Copied!
See for more info on how to use ethers.js, in the ethers.js docsโ€‹

Connectors

You enable web3 with any connector (such as WalletConnect, Metamask, Network etc.), the same way as with Moralis.authenticate), with the provider option:
1
const web3 = await Moralis.enableWeb3({ provider: "walletconnect" });
Copied!

NodeJs Enviroment

When using moralis in a nodejs environment, you can optionally use the privateKey option to sign transactions:
1
const web3 = await Moralis.enableWeb3({ privateKey: "your_private_key" });
Copied!

In Cloud Functions

It's also possible to get a Web3 instance inside cloud functions, but the syntax is a bit different. See the Cloud Functions Web3 page for more info.
This instance is a Web3.js instance

executeFunction

Via executeFunction, you can execute read-only (view) functions, and write methods. They both give a slightly different response. So we handle them seperately below.
Options:
  • contractAddress (required): A smart contract address
  • abi (required): Contract's or function ABI(should be provided as an array)
  • functionName (required): A function name
  • params (required): Parameters needed for your specific function
  • msgValue(optional): Number|String|BN|BigNumber. The value transferred for the transaction in wei.

Read-only functions

For read-only functions, you will need to wait for the execution to be completed. Then you get the results back directly.
1
const ABI = [
2
{
3
inputs: [],
4
name: "message",
5
outputs: [
6
{
7
internalType: "string",
8
name: "",
9
type: "string",
10
},
11
],
12
stateMutability: "view",
13
type: "function",
14
},
15
{
16
inputs: [
17
{
18
internalType: "string",
19
name: "_newMessage",
20
type: "string",
21
},
22
],
23
name: "setMessage",
24
outputs: [],
25
stateMutability: "nonpayable",
26
type: "function",
27
},
28
];
29
โ€‹
30
const readOptions = {
31
contractAddress: "0xe...56",
32
functionName: "message",
33
abi: ABI,
34
};
35
โ€‹
36
const message = await Moralis.executeFunction(readOptions);
37
console.log(message);
38
// -> "Hello World"
Copied!
Requires an enabled web3 provider. Before executing the function, make sure that the correct network is selected in your wallet.
You can receive this information without an active web3 provider using our Web3API: Moralis.Web3API.token.getAllowance()โ€‹

Example of calling a write contract method

An example of calling setting a message via a setMessage function.
1
const ABI = [
2
{
3
inputs: [],
4
name: "message",
5
outputs: [
6
{
7
internalType: "string",
8
name: "",
9
type: "string",
10
},
11
],
12
stateMutability: "view",
13
type: "function",
14
},
15
{
16
inputs: [
17
{
18
internalType: "string",
19
name: "_newMessage",
20
type: "string",
21
},
22
],
23
name: "setMessage",
24
outputs: [],
25
stateMutability: "nonpayable",
26
type: "function",
27
},
28
];
29
โ€‹
30
const sendOptions = {
31
contractAddress: "0xe...56",
32
functionName: "setMessage",
33
abi: ABI,
34
params: {
35
_newMessage: "Hello Moralis",
36
},
37
};
38
โ€‹
39
const transaction = await Moralis.executeFunction(sendOptions);
40
console.log(transaction.hash);
41
// --> "0x39af55979f5b690fdce14eb23f91dfb0357cb1a27f387656e197636e597b5b7c"
42
โ€‹
43
// Wait until the transaction is confirmed
44
await transaction.wait();
45
โ€‹
46
// Read new value
47
const message = await Moralis.executeFunction(readOptions);
48
console.log(message);
49
// --> "Hello Moralis"
Copied!
You will get back a transaction response from ethers.js, that includes the hash and other information.
Example transaction response
1
{
2
"hash": "0x39af55979f5b690fdce14eb23f91dfb0357cb1a27f387656e197636e597b5b7c",
3
"type": 2,
4
"accessList": null,
5
"blockHash": null,
6
"blockNumber": null,
7
"transactionIndex": null,
8
"confirmations": 0,
9
"from": "0xab5801a7d398351b8be11c439e05c5b3259aec9b",
10
"gasPrice": {
11
"type": "BigNumber",
12
"hex": "0x04cf1ef09a"
13
},
14
"maxPriorityFeePerGas": {
15
"type": "BigNumber",
16
"hex": "0x908a9040"
17
},
18
"maxFeePerGas": {
19
"type": "BigNumber",
20
"hex": "0x04cf1ef09a"
21
},
22
"gasLimit": {
23
"type": "BigNumber",
24
"hex": "0x75c0"
25
},
26
"to": "0x73bceb1cd57c711feac4224d062b0f6ff338501e",
27
"value": {
28
"type": "BigNumber",
29
"hex": "0x00"
30
},
31
"nonce": 13,
32
"data": "0x368b877200000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000004486f6c6100000000000000000000000000000000000000000000000000000000",
33
"r": "0x8b00442b141406a1b5d701c7ac6ab3b6adec13010fdc1218a42f8f9aa8e57718",
34
"s": "0x1abc60ae4de7af8bcba4d1b44e470f40a04c3c632fd4a75f87a553820a43ddef",
35
"v": 1,
36
"creates": null,
37
"chainId": 0
38
}
Copied!
If you want to wait until the transaction has been confirmed by the chain, then you can call transaction.wait(). That will resolve into a transaction receipt. This receipt will also include a log of all the events that have been fired in the transaction. For example here we wait for 3 confirmations:
1
const receipt = await transaction.wait(3);
Copied!
Example receipt
1
{
2
"to": "0x73bceb1cd57c711feac4224d062b0f6ff338501e",
3
"from": "0xab5801a7d398351b8be11c439e05c5b3259aec9b",
4
"contractAddress": null,
5
"transactionIndex": 72,
6
"gasUsed": {
7
"type": "BigNumber",
8
"hex": "0x75b2"
9
},
10
"logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
11
"blockHash": "0x746d7d42e8022f560577dfdc0150e1e8b009e59c537a9053a82e9ad6d20f6d06",
12
"transactionHash": "0x39af55979f5b690fdce14eb23f91dfb0357cb1a27f387656e197636e597b5b7c",
13
"logs": [],
14
"blockNumber": 11847564,
15
"confirmations": 2,
16
"cumulativeGasUsed": {
17
"type": "BigNumber",
18
"hex": "0x6743ab"
19
},
20
"effectiveGasPrice": {
21
"type": "BigNumber",
22
"hex": "0x04623af60c"
23
},
24
"status": 1,
25
"type": 2,
26
"byzantium": true,
27
"events": []
28
}
Copied!

Setting custom gas

Currently to set gas parameters, you will need to use ethers.js or web3.js directly. The following example uses the ethers.js library that comes with Moralis.
1
const ethers = Moralis.web3Library; // get ethers.js library
2
const web3Provider = await Moralis.enableWeb3(); // Get ethers.js web3Provider
3
const gasPrice = await web3Provider.getGasPrice();
4
โ€‹
5
const signer = web3Provider.getSigner();
6
โ€‹
7
// wMATIC token on Mumbai
8
const contract = new ethers.Contract('0x9c3C9283D3e44854697Cd22D3Faa240Cfb032889', ABI, signer);
9
โ€‹
10
const transaction = await contract.deposit({
11
value: Moralis.Units.ETH('1'),
12
gasLimit: 100000000,
13
gasPrice: gasPrice,
14
});
15
await transaction.wait();
Copied!

Transfering native crypto in contract method example

For example, you want to call a smart contract method that exchanges native cryptocurrency for tokens. This case is different from the usual situations where you use ERC20 tokens and specify the number of tokens to use as a method parameter. Action with a native cryptocurrency in a smart contract assumes that you will transfer some value along with the transaction. In solidity you can know it as a msg.value
1
const options = {
2
contractAddress: "0xe...56",
3
functionName: "swapNativeForTokens",
4
abi: ABI,
5
msgValue: Moralis.Units.ETH("0.1"),
6
};
7
โ€‹
8
const transaction = await Moralis.executeFunction(options);
9
const receipt = await transaction.wait();
10
console.log(receipt);
Copied!

Example of creating reusable options

You can use this construction to create reusable options for calling multiple contract methods.
1
const options = {
2
contractAddress: "0xe...56",
3
abi: ABI,
4
};
5
โ€‹
6
const symbol = await Moralis.executeFunction({
7
functionName: "symbol",
8
...options,
9
});
10
const decimals = await Moralis.executeFunction({
11
functionName: "decimals",
12
...options,
13
});
14
const name = await Moralis.executeFunction({
15
functionName: "name",
16
...options,
17
});
Copied!

Resolve transaction result

Moralis.executeFunction() returns:
  • The return value if the function is read-only
  • A transaction response, if the function writes on-chain.
You can resolve the transaction response into a receipt, by waiting until the transaction has been confirmed. For example, to wait for 3 confirmations:
1
const options = {
2
contractAddress: "0xe...56",
3
functionName: "swapNativeForTokens",
4
abi: ABI,
5
msgValue: Moralis.Units.ETH("0.1"),
6
};
7
const transaction = await Moralis.executeFunction(options);
8
const result = await transaction.wait();
Copied!

Events

There are several events, that you can listen to on Moralis, in order to check the web3 connection of the user:
  • onWeb3Enabled
  • onWeb3Deactivated
  • onChainChanged
  • onAccountChanged
  • onConnect (fired from the EIP1193 provider)
  • onDisconnect (fired from the EIP1193 provider)

Moralis.onWeb3Enabled()

Listen to events when a user connects to a chain (via Moralis.authenticate() / Moralis.enableWeb3()):
1
// Subscribe to onWeb3Enabled events
2
const unsubscribe = Moralis.onWeb3Enabled((result) => {
3
console.log(result);
4
});
5
โ€‹
6
// Unsubscribe to onWeb3Enabled events
7
unsubscribe();
Copied!
Result object
1
{
2
account: '0x1a2b3c4d....',
3
chain: '0x1',
4
connector: {} // the connector instance
5
web3: {} // the Ethers.js web3 instance
6
provider: {} // the EIP1193-provider, used to connect
7
}
Copied!

Moralis.onWeb3Deactivated()

Listen to events when a user disconnects to a chain (via Moralis.deactivateWeb3()):
1
// Subscribe to onWeb3Deactivated events
2
const unsubscribe = Moralis.onWeb3Deactivated((result) => {
3
console.log(result);
4
});
5
โ€‹
6
// Unsubscribe to onWeb3Deactivated events
7
unsubscribe();
Copied!
Result object
1
{
2
connector: {
3
} // the connector instance
4
provider: {
5
} // the EIP1193-provider, used to connect
6
}
Copied!

Moralis.onChainChanged()

Listen to events when the user changes a chain, after web3 has been enabled.
1
// Subscribe to onChainChanged events
2
const unsubscribe = Moralis.onChainChanged((chain) => {
3
console.log(chain);
4
// returns the new chain --> ex. "0x1"
5
});
6
โ€‹
7
// Unsubscribe to onChainChanged events
8
unsubscribe();
Copied!

Moralis.onAccountChanged()

Listen to events when the user changes an account, after web3 has been enabled.
1
// Subscribe to onAccountChanged events
2
const unsubscribe = Moralis.onAccountChanged((chain) => {
3
console.log(chain);
4
// returns the new account --> ex. "0x1a2b3c4d..."
5
});
6
โ€‹
7
// Unsubscribe to onAccountChanged events
8
unsubscribe();
Copied!

Moralis.onConnect()

You might want to use Moralis.onWeb3Activated instead, as that is more consistent, and handled by Moralis, instead of the EIP-1193 provider
Listen to events when the provider fires a connect event.
The Provider emits connect when it:
  • first connects to a chain after being initialized.
  • first connects to a chain, after the disconnect event was emitted.
1
// Subscribe to onConnect events
2
const unsubscribe = Moralis.onConnect((provider) => {
3
console.log(provider);
4
// returns the EIP-1193 provider
5
});
6
โ€‹
7
// Unsubscribe to onConnect events
8
unsubscribe();
Copied!

Moralis.onDisconnect()

You might want to use Moralis.onWeb3Deactivated instead, as that is more consistent, and handled by Moralis, instead of the EIP-1193 provider
Listen to events when the provider fires a disconnect event.
The Provider emits disconnect when it becomes disconnected from all chains
1
// Subscribe to onDisconnect events
2
const unsubscribe = Moralis.onDisconnect((error) => {
3
console.log(error);
4
// returns a ProviderRpcError
5
});
6
โ€‹
7
// Unsubscribe to onDisconnect events
8
unsubscribe();
Copied!
To listen to these events you just need to call Moralis.onXXX. For example:
1
const unsubscribe = Moralis.onAccountChanged(function (account) {
2
console.log(account);
3
});
4
// "0x1a2b3c4d..."
Copied!

Metamask (and other wallet) events

If you want to listen for events before an user is connected (on metamask), then you might want to listen to the events from Metamask directly
https://docs.metamask.io/guide/ethereum-provider.html#events
For example
1
window.ethereum.on('accountsChanged' (accounts) => {
2
console.log(accounts)
3
// --> [0x1a2b3c4d...]
4
})
Copied!
Other wallets have similar implementations, please look at the documentation of the respective wallet.

Linking

Link (unlink) an address to the current user.
  • link(address)
  • unlink(address)
The user may have multiple addresses they wish to associate with their profile. This can be done with the link function after the user has been authenticated.
1
Moralis.onAccountChanged(async function (account) {
2
const confirmed = confirm("Link this address to your account?");
3
if (confirmed) {
4
await Moralis.link(account);
5
alert("Address added!");
6
}
7
});
Copied!
The unlink function removes the given address from the user's profile.
1
await Moralis.unlink(address);
Copied!
Also, see the Crypto Login page for more info.

Changing Linking Message

The message the user sees when links an address to the current user can be changed by providing the signingMessage option:
1
await Moralis.link(accounts[0], { signingMessage: "Custom Linking Message" });
Copied!

ensureWeb3IsInstalled

Detect if web3 provider is activated.
Returns: True or False
1
const isWeb3Active = Moralis.ensureWeb3IsInstalled();
2
โ€‹
3
if (isWeb3Active) {
4
console.log("Activated");
5
} else {
6
await Moralis.enable();
7
}
Copied!

deactivateWeb3

Deactivates current web3 connection
1
await Moralis.enableWeb3();
2
console.log("ENABLED", Moralis.isWeb3Enabled());
3
await Moralis.deactivateWeb3();
4
console.log("DISABLED", Moralis.isWeb3Enabled());
Copied!

connector / connectorType

Returns details of the connector or the connector type, that is used to authenticate or enable web3:
1
const connectorType = Moralis.Web3.connectorType;
2
if (connectorType === "injected") {
3
console.log("Metamask or an injected provider is used");
4
}
5
โ€‹
6
const connector = Moralis.Web3.connector;
7
console.log(connector);
Copied!

chainId

Returns the current chain ID that is used to connect to web3
1
const chainId = await Moralis.chainId;
2
console.log(chainId); // 56
Copied!

account

Returns the current account that is used to connect to web3
1
const account = await Moralis.account;
2
console.log(account); // "0x...."
Copied!

switchNetwork

Function to change the current network
Note: this method can only be used, when Metamask is used as a connector

Options:

1
const chainId = "0x1"; //Ethereum Mainnet
2
const chainIdHex = await Moralis.switchNetwork(chainId);
Copied!
You can only switch to the network that is in the wallet. How to add a new network you can find below.

addNetwork

Note: this method can only be used, when Metamask is used as a connector
The function for adding a new network to the wallet. You can find the network configuration for each chain in their documentation sites.

Options:

  • chainid(required): Network Chain Id
  • chainName(required): Network name
  • currencyName(required): Name of native currency
  • currencySymbol(required): Currency Symbol
  • rpcUrl(required): New RPC URL
  • blockExplorerUrl(required): BLock Explorer URL
1
const chainId = 43114;
2
const chainName = "Avalanche Mainnet";
3
const currencyName = "AVAX";
4
const currencySymbol = "AVAX";
5
const rpcUrl = "https://api.avax.network/ext/bc/C/rpc";
6
const blockExplorerUrl = "https://cchain.explorer.avax.network/";
7
โ€‹
8
await Moralis.addNetwork(
9
chainId,
10
chainName,
11
currencyName,
12
currencySymbol,
13
rpcUrl,
14
blockExplorerUrl
15
);
Copied!