React runContractFunction error codes

does this help you with react: https://github.com/ethereum-boilerplate/ethereum-boilerplate/blob/f9381a503c0af5df6d457180082c07c0040c601a/src/components/Contract/Contract.jsx#L97 ?

this also works for me in react:

const { Moralis } = useMoralis();

  const options = {
    contractAddress: "0x6c6Ae1d2eADa359c8fC8308707DeBa552f35F5C2",
    functionName: "getReputation",
    abi: [
      {
        inputs: [
          {
            internalType: "address",
            name: "_address",
            type: "address"
          },
          {
            internalType: "bytes32",
            name: "_categoryID",
            type: "bytes32"
          }
        ],
        name: "getReputation",
        outputs: [
          {
            internalType: "uint80",
            name: "",
            type: "uint80"
          }
        ],
        stateMutability: "view",
        type: "function"
      }
    ],
    params: {
      _address: "0xbA6AADA3F43521296f92cdD6730108E13b927c1c",
      _categoryID:
        "0x91f9b2a50ec6433a1cb3014d0ac426a62822c084a87e5aade80c7a9f5ce3f4e5"
    }
  };

  const x = async () => {
    await Moralis.enableWeb3();
    const b = await Moralis.executeFunction(options);
    console.log("response:", b);
  };

That one did work. Have you tried with the native useWeb3Execute function hook.

That was the one that sent me through this rabbit hole. I think it is good to report to the team that that specific hook was sending me the errors mentioned above. And as you can see, all the parameters were sent exactly in the same way. I think there is something wrong with that hook.

it looks like this syntax works fine for me too:

  const {
    data: data1,
    error: eror1,
    fetch: fetch1,
    isFetching: isFetching1,
    isLoading: isLoading1
  } = useWeb3ExecuteFunction(options);


      <button onClick={() => fetch1()} disabled={isFetching1}>
        Fetch data
      </button>
      {data1 && <pre>{data1}</pre>}

but I had to also use await Moralis.enableWeb3();

Where did you put the await Moralis.enableWeb3();

in particular I had two buttons when I tested, one button that was executing await Moralis.enableWeb3(); and another button for useWeb3ExecuteFunction

I am having the same problem with useWeb3ExecuteFunction(). The hook doesn’t seem to take chain as a parameter. How does it know which chain to execute the function on? Do I have to call enableWeb3() before using this hook? Is there any working code that successfully runs useWeb3ExecuteFunction() on non-ethereum chain? thanks

my sample code as follows:

const ERC20_ABI = [
    {
      constant: true,
      inputs: [],
      name: 'totalSupply',
      outputs: [{ name: '', type: 'uint256' }],
      payable: false,
      stateMutability: 'view',
      type: 'function'
    }
  ]

  const { data, error, fetch, isFetching, isLoading } = useWeb3ExecuteFunction({
    contractAddress: '0xe28984e1EE8D431346D32BeC9Ec800Efb643eef4'.toLowerCase(),
    abi: ERC20_ABI,
    functionName: 'totalSupply',
    params: {}
  })

  console.log(data)

If you want to run only this totalSupply function (or any other read only function), then you can use runContractFunction that doesn’t depend on local web3 instance: https://docs.moralis.io/moralis-server/web3-sdk/native#runcontractfunction

in particular useWeb3ExecuteFunction will use current web3 instance and it depends on what chain is selected there in metamask or in what wallet are you using

Hi,

I also looked at your code in this repository:

I ran the website locally. After authenticate, I can executeFunction no problem.

However, if I were to refresh the page, even though I’m still logged in, executeFunction no longer works. To make it work again, I’d have to logout then log back in.

This is the reason why I couldn’t get useWeb3ExecuteFunction to work previously. Can you please kindly take a look. It feels like a bug to me.

Thanks,

I think that you have to use something like Moralis.enableWeb3() before using executeFunction
The reason is that executeFunction uses a web3 connection to MetaMask.

But if you only want to use read only functions, you can use runContractFunction where you don’t need a web3 connection: https://docs.moralis.io/moralis-server/web3-sdk/native#runcontractfunction

1 Like

Thank you for the advice. Now I am running into another error with runContractFunction. The code is as follows.

import { useMoralisWeb3Api, useMoralisWeb3ApiCall } from "react-moralis";

const { native: { runContractFunction }, } = useMoralisWeb3Api();

const ERC20_ABI = [
    {
      constant: true,
      inputs: [],
      name: "totalSupply",
      outputs: [{ name: "", type: "uint256" }],
      payable: false,
      stateMutability: "view",
      type: "function",
    },
  ];

  const getTotalSupply = useMoralisWeb3ApiCall(runContractFunction, {
    chain: "avalanche",
    address: "0xb31f66aa3c1e785363f0875a1b74e27b85fd66c7",
    function_name: "totalSupply",
    abi: ERC20_ABI,
  });

