Skip to main content
edited title
Link

What is the correct way to deploy a React app that uses Ethers.jsMetaMask?

Source Link

What is the correct way to deploy a React app that uses Ethers.js?

I am learning hardhat and ethers, so I made a create-react-app to interact with contracts on rinkeby. The react app works fine locally, but when I deploy it to Surge, I get an error and can't access the contracts anymore. I am not sure if this is because of ethers or the provider that metamask gives to ethers.

Here is the code that sets up the provider and signer by going through metamask:

  useEffect(() => {
    const init = async () => {
      const provider = await detectEthereumProvider();
      if (provider) {
        startApp(provider);
      } else {
        alert('Please install MetaMask!');
        setIsLoading(false);
        return;
      };

      async function startApp(provider) {
        if (provider !== window.ethereum) {
          alert('Do you have multiple wallets installed?');
          setIsLoading(false);
          return;
        };

        const ethersProvider = new ethers.providers.Web3Provider(provider);
        const signer = ethersProvider.getSigner();

        let signerAddress = await signer.getAddress();
        setCurrentMetaMaskAccount(signerAddress);

        const _myToken = new ethers.Contract(
          myTokenContractAddress.MyToken,
          MyToken.abi,
          signer
        );
        setMyToken(_myToken);

        const _faucet = new ethers.Contract(
          faucetContractAddress.Faucet,
          Faucet.abi,
          signer
        );
        setFaucet(_faucet);
      };
    };
    init();
  }, []);

The deployed React app produces this error:

Uncaught (in promise) Error: unknown account #0 (operation="getAddress", code=UNSUPPORTED_OPERATION, version=providers/5.1.2)

I have followed the Ether.js documentation for working with metamask:

const provider = new ethers.providers.Web3Provider(window.ethereum)
const signer = provider.getSigner()

What should I do to set up ethers.js and metamask so they work on a deployed react app?