简体   繁体   中英

Undefined web3.eth.getAccounts() in React Native, metamask authentication

I want to authenticate the user by his Metamask wallet. I am using web3 package in order to interact with the blocks and sign transactions. When I try to get the user accounts I get an empty result:

const Web3 = require('web3');
const web3 = new Web3(
  new Web3.providers.HttpProvider('https://api.avax.network/ext/bc/C/rpc')
);
const addresses = await web3.eth.getAccounts();

I suppose that I need to request the accounts like this await window.ethereum.request({ method: 'eth_requestAccounts'}); but it doesn't exist window mobile app.

I guess in a normal flow the user hit the auth button and will be redirected to Metamask wallet to authorize the app, how can I do this?

You are correct, but you also need to connect to MetaMask, not your own RPC. Here is your fixed code:

import detectEthereumProvider from '@metamask/detect-provider';

const web3 = await detectEthereumProvider(); // Use Metamask-injected web3
await web3.request({ method: 'eth_requestAccounts'});
const addresses = await web3.eth.getAccounts();

I found out a solution, I do not know if is the best way to do it.

In order to interact with the blocks and sign transactions the users authenticate their MetaMask wallet through WalletConnect service.

After the user is authenticated I can use the connector to create a provider in order to use it with ethers.js lib (Using web3.js the connection with RPC failed, I decided to use ethers instead):

const walletConnectProvider = new WalletConnectProvider({
    rpc: {
        43114: RPC 
    },
    chainId: 43114,
    connector: this.connector,
    qrcode: false
})
let wp = await walletConnectProvider.enable();
if(wp){
    this.provider = new providers.Web3Provider(walletConnectProvider);
}


const signer = this.provider.getSigner();
const contract = new Contract(GAMESESSION_ADDRESS, GameSession.abi, signer);
....

It is a little tricky but WalletConnect works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM