Providing chainId on authenticate and enable web3 methods issue when using walletconnect

Greetings.
I tried following the steps explained here
https://docs.moralis.io/moralis-server/users/crypto-login#walletconnect
so that wallet connect can be used as a provider
React is being used for the front end
hereā€™s my package.json file

ā€œ@walletconnect/web3-providerā€: ā€œ^1.6.5ā€,
ā€œreact-moralisā€: ā€œ^0.2.1ā€,
ā€œmoralisā€: ā€œ^0.0.37ā€,

Hereā€™s the code where Iā€™m authenticating and then enabling web3

await this.props.authenticate({ provider: "walletconnect", chainId: 56}).then(async () => {
                    if (!this.props.authError) {
                        this.props.enableWeb3({ provider: "walletconnect", chainId: 56}).then(async () => {

I can confirm that this is working as in the QR code modal is poping up authentication is possible everything works as expected besides being able to specify the network.
Once the user has been authenticated and web3 has been enabled iā€™m doing a quick check
using this ->

    let chainIdHex = this.props.Moralis.Web3.activeWeb3Provider.web3.currentProvider.chainId;
    console.log(chainIdHex);

Which returns 1

I also checked what i had as properties in the web3 object using console.log and the rpcā€™s are there

1: "https://speedy-nodes-nyc.moralis.io/WalletConnect/eth/mainnet"
3: "https://speedy-nodes-nyc.moralis.io/WalletConnect/eth/ropsten"
4: "https://speedy-nodes-nyc.moralis.io/WalletConnect/eth/rinkeby"
5: "https://speedy-nodes-nyc.moralis.io/WalletConnect/eth/goerli"
42: "https://speedy-nodes-nyc.moralis.io/WalletConnect/eth/kovan"
56: "https://speedy-nodes-nyc.moralis.io/WalletConnect/bsc/mainnet"
97: "https://speedy-nodes-nyc.moralis.io/WalletConnect/bsc/testnet"
137: "https://speedy-nodes-nyc.moralis.io/WalletConnect/polygon/mainnet"
80001: "https://speedy-nodes-nyc.moralis.io/WalletConnect/polygon/mumbai"

However instead of using chainId 56 for bsc mainnet which was passed as option on both methods
the web3 provider is using chainId 1.

What am I missing ?
Thanks in advance and lots of regards.

1 Like

Update it will be awesome if providing the chainId works but if not I will be happy if I can switch the network afterwards The rpc method call which @Yomoo showed me in the other authenticate post i created doesnā€™t work ā€œwallet_switchEthereumChainā€ since as far as I understood itā€™s a metamask rpc call built on top of the eth rpc calls. I did try it but as as i mentioned it doesnā€™t work ;/

Iā€™ll give it a try from my side and get back to you. Thanks for the patience.

1 Like

I tried running the exact sequence of method calling and when I console logged the network Id, it shows 56.

I even kept the metamask extension open with Ethereum Main network selected as I assumed that was interfering with the network configuration but it worked fine.

Are there other instances where you called an authenticate function ? Or some other steps that we might not know?

P.S. - I used the trust wallet on my phone to scan and connect with the QR code. (for extra reference)

npm Versions used ā€“

    "react-moralis": "^0.2.1",
    "moralis": "^0.0.42",
    "@walletconnect/web3-provider": "^1.6.5",

Console logged ā€“

1 Like

Ugh this doesnā€™t make any sense at all.
Iā€™m using moralis through a hoc functions as such

hereā€™s my hoc function

import hocify from 'hocify'
import { useMoralis, useMoralisWeb3Api, useMoralisWeb3ApiCall } from "react-moralis"
import { create, all } from 'mathjs'
import { useHistory } from 'react-router-dom';

const useHocify = (props) => {
    const {history} = useHistory(); 
    const Web3Api = useMoralisWeb3Api()
    const {authenticate, logout, isAuthenticated,authError, hasAuthError,user, enableWeb3,isAuthenticating, isWeb3Enabled, Moralis, web3} = useMoralis()
    Moralis.Web3.getSigningData = () => "Welcome to App";
    return {Web3Api,history,authenticate, logout, isAuthenticated,authError, hasAuthError,user, enableWeb3, isAuthenticating, isWeb3Enabled, Moralis, web3};
};
  

const withMoralis = hocify(useHocify);
export default withMoralis

And Hereā€™s an example component where I actually use it


import React from 'react'
import { connect } from 'react-redux'
import withMoralis from "../../reusable/Hoc"

class TestComponent extends React.Component {
    constructor(props) {
      super(props);
      this.state = { hasError: false };
    }
    componentDidMount(){
   
    }
    componentDidUpdate(prevProps) {

      }
    componentWillUnmount(){
    }

    static getDerivedStateFromError(error) {
        // Update state so the next render will show the fallback UI.
        return { hasError: true };
    }

    componentDidCatch(error, info) {
      console.log(error);
      console.log(info);
    }
render() {
        if (this.state.hasError) {
          // You can render any custom fallback UI
          return <h1>Something went wrong.</h1>;
        }else{
          return (
            <>
            {this.props.isAuthenticated && this.props.isWeb3Enabled  ? <>
<div><p>logged in </p></div>
</> : <>
<div><p>Not logged in </p></div>
<div><p onClick={async ()=>{
await this.props.authenticate({ provider: "walletconnect", chainId: 56}).then(async () => {
    if (!this.props.authError) {
        this.props.enableWeb3({ provider: "walletconnect", chainId: 56}).then(async () => {
            console.log ("enabled web3 bruh...");
        });
    } else {
        console.log("Login Failed: " +this.props.authError.message);
    }
});
}}>Test</p></div>
</> })
 }
}


const mapStateToProps = state => ({
  loginModalVisibility: state.loginModalVisibility,
  sesionCreated: state.sesionCreated
});

const mapDispatchToProps = (dispatch,ownProps) => {
  return {
    toggleAlert: (_title,_message)=>{
      dispatch({type: 'set', alertVisibility: true})
    },
    toggleModal: ()=>{
      dispatch({type: 'set', loginModalVisibility: true})
    }
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(withMoralis(TestComponent))

This is really really odd everything else works.
Normal metamask auth plus web3 enablement -> Check
Cloud functions Web3Api and all other fancy functionalities -> Check
Web3 call and send requests via smart contract works -> Check

Authentication via wallet connect works I tested it using my phone before even posting this thread using the Trust Wallet App.
It connects just fine however it can connect only to the Ethereum network.
It says
Connected Today, 1:40",
Address MainWallet(0x27401ā€¦C0780f4)
Network. Ethereum

I did authenticate using https://app.1inch.io/ and the Network value do changes to ā€œSmart Chainā€ which is the Binance Smart Chain Mainnet

Iā€™m honestly lost and would appreciate any ideas.
No thereā€™s no other authenticate calls which get invoked before this or after this.

If the example above doesnā€™t resolve this @malik is it possible to hop on a discord call regarding this ?

Can I run your code once without redux and test it? Iā€™ll get back to you with my findings.

Alright, I think I found the issue. It is a bug in the SDK code.
To make your functionality work, use this in the mean time ā€“

import hocify from 'hocify'
import { useMoralis, useMoralisWeb3Api, useMoralisWeb3ApiCall } from "react-moralis"
import { create, all } from 'mathjs'
import { useHistory } from 'react-router-dom';

const useHocify = (props) => {
    const {history} = useHistory(); 
    const Web3Api = useMoralisWeb3Api()
    const {authenticate, logout, isAuthenticated,authError, hasAuthError,user, enableWeb3,isAuthenticating, isWeb3Enabled, Moralis, web3} = useMoralis()
    Moralis.Web3.getSigningData = () => "Welcome to App";
//MADE CHANGE HERE
const authenticateWorking = Moralis.Web3.authenticate; 
    return {Web3Api,history,authenticateWorking, logout, isAuthenticated,authError, hasAuthError,user, enableWeb3, isAuthenticating, isWeb3Enabled, Moralis, web3};
};
  
const withMoralis = hocify(useHocify);
export default withMoralis
import React from 'react'
import { connect } from 'react-redux'
import withMoralis from "../../reusable/Hoc"

class TestComponent extends React.Component {
    constructor(props) {
      super(props);
      this.state = { hasError: false };
    }
    componentDidMount(){
   
    }
    componentDidUpdate(prevProps) {

      }
    componentWillUnmount(){
    }

    static getDerivedStateFromError(error) {
        // Update state so the next render will show the fallback UI.
        return { hasError: true };
    }

    componentDidCatch(error, info) {
      console.log(error);
      console.log(info);
    }
render() {
        if (this.state.hasError) {
          // You can render any custom fallback UI
          return <h1>Something went wrong.</h1>;
        }else{
          return (
            <>
            {this.props.isAuthenticated && this.props.isWeb3Enabled  ? <>
<div><p>logged in </p></div>
</> : <>
<div><p>Not logged in </p></div>
<div><p onClick={async ()=>{
//MADE CHANGE HERE
await this.props.authenticateWorking({ provider: "walletconnect", chainId: 56}).then(async () => {
    if (!this.props.authError) {
        this.props.enableWeb3({ provider: "walletconnect", chainId: 56}).then(async () => {
            console.log ("enabled web3 bruh...");
        });
    } else {
        console.log("Login Failed: " +this.props.authError.message);
    }
});
}}>Test</p></div>
</> })
 }
}


const mapStateToProps = state => ({
  loginModalVisibility: state.loginModalVisibility,
  sesionCreated: state.sesionCreated
});

const mapDispatchToProps = (dispatch,ownProps) => {
  return {
    toggleAlert: (_title,_message)=>{
      dispatch({type: 'set', alertVisibility: true})
    },
    toggleModal: ()=>{
      dispatch({type: 'set', loginModalVisibility: true})
    }
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(withMoralis(TestComponent))

I will let our developers know regarding the issue. Thank you for letting us know. :slight_smile:

1 Like

Can you check if it works with react-moralis 0.2.2?
Should be fixed in the latest release :slight_smile:

1 Like

@Erno @malik
Issue has been fixed on 0.2.2 thanks.
I also saw a few threads regarding the Signing Message
I can confirm that itā€™s working for me using the react moralis npm package.

3 Likes

Hello,
I have the same issue with react-moralis v. 0.3.11
This is my code:

import { useMoralis } from "react-moralis";

...

const { authenticate, enableWeb3, web3 } = useMoralis();

...

authenticate({ provider: "walletconnect", chainId: 1, onSuccess: () => {
                                enableWeb3({ provider: "walletconnect", chainId: 1, onSuccess: () => {
                                    console.log(web3.currentProvider.chainId)
                                }  })
                            } });

If the I authenticate via Metamask with another chain instead of 1 (ETH Mainnet) the software will print another number, so instead of using chainId 1 for eth mainnet it using another one

what you get if you use: chain_id = await web3.eth.getChainId() console.log(chain_id) ?

chain_id is 4
I logged in with rinkeby

In Network section i can see that moralis is querying ā€œhttps://speedy-nodes-nyc.moralis.io/WalletConnect/eth/rinkebyā€

how do you choose the chain in MetaMask for authentication?

Iā€™m using metamask app for the authentication, scanning the qr code
I choose the chain at the top of the app, on the homepage

is there a default chain selected before choosing the chain that you want to choose?

when I open the app is selected as default the last chain I used
Then I switch to a random chain different from the eth mainnet (to test the moralis login), log in and then I can see that Moralis handle the chain that I selected on the Metamask app and not the one I set in code

login/authentication would work with any chain, it doesnā€™t matter what chain you choose, but if you select intentionally a chain, then that is the chain that the application would use, the application it can not force MetaMask to use only a specific chain.

you can later check what chain is used in your application and ask the user to select a specific chain.

there are wallets that donā€™t even have the option to choose a chain, like trustwallet.

1 Like

I have one last question, do you know why my software after the first connection via walletconnect queries this endpoint almost every second: ā€œhttps://speedy-nodes-nyc.moralis.io/WalletConnect/eth/mainnetā€ ?

Itā€™s normal? even if I log out it keeps querying, and if I log out and connect to another chain, it will query both chains, for example mainnet and rynkeby
is there any way to at least stop it when i log out?

Thank you

it looks like walletconnect could make one request per second with eth_getBlockByNumber, it looks like there is the option to use disconnect: await provider.disconnect()

and also it may be an pollinInterval option that you could try to test