[SOLVED] MoralisProvider with api key for useApiContract hook

Hello! I was wondering if there is a way to initialize the MoralisProvider from the react-moralis SDK using a moralis api key. It only seems to be possible using a serverUrl and appId?

I am asking that question because I want to use the useApiContract hook from the package, which currently returns Error: Web3Api not initialized, run Moralis.start() first as an error when being executed.

How can I run Moralis.start from the react-moralis package or use the MoralisProvider with an api key?

This error is most likely to occur if the web3api call runs immediately whereas moralis initialization might be delayed due to network issues.
If youโ€™re running the function in a useEffect, you can add a dependency of isInitialized from useMoralis() and check if isInitialized is true before running the function

First off thanks for your answer. However, my issue is that I want to initialize and use the MoralisProvider using an api key from the admin.moralis.io dashboard. I am not even sure how to get an appId and serverUrl from the dashboard? Is there even a way to get an appId and serverUrl from it? The dashboard only seems to be providing an api key.

You cannot initialize moralis with api key. Will suggest you check out how to self host a server [ https://docs.moralis.io/docs/v1-server-self-hosting ] prior to when Moralis will stop offering hosted servers in the future. Nonetheless, You can get one directly from this url https://admin.moralis.io/dapps.

Ok, I created a server and initialized the MoralisProvider with the right credentials.

However I run into an 400 error at the request Error: invalid type (argument="type", value="a", code=INVALID_ARGUMENT, version=abi/5.0.7) with code 141.

Seemed you are using the wrong param values for the request. Can you share how your code looks like, the abi and the values passed

Sure!

This is the NextJS code

export function XToken(lpAddress) {
    const { chainId } = useMoralis()
    const functionName = "getXTokenAddress"

    const { runContractFunction, data, error } = useApiContract({
        abi: abi,
        address: lpAddress,
        chain: chainId,
        functionName: functionName,
    })

    useEffect(() => {
        runContractFunction()
    }, [])

    error && console.log(error)

    return <div>X Token Address: {data && data}</div>
}

Here the abi for the function

[
...
{
        "type": "function",
        "name": "getXTokenAddress",
        "constant": true,
        "stateMutability": "view",
        "payable": false,
        "gas": 29000000,
        "inputs": [],
        "outputs": [{ "type": "address" }]
    },
...
]

How come you got gas in abi. It shouldnโ€™t be there

I had something wrong with my abi file. Updated it and it works now! Thank you very much for your help.