Web3 Provider

Web3 specific functionality of the Moralis SDK.

Lets talk about Web3 integration!

Moralis comes with a set of plugins to help you focus on your development of your app and leave the rest to us.

Moralis SDK Web3 API

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, like for making contract calls.

const web3 = await Moralis.Web3.enable();
const contract = new web3.eth.Contract(contractAbi, contractAddress);

If you just need to access web3.utils without web3 connectivity. Use the following.

const web3 = new Moralis.Web3();
const amountInEth = web3.utils.fromWei(amountInWei, 'ether');

Just beware that calls like web3.eth.getAccounts() will not work. You can re-assign the variable using Moralis.Web3.enable() 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 but the syntax is a bit different. See the Cloud Functions Web3 page for more info.

Events

There are wrappers for the standard Web3 change events.

  • onConnect

  • onDisconnect

  • onChainChanged

  • onAccountsChanged

const unsubscribe = Moralis.Web3.onAccountsChanged(function(accounts) {
console.log(account);
});
// ["0x0f7056a5778b15ebd522f39ab9782abf3ee37f08"]

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.

Moralis.Web3.onAccountsChanged(async function (accounts) {
const confirmed = confirm('Link this address to your account?');
if (confirmed) {
await Moralis.Web3.link(accounts[0]);
alert('Address added!');
}
});

The unlink function removes the given address from the user's profile.

await Moralis.Web3.unlink(address);

Also see the Crypto Login page.