[SOLVED] Interacting with smart contracts

We have decided to switch to Moralis for all things web3 in our project. So far, weā€™ve been using plain ethers and web3-react. Iā€™m having difficulties interacting with smart contracts and I have read all forum posts with the same question in mind, yet all answers seem pretty unsatisfying.

After ā€œenabling web3ā€, the useMoralis hook should expose the provider, which (according to the docs) should be usable as an ethers provider to pass to a ethers Contract object. This would be ideal as we wouldnā€™t have to rewrite our code base.

  const { provider } = useMoralis();
  if (provider)
    return new ethers.Contract(
      config.address.marketRegistry,
      marketRegistryABI,
      provider
    );

Yet, the provider doesnā€™t seem to be a valid ethersjs provider. The resulting error is: ā€œError: invalid signer or provider (argument=ā€œsignerOrProviderā€, value=ā€[object Object]", code=INVALID_ARGUMENT, version=contracts/5.6.2)", as ethersjs checks for provider._isSigner/_isProvider which is not available (setting these to true gives more errors).

The docs further describe the executeFunction API which seems unnecessarily limited (or perhaps the docs are missing). Users of our dapp should be able to deploy their own smart contracts (yet the function parameter seems to be required). Furthermore we batch all call/view requests and request them in one single encoded transaction. This also doesnā€™t seem to be possible.

I guess we could simply use window.ethereum for all transaction requestsā€¦ Although Iā€™m wondering whether this covers all walletsā€¦ (which is one of the main reasons for using something like web3-react/moralis in the first place).

TLDR:
We would like to be able to send raw encoded transactions for call/view requests and deploy contracts using Moralis provider.

1 Like

This does the trick (after enabling web3)

  const { Moralis } = useMoralis();
  const provider = Moralis.web3;
  const signerOrProvider = provider?.getSigner() ?? provider;
  return new ethers.Contract(
    config.address.marketRegistry,
    marketRegistryABI,
    signerOrProvider
  );

Apparently the ethers provider is found in Moralis.web3.

2 Likes