cavanmflynn / ethers-multicall

Make multiple Ethereum network requests in a single HTTP query. ethcall for ethers v5.
MIT License
224 stars 99 forks source link

Getting: Error: underlying network changed #41

Closed FabienCoutant closed 2 years ago

FabienCoutant commented 2 years ago

Hi, I'm using ethers-multicall in my app but getting the following error on network change:

index.js?4a96:219 Uncaught (in promise) Error: underlying network changed (event="changed", network={"name":"matic","chainId":137,"ensAddress":null}, detectedNetwork={"name":"homestead","chainId":1,"ensAddress":"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"}, code=NETWORK_ERROR, version=providers/5.6.8)

I'm calling a getBalances() function in order to fetch the user's balances of multi tokens:

export const getMultipleTokenBalancesByMultiCall = async (
  tokens: Token[],
  userAddress: string,
  chainId: number,
  provider: ethers.providers.Provider
): Promise<TokenWithBalance[]> => {
  const ethCallProvider = new Provider(provider, chainId);
  const balanceCalls = tokens.map((token) => {
    if (NATIVE[chainId].equals(token)) {
      return ethCallProvider.getEthBalance(userAddress);
    }
    return getERC20Contract_MultiCall(token.address).balanceOf(userAddress);
  });
  const balances = await ethCallProvider?.all(balanceCalls);
  return tokens.map(
    (token, index) =>
      ({
        ...token,
        balance: FixBigNumber.fromWei(
          balances[index].toString(),
          token.decimals
        ),
      } as TokenWithBalance)
  );
};

The function is called like below:

export const useGetUserAssetsBalances = (assets: any): TokenWithBalance[] => {
  const { account, provider, chainId } = useWeb3React();
  const [balances, setBalances] = useState<TokenWithBalance[]>([]);
  const fetchBalances = useCallback(async () => {
    const tokens: Token[] = Object.values(assets);
    const data = (await getMultipleTokenBalancesByMultiCall(
      tokens,
      account!,
      chainId!,
      provider!,
    )) as TokenWithBalance[];

    setBalances(data);
  }, [account, provider, assets, chainId]);

  useEffect(() => {
    if (account && assets && provider && chainId) {
      fetchBalances();
    }
  }, [account, chainId, provider, assets, setBalances, fetchBalances]);
  return balances;
};

I don't have any idea on what happens here. Do someone has an idea?

FabienCoutant commented 2 years ago

It's seem that issue is link to web3React and not multicall. I closing it for now.