2

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

0

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(
        TOKEN_ADDRESS,
        abi,
        signer
      );
      
      const tx = await Contract.functionName();
3
  • but where i add the window.ethereum so it will use metamask as singer ?
    – heelowyou
    Commented Mar 21, 2023 at 12:03
  • there is no need for that the above code uses metamask! just try it Commented Mar 21, 2023 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
    Commented Mar 25, 2023 at 11:55

Your Answer

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

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