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.

Web3.js

In Browser

Similar to window.ethereum.enable() but returns a promise that resolves to a Web3 instance. Use this when you need a fully functional Web3 instance, such as for making contract calls.
1
const web3 = await Moralis.enableWeb3();
2
const contract = new web3.eth.Contract(contractAbi, contractAddress);
Copied!
If you want to use providers like WalletConnect you need to specify the provideroption
1
const web3 = await Moralis.enableWeb3({ provider: "walletconnect" });
2
const contract = new web3.eth.Contract(contractAbi, contractAddress);
Copied!
If you only need to access web3.utils without Web3 connectivity, use the following:
1
const web3 = new Moralis.Web3();
2
const amountInEth = web3.utils.fromWei(amountInWei, 'ether');
Copied!
Just beware that calls like web3.eth.getAccounts() will not work. You can re-assign the variable using Moralis.enableWeb3() later if you need full Web3 connectivity.
See the Web3.js docs for more info on the Web3 object.

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.

executeFunction

Runs a smart contract function. You can execute .call() orsend() smart contract methods.

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.
1
const ABI = [
2
{
3
constant: true,
4
inputs: [
5
{
6
internalType: "address",
7
name: "owner",
8
type: "address"
9
},
10
{
11
internalType: "address",
12
name: "spender",
13
type: "address"
14
}
15
],
16
name: "allowance",
17
outputs: [
18
{
19
internalType: "uint256",
20
name: "",
21
type: "uint256"
22
}
23
],
24
payable: false,
25
stateMutability: "view",
26
type: "function"
27
}
28
];
29
​
30
const options = {
31
contractAddress: "0xe...56",
32
functionName: "allowance",
33
abi: ABI,
34
params: {
35
owner: "0x2...45",
36
spender: "0x3...49"
37
},
38
};
39
​
40
const allowance = await Moralis.executeFunction(options);
Copied!
Requires an enabled web3 provider. Before executing the function, make sure that the correct network is selected in your wallet.
If you use WalletConnect, check Callbacks Promises Events to be able recieve tsHash, receipt and etc.
You can recieve this information without an active web3 provider using our Web3API: Moralis.Web3API.token.getAllowance()​

Example of calling a send contract method

An example of calling an ERC20 standard method approve . It sets amount as the allowance of spender over the caller’s tokens.
1
const ABI = [
2
{
3
"constant": false,
4
"inputs": [
5
{
6
"internalType": "address",
7
"name": "spender",
8
"type": "address"
9
},
10
{
11
"internalType": "uint256",
12
"name": "amount",
13
"type": "uint256"
14
}
15
],
16
"name": "approve",
17
"outputs": [
18
{
19
"internalType": "bool",
20
"name": "",
21
"type": "bool"
22
}
23
],
24
"payable": false,
25
"stateMutability": "nonpayable",
26
"type": "function"
27
},
28
];
29
​
30
const options = {
31
contractAddress: "0xe...56",
32
functionName: "approve",
33
abi: ABI,
34
params: {
35
spender: "0x2...45",
36
amount: Moralis.Units.Token("0.5", "18")
37
},
38
};
39
​
40
const receipt = await Moralis.executeFunction(options);
41
console.log(receipt)
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 receipt = await Moralis.executeFunction(options);
9
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({ functionName: 'symbol', ...options })
7
const decimals = await Moralis.executeFunction({ functionName: 'decimals', ...options })
8
const name = await Moralis.executeFunction({ functionName: 'name', ...options })
Copied!

Callbacks Promises Events

Moralis.executeFunction() supports promise events. It allows you to get info on different stages of your interaction with the blockchain.
For example, you can instantly get a transactionHash without awaitng the entire transaction has been processed. And then after the transaction is processed, you can receive a receipt
To receive all data as event callbacks, you need to switch awaitReceipt to false in your transaction options.
1
const options = {
2
contractAddress: "0xe...56",
3
functionName: "swapNativeForTokens",
4
abi: ABI,
5
msgValue: Moralis.Units.ETH("0.1"),
6
awaitReceipt: false // should be switched to false
7
};
8
​
9
const tx = await Moralis.executeFunction(options);
10
​
11
tx.on("transactionHash", (hash) => { ... })
12
.on("receipt", (receipt) => { ... })
13
.on("confirmation", (confirmationNumber, receipt) => { ... })
14
.on("error", (error) => { ... });
Copied!

Events

There are wrappers for the standard Web3 change events.
  • onConnect
  • onDisconnect
  • onChainChanged
  • onAccountsChanged
1
const unsubscribe = Moralis.onAccountsChanged(function(accounts) {
2
console.log(account);
3
});
4
// ["0x0f7056a5778b15ebd522f39ab9782abf3ee37f08"]
Copied!

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.onAccountsChanged(async function (accounts) {
2
const confirmed = confirm('Link this address to your account?');
3
if (confirmed) {
4
await Moralis.link(accounts[0]);
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!

isMetaMaskInstalled

Detect if MetaMask web3 provider is installed.
Returns: True or False
1
const isMetaMaskInstalled= await Moralis.isMetaMaskInstalled();
2
console.log(isMetaMaskInstalled)
Copied!

getChainId

Returns the current chain ID
1
const chainId = await Moralis.getChainId();
2
console.log(chainId); // 56
Copied!

switchNetwork

Function to change the current network

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

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!
​
Last modified 27d ago