我正在使用 web3modal
import { useWeb3Modal } from "@web3modal/react";
const foo = () => {
const { open, close } = useWeb3Modal();
async function connect_wallet() {
try {
await open(); // Open the web3modal provider selection modal
console.log("web3 and provider")
// provider
} catch (error) {
console.error("Error connecting to provider:", error);
}
}
return(
<div>
<button onClick={connect_wallet}>
Connect Wallet
</button>
</div>
)
}
因此 web3modal 会正常弹出并连接,但是如何从中获取提供程序和 web3 的值?
您可以按照以下方式尝试。
import Web3Modal from "web3modal";
...
const provider = await web3Modal.connect();
console.log("Provider:", provider);
好吧,有一点背景知识,我需要处理一个项目,只是为了意识到 @web3mnodal 库发生了很多变化,我在尝试从
open
方法获取连接的提供程序时感到沮丧,但未能成功.
现在,在设置 web3modal 时,我选择了 web3modal+wagmi 设置(而不是 ethers 设置),原因是我的大部分 ethers 代码都使用 v6,而 web3modal ether 版本停留在 v5(这意味着我有将我的代码库切换回 5),wagmi 设置的好处是它以某种方式连接到 web3modal。
我从
wagmi
库导入了一些钩子,即
import {useAccount, useWalletClient} from 'wagmi'
useAccount 挂钩为您提供帐户的状态,例如地址、当前连接器(如果已连接,则为 null)、连接状态和
connecting
状态(如果当前正在连接)
const { address, isConnected, connector, isConnecting, isDisconnected, isReconnecting, status } = useAccount()
另一方面,useWalletClient 获取实际的连接器/walletCient(这就是您所需要的,因为与从 useAccount 挂钩获得的连接器不同,它具有更多信息,您可以执行
connector.getWalletClient()
tho)
这是简单的部分,困难的部分是尝试将连接器/walletCliend 转换为以太坊提供者和/或签名者,我必须为此创建一个辅助函数。
代码看起来像这个示例
import { useWeb3Modal } from "@web3modal/wagmi/react";
import { useEffect } from "react";
import { ethers } from "ethers";
import { WalletClient } from "viem";
import { useAccount, useWalletClient } from "wagmi";
const clientToProviderSigner = async (client: WalletClient) => {
const { account, chain, transport } = client;
const network = {
chainId: chain?.id,
name: chain?.name,
ensAddress: chain?.contracts?.ensRegistry?.address,
};
// You can use whatever provider that fits your need here.
const provider = new ethers.BrowserProvider(transport, network);
const signer = await provider.getSigner(account?.address);
return { provider, signer };
};
const App = () => {
const { open } = useWeb3Modal()
const { isConnected } = useAccount()
const { data: walletClient } = useWalletClient();
// This is to update ya state/redux store
const connectWallet = async () => {
if (!walletClient) return;
const { signer, provider } = await clientToProviderSigner(walletClient)
// Do whatever you want with the provider and signer like storing them in a state or context
};
useEffect(() => {
// Only open modal if the user isn't connected
!isConnected && open()
}, [])
useEffect(() => {
// Finally we only want to get a provider if the user is connected(from the modal) AND there's a wallet client
isConnected && walletClient && connectWallet();
}, [isConnected, walletClient])
}
export default App
希望这有帮助。