The mystery of web3.eth.getAccounts() in the world of React Native and Metamask authentication

My goal is to authenticate the user using their Metamask wallet. To achieve this, I am utilizing the web3 package for interacting with blockchain and signing transactions. However, I am encountering an issue where attempting to retrieve user accounts results in an empty response:

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 believe that I may need to request the accounts differently, such as

await window.ethereum.request({ method: 'eth_requestAccounts'});
, but the window object does not exist in the mobile app.

In a typical scenario, the user would click an authentication button and then be redirected to their Metamask wallet to authorize the application. How can I accomplish this flow?

Answer №1

While you have the right idea, it is important to note that connecting to MetaMask is crucial instead of using your own RPC. Take a look at the updated code below:

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

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

Answer №2

After much trial and error, I stumbled upon a solution that seems to work well.

To allow users to interact with blocks and sign transactions, they must authenticate their MetaMask wallet using the WalletConnect service.

Once authentication is complete, I utilize the connector to create a provider for use with the ethers.js library (I encountered RPC connection issues with web3.js, so ethers proved to be a better alternative):

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);
....

Although it can be a bit complex, WalletConnect performs admirably in practice.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The insertMany method in Nodejs does not function properly with the Mongodb ordered option

I have integrated MongoDB into my application, specifically version 4.4.1. I made sure to set the unique option in the word field to true for data integrity. Here is the code snippet I am using: try { const words = [ { word: "her" }, ...

Tips for identifying if the function "res.end()" has been executed or not

Is there a method to determine if the res.end function has been triggered? var http = require('http'); http.createServer(function (req, res) { some_function_may_called_end(req, res); // Is there a way to check for this? if(res.is_ended = ...

Tips on personalizing the vue-filemanager interface within Laravel

I'm currently utilizing the Laravel file manager package from here, which provides a pre-compiled JS file or allows for direct use of the vue-component through npm from here. Unfortunately, in both options, the front-end is not customizable. I have i ...

Control the HTML button's state according to the information received from the server

I am currently working with datatable Jquery and using an ajax call to retrieve data from the server. Let's assume that the database consists of three attributes: "Attribute1, Attribute2, Status". Depending on the Status attribute, I need to enable or ...

Ways to customize a bot's status based on the time of day

I'm currently working on enhancing my discord bot by having its status change every hour for a more dynamic user experience. However, I'm facing challenges with JavaScript dates. Can anyone provide some guidance? Below is the snippet of code I ha ...

Is there a way to stop a <script> element's code from executing again if I modify one of its DOM parent elements?

Let's simplify the scenario at hand. On a webpage, there is a particular section of HTML structured like this: <div id="wrap-this"> <script> $(document).ready(function() { alert('Blah.'); }); ...

Dividing the ZMQ socket from the express app.js by integrating with mongodb

Currently, I am working on an Express application that is responsible for gathering data sent from a remote machine through ZMQ and then updating a MongoDB database with this information. The data updates are transmitted every 5 minutes in the form of enc ...

Is it possible for bots to mimic onTouch events?

Query: In order to safeguard a mobile website from SPAM/Bots without resorting to user-unfriendly CAPTCHA, we are considering disabling onClick events at the server side while still permitting onTouch events. Can bots emulate the onTouch function, thus e ...

Will the bootstrap carousel continue running in the background even if I hide it?

Currently, I have incorporated the twitter bootstrap carousel into my website with the following code: <div id="slider" class="carousel slide"> <!-- Wrapper for slides --> <div class="caro ...

Identifying Seating Arrangements at the Poker Table - Sit-and-Go Events

Note: The JavaScript code has been implemented based on the answer provided by ajrwhite. Hopefully, it proves helpful to someone. Link: http://codepen.io/eMineiro/pen/EKrNBe Be sure to open the CodePen console to see the examples in action. When playing ...

What method could I use to verify that my Angular 2+ login function has been invoked successfully?

Can anyone provide guidance on how to effectively verify if a function has been executed within the interaction of a component and a service? I welcome any insights or suggestions that can help me address this challenge! ...

Creating beautiful user interfaces with Material UI and React

I'm currently exploring how to integrate Material UI into my React project. After successfully installing the module, I attempted to create a custom button component. Here is my Button.js file: import React from 'react'; import FlatButton ...

A guide on incorporating multiple nested loops within a single table using Vue.js

Is it possible to loop through a multi-nested object collection while still displaying it in the same table? <table v-for="d in transaction.documents"> <tbody> <tr> <th>Document ID:</th> &l ...

How can I retrieve the Sequelize results in the form of a 2D array rather than an array of objects?

I have a situation where I am using the Sequelize query() method like this: const sequelize = new Sequelize(...); ... // IMPORTANT: Cannot modify this query const queryFromUser = "SELECT table1.colname, table2.colname FROM table1 JOIN table2 ON/*...*/ ...

Contemplating the Sequence of DOM Execution

In the world of html/javascript, the order of execution is typically serial, meaning that the browser reads the code line by line and interprets it accordingly. This is a common practice in most programming languages. Some javascript programmers prefer to ...

Delete all inputs with identical class except for one using Jquery

In the #tikersDiv div, I am looking to eliminate all input labels that have the same class except for one. Here is the script I have tried without success: $('#tikersDiv').children('label').each(function(i){ let removed = $('#id ...

Having trouble with Node.js Async/Await not returning as anticipated

Attempting to create a basic report server using node express, but encountering unexpected issues. Below is the API endpoint for generating a report: router.post('/test', async function (req, res) { return res.json(await reportService.test()); ...

Get data from ajax request in controller

I'm currently working with this JavaScript code snippet: var formData = new FormData($('#formSlip').get(0)); formData.append('myList', JSON.stringify(tests)); The variable tests holds a list of objects. I am making an AJAX PO ...

Creating Dynamic Visibility in ASP.NET Server Controls: Displaying or hiding a textbox based on a dropdown selection

Is there a way to dynamically show/hide a textbox or an entire div section based on a user's selection from a dropdown menu? Can this be achieved using client-side HTML controls instead of server controls? Would utilizing jQuery provide the best solut ...

Disappearing Into the Background Excluding Specific Divs

I have a dilemma with fading in and out a background image using jQuery fadeIn and fadeOut. The issue arises because my wrapper div contains elements such as sidebar and navigation that are positioned absolutely within the wrapper div, causing them to also ...