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
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:
Or when you use a package manager:
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.
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:
With this instance, you can use any methods from ethers.js, for example:
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:
NodeJs Enviroment
Currently this doesn't work on free plan due to Speedy Nodes removal
When using moralis in a nodejs environment, you can optionally use the privateKey
option to sign transactions:
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.
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.
You will get back a transaction response from ethers.js, that includes the hash
and other information.
Example transaction response
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:
Example receipt
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.
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
Example of creating reusable options
You can use this construction to create reusable options for calling multiple contract methods.
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 1 confirmation:
To wait for 5 confirmations:
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()
):
Result object
Moralis.onWeb3Deactivated()
Listen to events when a user disconnects to a chain (via Moralis.deactivateWeb3()
):
Result object
Moralis.onChainChanged()
Listen to events when the user changes a chain, after web3 has been enabled.
Moralis.onAccountChanged()
Listen to events when the user changes an account, after web3 has been enabled.
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.
From the specification:
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.
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.
From the specification:
The Provider emits disconnect when it becomes disconnected from all chains
To listen to these events you just need to call Moralis.onXXX
. For example:
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
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.
The unlink
function removes the given address from the user's profile.
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:
ensureWeb3IsInstalled
Detect if web3 provider is activated.
Returns: True
or False
deactivateWeb3
Deactivates current web3 connection
connector / connectorType
Returns details of the connector or the connector type, that is used to authenticate or enable web3:
chainId
Returns the current chain ID that is used to connect to web3
account
Returns the current account that is used to connect to web3
switchNetwork
Function to change the current network
Note: this method can only be used, when Metamask is used as a connector
Options:
chain
(required): The chain id to switch to. Accepts values in numbers or in hex strings. Valid values are listed on the intro page in the Transactions and Balances section. Examples:56
,"0x38"
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 IdchainName
(required): Network namecurrencyName
(required): Name of native currencycurrencySymbol
(required): Currency SymbolrpcUrl
(required): New RPC URLblockExplorerUrl
(required): BLock Explorer URL
Last updated