Code Monkey home page Code Monkey logo

Comments (12)

YessineAmor avatar YessineAmor commented on July 29, 2024 1

How to configure usewalletprovider flexibly? Do you have to pass in fixed chainid and connectors configuration at present?

I created a Context to hold the chainId, passed its value to the chainId prop in UseWalletProvider and updated the context value everytime the network changed

from use-wallet.

supermars01 avatar supermars01 commented on July 29, 2024

Or how to monitor the 'network changed' event
1610596753(1)

from use-wallet.

linxux avatar linxux commented on July 29, 2024

You can refer to we3-react/example - useInactiveListener

from use-wallet.

supermars01 avatar supermars01 commented on July 29, 2024

You can refer to we3-react/example - useInactiveListener

thank you!

from use-wallet.

cosmin-negoita avatar cosmin-negoita commented on July 29, 2024

@linxux How is it supposed to be used? I can't find any info on that and I would really appreciate some help!

from use-wallet.

linxux avatar linxux commented on July 29, 2024

@linxux How is it supposed to be used? I can't find any info on that and I would really appreciate some help!

  1. For multiple network supported in use-wallet, you can refer to @YessineAmor mentioned.

  2. For switching multiple networks, here are the code snippets.

const useInactiveListener = (suppress: boolean = false) => {
  const { status, error, account } = useWallet()
  const { login } = useAuth()

  useEffect((): any => {
    const { ethereum } = window as any
    if (ethereum && ethereum.on && !suppress) {
      ...
      const handleChainChanged = (chainId: string | number) => {
        console.log("Handling 'chainChanged' event with payload", chainId)
        if (supportedChainId(chainId)) {
          const connetorId = getConnectorId()
          login(connetorId)
        }
      }
      ...
    }
  }
}

const useAuth = (): { login: (connectorId: keyof Connectors | undefined) => void; logout: () => void } => {
  const { error, connect, reset, connector } = useWallet()
  
  useEffect(() => {
    if (!error) return
    if (error instanceof ChainUnsupportedError) {
      const chainId = getTargetChainId() // get the target chainId from Context or any other storages
      
      // call `wallet_addEthereumChain` or `wallet_switchEthereumChain` as you need
      // see [EIP-3085: Wallet Add Ethereum Chain RPC Method (`wallet_addEthereumChain`)](https://eips.ethereum.org/EIPS/eip-3085)
      // and [EIP-3326: wallet_switchEthereumChain](https://ethereum-magicians.org/t/eip-3326-wallet-switchethereumchain/5471)
      chainId && setupChainNetworkByChainId(chainId).then((hasSetup) => {
        if (hasSetup) {
          login(connector)
        }
      })
    }
  }, [error])

  const login = useCallback(async (connectorId: keyof Connectors | undefined) => {
    await connect(connectorId)
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  
  const logout = useCallback(() => {
    reset()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  
  return { login, logout }
}

from use-wallet.

cosmin-negoita avatar cosmin-negoita commented on July 29, 2024

@linxux Thank you, I think @YessineAmor answer was straight forward, but I couldn't figure out how to retrieve the chainId so I can pass it to the UseWalletProvider. My app will only support ETH and BSC, so I thought I could try to connect to ETH, and if the wallet status returns error, I could retry on BSC. What do you think?

from use-wallet.

linxux avatar linxux commented on July 29, 2024

Hi @cosmin-negoita , assume your Dapp has the network switcher for ETH/BSC.
when the user chooses the network, then your Dapp could update the chainId in context (ReactContext/Localstorage...).
Then you can,

  1. wrapper the UseWalletProvider into your customized provider, and retrieve the chainId from context
  2. or get the the chainId from localstorage after page reload due to the network changed

from use-wallet.

supermars01 avatar supermars01 commented on July 29, 2024

How to configure usewalletprovider flexibly? Do you have to pass in fixed chainid and connectors configuration at present?

I created a Context to hold the chainId, passed its value to the chainId prop in UseWalletProvider and updated the context value everytime the network changed

but how do you determine chainid when you connect with Walletconnect

from use-wallet.

YessineAmor avatar YessineAmor commented on July 29, 2024

from use-wallet.

ladyruo avatar ladyruo commented on July 29, 2024
//@ts-nocheck
import { useCallback, useEffect, useState } from 'react';

const useChainId = () => {
  const [chainId, setChainId] = useState(97);

  const fetchChainId = useCallback(async () => {
    if (window.ethereum) {
      const ethereum = window.ethereum;
      let chainId = await ethereum.request({
        method: 'eth_chainId',
      });
      chainId = parseInt(chainId, 16);
      setChainId(chainId);

      window.ethereum.on('networkChanged', function (chainId) {
        chainId = parseInt(chainId, 16);
        setChainId(chainId);
      });
    }
  }, []);

  useEffect(() => {
    fetchChainId().catch((err) => console.error(err.stack));

    const refreshChainId = setInterval(fetchChainId, 1000);
    return () => clearInterval(refreshChainId);
  }, []);

  return chainId;
};

export default useChainId;

const UseWalletProviderWrapper = (props) => {
  const chainId = useChainId();
  console.log("🚀 ~ file: App.tsx ~ line 35 ~ UseWalletProviderWrapper ~ chainId", chainId)

  return <UseWalletProvider chainId={chainId} {...props}></UseWalletProvider>;
}

from use-wallet.

BitWonka avatar BitWonka commented on July 29, 2024

@ladyruo thanks a lot for that, had to slightly modify it to fix a memory leak in the interval though

import { useCallback, useEffect, useState } from "react";

const useChainId = () => {
  const [chainId, setChainId] = useState(97);

  const fetchChainId = useCallback(async () => {
    if (window.ethereum) {
      const ethereum = window.ethereum;
      let chainId = await ethereum.request({
        method: "eth_chainId",
      });
      chainId = parseInt(chainId, 16);
      console.log("network changed");
      setChainId(chainId);
    }
  }, [setChainId]);

  useEffect(() => {
    fetchChainId().catch((err) => console.error(err.stack));\

    window.ethereum.on("networkChanged", fetchChainId);
    return () => window.ethereum.removeListener("networkChanged", fetchChainId);
  }, [fetchChainId]);

  return chainId;
};

export default useChainId;
const UseWalletProviderWrapper = (props) => {
  const chainId = useChainId();
  console.log("🚀 ~ file: App.tsx ~ line 35 ~ UseWalletProviderWrapper ~ chainId", chainId)

  return <UseWalletProvider chainId={chainId} {...props}></UseWalletProvider>;
}

from use-wallet.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.