Moralis JS SDK v1.0 (migration to Ethers.js)

Ah I see what you mean. Seems like this is a difference between web3 and ethers. Web3 returns utils etc. as well in the provider. EthersJs does not do this.

You will get back a Web3Provider, so if you want to use other EthersJs functionalities, then you need to import these from EthersJs

1 Like

Ah Ok i see now, that makes sense, thanks for clarifying!

1 Like

@YosephKS : Thank you !!
yes, i was still developing under Web3js but now i want to migrate my scripts to ethersjs. I know I have to update my webpages scripts but i’m stuck on only 1 point. If i use the alias of the new Moralis SDK (>= 1.0.7):
<script src="https://unpkg.com/[email protected]/dist/moralis.js"></script>

i could not figure out how to change the code in my index main.js (it’s for Clone-Rarible-24H) :

window.web3 = await Moralis.enableWeb3();
window.tokenContract = new web3.eth.Contract(tokenContractAbi, TOKEN_CONTRACT_ADDRESS);
window.marketplaceContract = new web3.eth.Contract(marketplaceContractAbi, MARKETPLACE_CONTRACT_ADDRESS);

i have tried tons of syntax combinations regarding some tricks found on this forum + reading the ethersjs’ pages, as adviced by Erno : https://docs.ethers.io/v5/api/contract/example/

For the old web3js syntax:
new web3.eth.Contract(tokenContractAbi, TOKEN_CONTRACT_ADDRESS);

… the new syntax for ethers is:
new ethers.Contract(TOKEN_CONTRACT_ADDRESS, tokenContractAbi, providerOrSigner)

But i always finish with an error in browser console such as:
Uncaught (in promise) TypeError: ethers.Contract is not a constructor

If you could tell me how to translate the 3 first lines above, you will earn a lot of Karma points :wink:

2 Likes

Guys I have an issue with enabling web3 after the update, Can you help me to fix this?

Hey @Erno , I’m using react-moralis and useWeb3ExecuteFunction to run smart contract functions. It worked fine on version 0.3.11, but after installing the latest version v1.1.0, somehow the function stays in loading and fetching phase. Nothing changed in my code, I used the snippet from github passing the parameters in fetch function. I’m aware of migration on ether.js, I do await data.wait() to get my smart contract data, but it’s null all the time.
If you have any idea, let me know, please.
Thanks for your time and effort!

Hi, i have the same problem, event works fine some times (i can see my log of the current chain, and switch with five differents test chains), but some times no more emit (everything break, but no error)…
I call enableWeb3 in first, no problem.
After that, i call a initEvents function, that create listeners on Moralis.onChainChanged((chain) => {console.log('new chain : ’ + chain);});

There is an issue from onChainChanged event ?

Thanks in advance !

I confirm, when i use metamask events, no problem :

    //Not work everytime, when it break no more event and no error
    this.web3.getOnChainEvent((chain: string | null) => {
      console.log('Chain changed');
      console.log(chain);
      this.getNativeBalance();
    });

    // Work fine
    (window as any).ethereum.on("chainChanged", (chain: any) => {
      console.log("chain");
      console.log(chain);
    });
1 Like

I’re right, it’s Metamask. I moved from Brave to Firefox installing Metamask there to test it and it passed well. I get all my data and event, huh.
Thanks for direction in debugging. :slight_smile:

Hi I used Moralis provider and met issues below…
How can I set network as “any” in Moralis provider to avoid network changes error?

1 Like

YosephKS,
I tried again today to upgrade my project to Ethers.js, as we have the new SDK 1.1.0, but one more time my browser console returns error : it says my contracts are undefined.
The doc at https://docs.ethers.io/v5/api/contract/example/ is not solving my issue. If i tried to update the old :
new web3.eth.Contract(tokenContractAbi, TOKEN_CONTRACT_ADDRESS);
by this :
const tokenContract = new ethers.Contract(TOKEN_CONTRACT_ADDRESS, tokenContractAbi);
my console reports that ethers is not a constructor.
I tried to import the ethers CDN :
<script src="https://cdn.ethers.io/lib/ethers-5.2.umd.min.js" type="application/javascript"></script>
but the issue remains.

Any migration instructions for Cloud Code?

Do you have more info? When does this error occur?
What code dit you run, and what version are you using?

SDK v1 does not affect cloud functions

Where did you get ethers from? Did you import that library yourself?

In the latest version you can use:

const ethers = Moralis.web3Library

That will give you access to the complete ethersJs library

const web3Provider = await Moralis.enableWeb3()

Will only give you an ethers web3Provier instance.

Hope this helps, otherwise can you share your code? As I can not see how you initialise ethers from your message

1 Like

Thank you Erno !! I’m going to try.
I also discover today that the Moralis’ doc has been updated regarding the Web3 Provider. I’m going to make new tests.

1 Like

I assume you updated both moralis and react-moralis, right?
If so than it should work. Also note that read-only functions do return the data directly, without the need to use data.wait() (see https://docs.moralis.io/moralis-server/web3/web3#executefunction)

If you use a “write” function, and use moralis v1 and react-moralis v1, and still have this issue, can you then share your code-snippet?

One more thing:
in the doc article i mentioned just in my previuous post, for paragraph " Web3.js", it is stated that this code should be in the frontend index.html :
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/web3.min.js"></script>
Does it mean that if i want to use Ethers.js, i must remove this code ? Thank you for your advices.

Correct. You only need to include that code if you want to use web3.js

If you are using ethers.js, then you don’t need to include it (and you can remove it if you had it like that from before the v1 update)

1 Like
  1. I enabled Web3 with walletconnect to ethereum mainnet.
  2. Switch network to avalanche testnet.
  3. Deposit Lp
  4. Error pop up:
Error: underlying network changed (event="changed", network={"chainId":43114,"name":"unknown"}, detectedNetwork={"chainId":43113,"name":"unknown"}, code=NETWORK_ERROR, version=providers/5.5.2)
    at Logger.makeError (index.ts:225:1)
    at Web3Provider.<anonymous> (base-provider.ts:973:1)
    at Generator.next (<anonymous>)
    at fulfilled (base-provider.ts:2:1)

Enable Web3

  const connectAccount = (walletId: WalletId) => {
    let provider: MoralisType.Web3ProviderType = 'metamask'
    switch (walletId) {
      case WalletId.WALLETCONNECT:
        provider = 'walletconnect'
        break
      default:
        break
    }
    const onError = () => {
      showMessage(`Error happened on connecting to ${walletId}`, 'warning')
    }
    const onSuccess = () => {
      showMessage(`Successfully connected to ${walletId}`)
    }
    enableWeb3({ provider, onError, onSuccess })
  }


Deposit Lp

import { Contract } from 'ethers'
import { useMoralis } from 'react-moralis'
const { chainId, web3 } = useMoralis()
const handleClickSupply = async () => {
    const signer = web3.getSigner()
    const pool = new Contract(poolAddress, poolAbi, signer)
    pool.connect(signer)
    try {
      const amount = utils.parseUnits(
        depositLiquidity.token.amount,
        depositLiquidity.token.decimals,
      )
      const transaction = await pool.deposit(
        depositLiquidity.token.address,
        depositLiquidity.token.amount,
        account,
      )
      if (transaction) {
        await transaction.wait()
      }
    } catch (err) {
      console.log(err)
    }
  }
}
1 Like

@RedCabbage I encounter same error when I updated the package. What I did was to run ‘yarn install’ or do ‘npm install’ again whichever package manager you are using, and it was solved. So you can try that.