Comments (12)
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.
Or how to monitor the 'network changed' event
from use-wallet.
You can refer to we3-react/example - useInactiveListener
from use-wallet.
You can refer to we3-react/example - useInactiveListener
thank you!
from use-wallet.
@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 How is it supposed to be used? I can't find any info on that and I would really appreciate some help!
-
For multiple network supported in
use-wallet
, you can refer to @YessineAmor mentioned. -
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.
@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.
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,
- wrapper the
UseWalletProvider
into your customized provider, and retrieve thechainId
from context - or get the the
chainId
fromlocalstorage
after page reload due to the network changed
from use-wallet.
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.
from use-wallet.
//@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.
@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)
- [security] Possible issue HOT 1
- Support Frameworks Other Than React HOT 1
- Unexpected character - dist/esm/Cipher.png HOT 1
- Next.js - SyntaxError: Invalid or unexpected token HOT 8
- Hardhat - Uncaught ChainUnknownError: Unknown chain id: 31337
- wallet.chainId defaulting to 1
- support chain do not in the chains list HOT 3
- autoConnect property has bugs!
- useWallet() sometimes return null account value in it's object HOT 1
- Files changed
- explorerUrl inconsistencies
- New use-wallet supporter HOT 8
- Doesn't support React18?
- Throwing error `ChainUnknownError` makes the app crashes
- Add Sepolia as a supported testnet for Ethereum HOT 2
- How does walletconnect use V2 HOT 3
- Unknown chain id: 8453 HOT 1
- ConnectorWalletConnectV2.ts WalletConnect is not a constructor
- When using walletconnectV2, an error is reported HOT 4
- Add Amoy as a supported testnet for Polygon HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from use-wallet.