Error message is as follows:

Argument of type ‘{ chain: “avalanche”; address: string; function_name: string; abi: { constant: boolean; inputs: never[]; name: string; outputs: { name: string; type: string; }[]; payable: boolean; stateMutability: string; type: string; }[]; }’ is not assignable to parameter of type ‘{ chain?: “avalanche” | “eth” | “0x1” | “ropsten” | “0x3” | “rinkeby” | “0x4” | “goerli” | “0x5” | “kovan” | “0x2a” | “polygon” | “0x89” | “mumbai” | “0x13881” | “bsc” | “0x38” | “bsc testnet” | “0x61” | “0xa86a” | undefined; subdomain?: string | undefined; providerUrl?: string | undefined; function_name: string; } …’. Object literal may only specify known properties, and ‘abi’ does not exist in type ‘{ chain?: “avalanche” | “eth” | “0x1” | “ropsten” | “0x3” | “rinkeby” | “0x4” | “goerli” | “0x5” | “kovan” | “0x2a” | “polygon” | “0x89” | “mumbai” | “0x13881” | “bsc” | “0x38” | “bsc testnet” | “0x61” | “0xa86a” | undefined; subdomain?: string | undefined; providerUrl?: string | undefined; function_name: string; } …’. TS2345

I am not sure why it’s complaining about the abi parameter. appreciate your help.

it looks like this works fine in vanilla JS:

ERC20_ABI = [
    {
      constant: true,
      inputs: [],
      name: "totalSupply",
      outputs: [{ name: "", type: "uint256" }],
      payable: false,
      stateMutability: "view",
      type: "function",
    },
  ];

x = await Moralis.Web3API.native.runContractFunction({
    chain: "avalanche",
    address: "0xb31f66aa3c1e785363f0875a1b74e27b85fd66c7",
    function_name: "totalSupply",
    abi: ERC20_ABI,
  })

=>
'19967027525055234432398593'

Thank you. Do you mind also showing me how to do this properly in the react-moralis framework? I find your code in this repository (https://github.com/MoralisWeb3/demo-apps/tree/main/react-moralis-examples) extremely helpful. It’ll be nice if you could add code there for using web3 api to call a read only function.

you can also use Moralis.Web3API.native directly in react.

reading that error now, it looks like something related to types, are you using simple react?

Thank you very much for still with me. I was just playing with your example project and modified the code from this file directly (https://github.com/MoralisWeb3/demo-apps/blob/main/react-moralis-examples/src/modules/Web3Api.tsx) It looks like you guys had typescript enabled for this react project. So the fact that the project is complaining about types probably implies something under the hood isn’t 100%. thank you again.

Hi, just want to check in to find out if you guys get a chance to look into why typescript is complaining about types in your demo app. thank you.

Hi @junkseeker could you please share your ready code/repo?

Hello @Yomoo,

Thanks for reaching out. I am starting from one of your demos.

git clone https://github.com/MoralisWeb3/demo-apps.git
cd demo-apps/react-moralis-examples/
yarn

server version: 0.0.288
replace src/modules/Web3Api.tsx with the following:

import React from "react";
import { Stack, Button, HStack, VStack, Divider } from "@chakra-ui/react";
import { CodeBlock } from "../components/CodeBlock";
import { useMoralisWeb3Api, useMoralisWeb3ApiCall } from "react-moralis";

export const Web3Api = () => {
  const ERC20_ABI = [
    {
      constant: true,
      inputs: [],
      name: "totalSupply",
      outputs: [{ name: "", type: "uint256" }],
      payable: false,
      stateMutability: "view",
      type: "function",
    },
  ];

  const {
    native: { runContractFunction },
  } = useMoralisWeb3Api();

  const wethAddress = "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2";

  const getTotalSupply = useMoralisWeb3ApiCall(runContractFunction, {
    chain: "eth",
    address: wethAddress,
    function_name: "totalSupply",
    abi: ERC20_ABI,
  });

  return (
    <VStack spacing={6} alignItems="stretch" divider={<Divider />}>
      <Stack spacing={3}>
        <HStack>
          <Button onClick={() => getTotalSupply.fetch()}>
            get total supply
          </Button>
        </HStack>
        <CodeBlock>{JSON.stringify(getTotalSupply, null, 2)}</CodeBlock>
      </Stack>
    </VStack>
  );
};

There’s a type check error on the following ine: “abi: ERC20_ABI,”

The code works fine if I were to skip the type check with // @ts-ignore:next-line

I am just saying it’s better to get it working 100% with type checks fully functional.

Thanks again

1 Like

I see. Thank you! We will update the types