Metamask React SDK

Hi I’m using MetaMask javascript sdk in my react project https://docs.metamask.io/wallet/how-to/use-sdk/javascript/react/
And the reason why we used this was as if someone will open our link on the browser then to redirect him to MetaMask app and then get redirected to our link if connection is successful and get the account address, chain id and wallet balance. But right now I’m not able to get the balance info. I’m using the below piece of code for getting the balance.

await window.ethereum
        .request({
          method: "eth_getBalance",
          params: [wallet.accounts[0], "latest"],
        })
        .then((res: any) => {
          console.log("res", res);
        })
        .catch((e: any) => console.log("request accounts ERR", e));

Please help here.

2 Likes

Hello @abhisr4 !
Welcome to MetaMask community !

What is the res object in the then block?
Or is the result caught by the catch block?
In this case, it is interesting what the object e is equal to.

Can you upload a simplified version of your application to github so that it can be deployed and tested?

1 Like

Hi @snwlprd.eth,
In our application when we are getting redirected from metamask app to mobile browser then this function isn’t doing anything. Neither it is going to then nor catch . But if we are adding any logs before this await those are showing only this await part is not giving us anything.,

1 Like

@abhisr4

Does this work well in a browser with the MetaMask wallet extension?

Try the following function to connect, without await:

 const connect = () => {
    window.ethereum
      .request({
        method: "eth_requestAccounts",
        params: [],
      })
      .then((res) => console.log("request accounts", res))
      .catch((e) => console.log("request accounts ERR", e));
  };
3 Likes

This part is working fine, it’s just that after connecting to the wallet the app is redirecting to the mobile browser and thus the below function which helps us to get balance is not working

  // useCallback ensures that we don't uselessly re-create the _updateWallet function on every render
  const _updateWallet = useCallback(async (providedAccounts?: any) => {
    // await window.ethereum.enable();

    try {
      if (typeof window.ethereum !== "undefined") {
        console.log("inside");

        const accounts =
          providedAccounts ||
          (await window.ethereum.request({ method: "eth_accounts" }));

        console.log("after account", accounts);

        console.log("accounts.length", accounts.length);
        if (accounts.length === 0) {
          // If there are no accounts, then the user is disconnected
          setWallet(disconnectedState);
          return;
        }

// from here this part is not working after redirecting to mobile browser
        let balance = await window.ethereum.request({
          method: "eth_getBalance",
          params: [accounts[0], "latest"],
        });

        if (typeof balance !== "undefined") {
          balance = formatBalance(balance as string);
        } else {
          throw new Error("Balance is undefined");
        }

        console.log("after balance", balance);

        const chainId = await window.ethereum.request({
          method: "eth_chainId",
        });

        console.log("after chain", chainId);

        // Gari balance
        let encoded = new ethers.AbiCoder().encode(["address"], [accounts[0]]);
        const erc20Bal = await window.ethereum.request({
          method: "eth_call",
          params: [
            {
              to: tokenAddresses.gari,
              data: ERC20_FUNCTION.balance + encoded.slice(2),
            },
          ],
        });

        let gari;
        if (typeof erc20Bal !== "undefined") {
          gari = formatBalance(erc20Bal as string, 9);
        } else {
          throw new Error("erc20Bal is undefined");
        }

        console.log("after gari", gari);

        // Staking Info
        encoded = new ethers.AbiCoder().encode(["address"], [accounts[0]]);
        const stakeData = await window.ethereum.request({
          method: "eth_call",
          params: [
            {
              to: tokenAddresses.staking,
              data: STAKING_FUNCTION.info + encoded.slice(2),
            },
          ],
        });

        console.log("after stake", stakeData);

        let stakedAmount;
        let lastStaked;
        let reward;
        if (typeof stakeData !== "undefined" && stakeData !== null) {
          //stake amount
          stakedAmount = formatBalance(
            "0x" + (stakeData as string).substring(2, 66),
            9
          );

          // last stake date
          lastStaked = new Date(
            parseInt((stakeData as string).substring(67, 130), 16) * 1000
          ).toDateString();

          // pending rewards
          reward = formatBalance(
            "0x" + (stakeData as string).substring(131, 194),
            9
          );
        } else {
          throw new Error("stakeData is undefined");
        }

        // Allowance Info
        // const allowanceData = await window.ethereum.request({
        //   method: "eth_call",
        //   params: [
        //     {
        //       to: tokenAddresses.gari,
        //       data: ERC20_FUNCTION.allowance + encoded.slice(2),
        //     },
        //   ],
        // });

        // const allowance = formatBalance(allowanceData, 9);

        setWallet({
          accounts,
          balance: balance as string, // Type assertion
          gari,
          allowance: "",
          stakedAmount,
          lastStaked,
          reward,
          chainId: chainId as string, // Type assertion
        });
      }
    } catch (error) {
      console.log(error);
    }
  }, []);
1 Like

@abhisr4

What version of the MetaMask/sdk library are you using? 0.4.2 or 0.5.0 ?
What mobile device was this tested on ?
Show code with MetaMask sdk connection and options object.

If you’re worried about performance and extra renders you should use useMemo to capture the provider object and you could try doing it via web3js:

import { MetaMaskSDK } from '@metamask/sdk';
import Web3 from "web3";
const sdk = new MetaMaskSDK({
  enableDebug: true,
  autoConnect: {
    enable: true
  },
  dappMetadata: {
    url: window.location.href,
    name: document.title,
  },
  logging: {
    developerMode: true,
  },
  storage: {
    enabled: true,
  }
});

const ethereum = sdk.getProvider();

if (ethereum) {
      const web3 = new Web3(ethereum);
      setStateApiWeb3(web3);
    }
2 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.