Hook a process to walletConnect

724 Views Asked by At

I've just started to use walletConnect web3Modal to handle my clients' ethereum wallet connections. Out authentication process is something like this:

  1. User connects his / her wallet to app
  2. Once the wallet is connected, A request will be sent to server to register the wallet address of the client.
  3. A User object is returned from server.

The problem is useWeb3Modal hook returns an async function called open(); Which is resolved when the modal is opened (Not when wallet is connected successfully)

Now I want to write a hook which handles this login logic for me. The problem is if client's wallet is not connected to my app, I can't request server after successful wallet connection since there's no state which defines wallet connection state.

Here's my code:

import {useAccount, useSigner} from "wagmi";
import signMessage from "@/modules/auth/services/signMessage";
import type {Signer} from "@wagmi/core";
import {useWeb3Modal} from "@web3modal/react";

const useLogin = (): () => void => {
    const {isConnected, isConnecting, isReconnecting, address} = useAccount();
    const {open} = useWeb3Modal();
    const signer = useSigner();
    return () => {
        console.log(`isConnected: ${isConnected} isConnecting: ${isConnecting} isReconnecting: ${isReconnecting} address: ${address}`)
        if (!isConnected && !isConnecting && !isReconnecting) {
            open().then(console.log);
            return;
        }

        signMessage(address as string, signer.data as Signer).then(accessToken => {
            console.log(accessToken);
        });
    };
}

export default useLogin;

And the way I use this hook is something like this:

import {Button} from "@mui/material";
import {useWeb3Modal} from "@web3modal/react";
import useLogin from "../hooks/useLogin";

const Home = (props) => {
    const login = useLogin(); //The hook I've written above
    const {open} = useWeb3Modal();

    return (
        <>
            <Button variant="contained" onClick={() => login()} disableElevation>Connect wallet</Button>
        </>
    )
}

Any ideas how to handle it?

1

There are 1 best solutions below

0
On

Actually i found a cleaner way to call a function when wallet is connected.

import {useAccount} from "wagmi";

const App = (props) => {
    const { isConnected, address } = useAccount({
        onConnect: ({ address, connector }) => console.log("Connected. address:"+address),
      });
}