3

I am developing react native mobile application where user can connect their crypto wallet(MetaMask, Rainbow, etc.) to mobile application. Everything is working well. I have used this (@walletconnect/react-native-dapp) react-native package to achieve this requirement.

After connected the external wallet (MetaMask), later I have to do some transaction by my app.

To do transaction I have to get know which network currently set in MetaMask wallet.

Is there any way to know the current connected network(chainId)to Metamask by this react-native package.

To do the transaction I am using this code.

try {
  let dataa = await contract.methods
    .transfer(toAddress, value.toString())
    .encodeABI();
  let txObj = {
    // gas: Web3js.utils.toHex(100000),
    data: Web3js.utils.toHex(dataa),
    from: userWallet,
    to: POZ_TOKEN, // Contractor token address
  };
  try {
    const transactionHash = await connector
      .sendTransaction(txObj)
      .catch((_err: any) => {
        Toast.show({
          autoHide: true,
          text1: t('topUpPoz.transactionFailed'),
          type: 'error',
        });
      });
    console.log('transactionHash is =', transactionHash);

Please suggest me anyone.

Pankaj Sonava
  • 519
  • 4
  • 20

1 Answers1

0

With @walletconnect/react-native-dapp we can fetch chain ID using connector, sample code is given below.

Note: checkNetworkIdHandler is a custom user defined function to check chainId connected is valid or not.

 import {useWalletConnect} from '@walletconnect/react-native-dapp';  
 
  //creating a wallet connect connector
  const connector = useWalletConnect();

  const connectExternalWallet = React.useCallback(() => {
    return connector.connect();
  }, [connector]);


//below code snippet to be called on wallet connect button click
async function connectWallet(){
  try {
        let connection = await connectExternalWallet();
        let networkStatus = checkNetworkIdHandler(connection.chainId);
  }catch (exception) {
        console.log("Exception occurred while connecting to metamask");
  }
}
Vineeta
  • 85
  • 1
  • 11
  • Yeah, this is okay when we get chainID after connected to wallet. What happened if I changed the network in external wallet after connected in my app. Will this method provide updated chainId ? – Pankaj Sonava Jan 21 '23 at 07:12