wevm / wagmi

React Hooks for Ethereum
https://wagmi.sh
MIT License
5.79k stars 968 forks source link

How do I get the provider after the wallet is linked #4114

Closed hesiyuetian closed 3 days ago

hesiyuetian commented 4 days ago

What is the type of issue?

No response

What is the issue?

How do I get the provider after the wallet is linked, because I want to use ethers to interact with the contract

Where did you find it?

https://wagmi.sh/react/api/hooks/useConnections

LucasCodr commented 4 days ago

Hello @hesiyuetian! You can use the connector object provided by the "useAccount" hook to get the provider. Here's an example using ethers v6 in nextjs:

'use client'
import { useAccount } from 'wagmi'
import { BrowserProvider, type Eip1193Provider } from 'ethers'
import { useQuery } from '@tanstack/react-query'

export default function Page() {
  const { connector } = useAccount()

  const { data } = useQuery({
    queryKey: ['blockNumber'],
    queryFn: async () => {
      const provider = await connector?.getProvider()

      const myProvider = new BrowserProvider(provider as Eip1193Provider)

      return myProvider.getBlockNumber()
    },
    enabled: !!connector?.getProvider,
  })

  return <div>{data}</div>
}

A related question was asked here as well.

hesiyuetian commented 4 hours ago

thanks