Use two providers at the same time (one Ethereum, other — Polygon)

551 views Asked by At

I'd like to use two providers at the same time, one is Web3Proivder, which I get through Metamask connection, and it works fine. I'm stuck at setting up provider for Polygon right now. I want to read data from storage from Polygon contracts, how do I do that?

This is the code that works:

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

    contract.callSomeMethod();
} 

callWithActiveProvider(); // this works

This does not:

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?

This is the functions/imports that are used above:

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);
}

The hardest part is that both of them should work at the same time, so user can make a transaction on Ethereum, and we should be able to make a request to read storage from Polygon contract in the background.

1

There are 1 answers

0
pguardiario On

You probably want a 2nd web3 with a polygon https url from infura:

const Web3 = require('web3')
const polygonWeb3 = new Web3(new Web3.providers.HttpProvider(infuraUrl))