in my react app i want to use alchemy/someother-provider RPC and i want to use metamask as singer ( window.ethereum )

how to i set that ?

my current code :

var provider = new ethers.providers.JsonRpcProvider (RPCURL); var contract = new ethers.Contract(CONTRACT_ADDRESS, NEWABI, provider); var contractsinger = new ethers.Contract(CONTRACT_ADDRESS, NEWABI, provider);

after conecting to metamask the "contractsinger" becomes :

  var providerforsinger = new ethers.providers.Web3Provider(window.ethereum, "any"); 
   signer = providerforsinger.getSigner();
   contractsinger = new ethers.Contract(CONTRACT_ADDRESS, NEWABI, signer);

1 Answer 1


Here you can try this

const getProviderOrSigner = async (needSigner = false) => {
    const web3Provider = new providers.Web3Provider(provider);

    if (needSigner) {
      const signer = web3Provider.getSigner();
      return signer;
    return web3Provider;

Here needSigner will be true or false based on data

Moreover to call the function from smart contract

const signer = await getProviderOrSigner(true);
const Contract = new Contract(
      const tx = await Contract.functionName();
  • but where i add the window.ethereum so it will use metamask as singer ?
    – heelowyou
    Mar 21 at 12:03
  • there is no need for that the above code uses metamask! just try it Mar 21 at 12:39
  • this code uses either singer or provider ... i want to use both ... for example if user read data there will be return depending on msg.sender...
    – heelowyou
    Mar 25 at 11:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.