How can I use another web3 provider with React to read data from Polygon?

1.6k views Asked by At

I have this code:

import { useWeb3React, useWeb3React as useWeb3ReactCore } from '@web3-react/core';

function getSigner(library: Web3Provider, account: string): JsonRpcSigner {
    return library.getSigner(account).connectUnchecked();
}
    

function getProviderOrSigner(
    library: Web3Provider,
    account?: string,
): Web3Provider | JsonRpcSigner {
    return account ? getSigner(library, account) : library;
}    
    
function getContract(
    address: string,
    ABI: any,
    library: Web3Provider,
    account?: string,
): Contract {
    if (!isAddress(address) || address === AddressZero) {
        throw Error(`Invalid 'address' parameter '${address}'.`);
    }
        
    return new Contract(address, ABI, getProviderOrSigner(library, account) as any);
}


function useActiveWeb3React(): Web3ReactContextInterface<Web3Provider> & {
  chainId?: ChainId;
} {
  const context = useWeb3ReactCore<Web3Provider>();
  const contextNetwork = useWeb3ReactCore<Web3Provider>(NetworkContextName);
  return context.active ? context : contextNetwork;
}
        
        
function getCollectContract(library: Web3Provider, account: string, chainId: ChainId) {
    return getContract(CONTRACT_ADDRESS, CONTRACT_ABI, library, account);
}
              
function callWithActiveProvider() {
    const { library, account, chainId } = useActiveWeb3React();
    const contract: Contract | null = useMemo(() => getCollectContract(library, account, chainId), [
        library,
        account,
        chainId,
    ]);

    contract.callSomeMethod();
} 

callWithActiveProvider(); // this works

function callWithPolygonProvider() {
    const { library, account, chainId } = ???????();
    const contract: Contract | null = useMemo(() => getCollectContract(library, account, chainId), [
        library,
        account,
        chainId,
    ]);

    contract.callPolygonMethod();
}

callWithPolygonProvider() // but how do I do this?

I use callSomeMethod() with active provider, which is set up by user (most likely via metamask or wallet connect), but I would also like to call another method from another contract on Polygon, it would look something like callWithPolygonProvider(), how can I do it? It should work in the background without worrying user.

1

There are 1 answers

1
daniilorain On BEST ANSWER

I had to use another Web3ReactProvider.
https://github.com/NoahZinsmeister/web3-react/issues/485