# Table of Contents - [Getting Started – @wagmi/core](#getting-started-wagmi-core) - [Getting Started – wagmi](#getting-started-wagmi) - [wagmi: React Hooks for Ethereum – wagmi](#wagmi-react-hooks-for-ethereum-wagmi) - [wagmi Blog – wagmi](#wagmi-blog-wagmi) - [Getting Started – @wagmi/cli](#getting-started-wagmi-cli) - [TypeScript – @wagmi/core](#typescript-wagmi-core) - [Connect Wallet Example – wagmi](#connect-wallet-example-wagmi) - [Chains – @wagmi/core](#chains-wagmi-core) - [Config – @wagmi/core](#config-wagmi-core) - [Migration Guide – @wagmi/core](#migration-guide-wagmi-core) - [Configuring Chains – @wagmi/core](#configuring-chains-wagmi-core) - [Alchemy – @wagmi/core](#alchemy-wagmi-core) - [Infura – @wagmi/core](#infura-wagmi-core) - [Public – @wagmi/core](#public-wagmi-core) - [JSON RPC – @wagmi/core](#json-rpc-wagmi-core) - [Injected – @wagmi/core](#injected-wagmi-core) - [Coinbase Wallet – @wagmi/core](#coinbase-wallet-wagmi-core) - [MetaMask – @wagmi/core](#metamask-wagmi-core) - [Mock – @wagmi/core](#mock-wagmi-core) - [Safe Wallet – @wagmi/core](#safe-wallet-wagmi-core) - [WalletConnect – @wagmi/core](#walletconnect-wagmi-core) - [WalletConnectLegacy – @wagmi/core](#walletconnectlegacy-wagmi-core) - [disconnect – @wagmi/core](#disconnect-wagmi-core) - [connect – @wagmi/core](#connect-wagmi-core) - [fetchBalance – @wagmi/core](#fetchbalance-wagmi-core) - [fetchBlockNumber – @wagmi/core](#fetchblocknumber-wagmi-core) - [fetchEnsAddress – @wagmi/core](#fetchensaddress-wagmi-core) - [Library Comparison – wagmi](#library-comparison-wagmi) - [fetchEnsAvatar – @wagmi/core](#fetchensavatar-wagmi-core) - [fetchEnsName – @wagmi/core](#fetchensname-wagmi-core) - [fetchEnsResolver – @wagmi/core](#fetchensresolver-wagmi-core) - [Config – wagmi](#config-wagmi) - [Config Options – @wagmi/cli](#config-options-wagmi-cli) - [fetchFeeData – @wagmi/core](#fetchfeedata-wagmi-core) --- # Getting Started – @wagmi/core On This Page * [Installation](#installation) * [Configure chains](#configure-chains) * [Create a wagmi config](#create-a-wagmi-config) * [You're good to go!](#youre-good-to-go) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9CGetting%20Started%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/core/getting-started.en-US.mdx) * Core * Getting Started Getting Started =============== `@wagmi/core` is a VanillaJS library containing everything you need to start working with Ethereum. It makes it easy to "Connect Wallet," display ENS and balance information, sign messages, interact with contracts, and much more. If you are wanting to use `@wagmi/core` with `wagmi` in React, please refer to the [Actions](https://wagmi.sh/react/actions) section. Installation[](#installation) ------------------------------ Install `@wagmi/core` and its [viem](https://viem.sh) peer dependency. npmpnpmyarn npm i @wagmi/core viem Configure chains[](#configure-chains) -------------------------------------- First, configure your desired chains to be used by wagmi, and the providers you want to use. import { configureChains, mainnet } from '@wagmi/core' import { publicProvider } from '@wagmi/core/providers/public' const { chains, publicClient, webSocketPublicClient } = configureChains( [mainnet], [publicProvider()], ) This example uses the Ethereum Mainnet chain (`mainnet`) from `@wagmi/core`, however, you can also pass in any [EVM-compatible chain](/core/chains#wagmichains) . Note: In a production app, it is not recommended to only pass `publicProvider` to `configureChains` as you will probably face rate-limiting on the public provider endpoints. It is recommended to also pass an [`alchemyProvider`](/core/providers/alchemy) or [`infuraProvider`](/core/providers/infura) as well. [Read more about configuring chains](/core/providers/configuring-chains) Create a wagmi config[](#create-a-wagmi-config) ------------------------------------------------ Next, create a wagmi `config` instance using [`createConfig`](/core/config) , and pass the result from `configureChains` to it. import { createConfig, configureChains, mainnet, } from '@wagmi/core' import { publicProvider } from '@wagmi/core/providers/public' const { chains, publicClient, webSocketPublicClient } = configureChains( [mainnet], [publicProvider()], ) const config = createConfig({ autoConnect: true, publicClient, webSocketPublicClient, }) [Read more about client configuration](/core/config) You're good to go![](#youre-good-to-go) ---------------------------------------- Use actions! You can now import and use actions throughout your app. import { connect, fetchEnsName } from '@wagmi/core' import { InjectedConnector } from '@wagmi/core/connectors/injected' const { account } = await connect({ connector: new InjectedConnector(), }) const ensName = await fetchEnsName({ address: account }) Want to learn more? Continue on reading the documentation. [FAQ](/react/faq "FAQ") [Migration Guide](/core/migration-guide "Migration Guide") --- # Getting Started – wagmi On This Page * [Quick setup](#quick-setup) * [Manual setup](#manual-setup) * [Installation](#installation) * [Configure chains](#configure-chains) * [Create a wagmi config](#create-a-wagmi-config) * [Wrap app with WagmiConfig](#wrap-app-with-wagmiconfig) * [You're good to go!](#youre-good-to-go) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9CGetting%20Started%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/react/getting-started.en-US.mdx) * React * Getting Started Getting Started =============== Quick setup[](#quick-setup) ---------------------------- It is recommended to set up your wagmi app using the `create-wagmi` command line interface (CLI). This will set up a new wagmi app using TypeScript and install the required dependencies: npmpnpmyarn npm init wagmi When the setup is complete, you can start your app by running `npm run dev` and then navigating to `http://localhost:3000`. Want to learn more? Check out the [`create-wagmi` CLI docs](/cli/create-wagmi) . Manual setup[](#manual-setup) ------------------------------ ### Installation[](#installation) Install wagmi and its viem peer dependency. npmpnpmyarn npm i wagmi viem ### Configure chains[](#configure-chains) First, configure your desired chains to be used by wagmi, and the providers you want to use. import { configureChains, mainnet } from 'wagmi' import { publicProvider } from 'wagmi/providers/public' const { chains, publicClient, webSocketPublicClient } = configureChains( [mainnet], [publicProvider()], ) This example uses the Ethereum Mainnet chain (`mainnet`) from `wagmi`, however, you can also pass in any [EVM-compatible chain](/react/chains) . Note: In a production app, it is not recommended to only pass `publicProvider` to `configureChains` as you will probably face rate-limiting on the public provider endpoints. It is recommended to also pass an [`alchemyProvider`](/react/providers/alchemy) or [`infuraProvider`](/react/providers/infura) as well. [Read more about configuring chains](/react/providers/configuring-chains) ### Create a wagmi config[](#create-a-wagmi-config) Next, create a wagmi `config` instance using [`createConfig`](/react/config) , and pass the result from `configureChains` to it. import { WagmiConfig, createConfig, configureChains, mainnet } from 'wagmi' import { publicProvider } from 'wagmi/providers/public' const { chains, publicClient, webSocketPublicClient } = configureChains( [mainnet], [publicProvider()], ) const config = createConfig({ autoConnect: true, publicClient, webSocketPublicClient, }) [Read more about config configuration](/react/config) ### Wrap app with `WagmiConfig`[](#wrap-app-with-wagmiconfig) Finally, wrap your app with the [`WagmiConfig`](/react/WagmiConfig) component, passing `config` to it. const config = createConfig({ autoConnect: true, publicClient, webSocketPublicClient, }) function App() { return ( ) } ### You're good to go![](#youre-good-to-go) Use hooks! Every component inside the `WagmiConfig` is now set up to use the wagmi hooks. import { useAccount, useConnect, useEnsName } from 'wagmi' import { InjectedConnector } from 'wagmi/connectors/injected' function Profile() { const { address, isConnected } = useAccount() const { data: ensName } = useEnsName({ address }) const { connect } = useConnect({ connector: new InjectedConnector(), }) if (isConnected) return
Connected to {ensName ?? address}
return } Want to learn more? Check out the [examples](/examples/connect-wallet) to learn how to use wagmi in real-world scenarios or continue on reading the documentation. [Library Comparison](/react/comparison "Library Comparison") --- # wagmi: React Hooks for Ethereum – wagmi **wagmi** is a collection of React Hooks containing everything you need to start working with Ethereum. wagmi makes it easy to "Connect Wallet," display ENS and balance information, sign messages, interact with contracts, and much more — all with caching, request deduplication, and persistence. npmpnpmyarn npm i wagmi viem [Get Started](/core/getting-started) · [Examples](/examples/connect-wallet) · [GitHub Repository](https://github.com/wagmi-dev/wagmi) Overview[](#overview) ---------------------- import { WagmiConfig, createConfig, mainnet } from 'wagmi' import { createPublicClient, http } from 'viem' const config = createConfig({ autoConnect: true, publicClient: createPublicClient({ chain: mainnet, transport: http() }), }) function App() { return ( ) } import { useAccount, useConnect, useDisconnect } from 'wagmi' import { InjectedConnector } from 'wagmi/connectors/injected' function Profile() { const { address, isConnected } = useAccount() const { connect } = useConnect({ connector: new InjectedConnector(), }) const { disconnect } = useDisconnect() if (isConnected) return (
Connected to {address}
) return } In this example, we create a wagmi `config` and pass it to the `WagmiConfig` React Context. The config is set up to use viem's Public Client and automatically connect to previously connected wallets. Next, we use the `useConnect` hook to connect an injected wallet (e.g. MetaMask) to the app. Finally, we show the connected account's address with `useAccount` and allow them to disconnect with `useDisconnect`. We've only scratched the surface for what you can do with wagmi! Features[](#features) ---------------------- wagmi supports all these features out-of-the-box: * 20+ hooks for working with wallets, ENS, contracts, transactions, signing, etc. * Built-in wallet connectors for MetaMask, WalletConnect, Coinbase Wallet, Injected, and more * Caching, request deduplication, multicall, batching, and persistence * Auto-refresh data on wallet, block, and network changes * TypeScript ready (infer types from ABIs and EIP-712 Typed Data) * Command-line interface for managing ABIs and code generation * Test suite running against forked Ethereum network ...and a lot more. Community[](#community) ------------------------ Check out the following places for more wagmi-related content: * Follow [@wevm\_dev](https://twitter.com/wevm_dev) , [@awkweb](https://twitter.com/awkweb) , and [@jakemoxey](https://twitter.com/jakemoxey) on Twitter for project updates * Join the [discussions on GitHub](https://github.com/wagmi-dev/wagmi/discussions) * Share [your project/organization](https://github.com/wagmi-dev/wagmi/discussions/201) that uses wagmi * Browse the [awesome-wagmi](https://github.com/wagmi-dev/awesome-wagmi) list of awesome projects and resources Support[](#support) -------------------- Help support future development and make wagmi a sustainable open-source project. Thank you 🙏 * [GitHub Sponsors](https://github.com/sponsors/wagmi-dev?metadata_campaign=docs_support) * [Gitcoin Grant](https://wagmi.sh/gitcoin) * [wagmi-dev.eth](https://etherscan.io/enslookup-search?search=wagmi-dev.eth) Sponsors[](#sponsors) ---------------------- [![Paradigm](https://raw.githubusercontent.com/wagmi-dev/.github/main/content/sponsors/paradigm-dark.svg)](https://paradigm.xyz) [![Family](https://raw.githubusercontent.com/wagmi-dev/.github/main/content/sponsors/family-dark.svg)](https://twitter.com/family) [![Context](https://raw.githubusercontent.com/wagmi-dev/.github/main/content/sponsors/context-dark.svg)](https://twitter.com/context) [![WalletConnect](https://raw.githubusercontent.com/wagmi-dev/.github/main/content/sponsors/walletconnect-dark.svg)](https://walletconnect.com) [![LooksRare](https://raw.githubusercontent.com/wagmi-dev/.github/main/content/sponsors/looksrare-dark.svg)](https://looksrare.org) [![PartyDAO](https://raw.githubusercontent.com/wagmi-dev/.github/main/content/sponsors/partydao-dark.svg)](https://twitter.com/prtyDAO) [![Dynamic](https://raw.githubusercontent.com/wagmi-dev/.github/main/content/sponsors/dynamic-dark.svg)](https://www.dynamic.xyz) [![Sushi](https://raw.githubusercontent.com/wagmi-dev/.github/main/content/sponsors/sushi-dark.svg)](https://www.sushi.com) [![Stripe](https://raw.githubusercontent.com/wagmi-dev/.github/main/content/sponsors/stripe-dark.svg)](https://www.stripe.com) [![BitKeep](https://raw.githubusercontent.com/wagmi-dev/.github/main/content/sponsors/bitkeep-dark.svg)](https://bitkeep.com) [![Privy](https://raw.githubusercontent.com/wagmi-dev/.github/main/content/sponsors/privy-dark.svg)](https://privy.io) [![Spruce](https://raw.githubusercontent.com/wagmi-dev/.github/main/content/sponsors/spruce-dark.svg)](https://www.spruceid.com) [![rollup.id](https://raw.githubusercontent.com/wagmi-dev/.github/main/content/sponsors/rollup.id-dark.svg)](https://rollup.id) [![PancakeSwap](https://raw.githubusercontent.com/wagmi-dev/.github/main/content/sponsors/pancake-dark.svg)](https://pancakeswap.finance) [![Celo](https://raw.githubusercontent.com/wagmi-dev/.github/main/content/sponsors/celo-dark.svg)](https://celo.org) [![Rainbow](https://raw.githubusercontent.com/wagmi-dev/.github/main/content/sponsors/rainbow-dark.svg)](https://rainbow.me/) [![Pimlico](https://raw.githubusercontent.com/wagmi-dev/.github/main/content/sponsors/pimlico-dark.svg)](https://pimlico.io/) [![Zora](https://raw.githubusercontent.com/wagmi-dev/.github/main/content/sponsors/zora-dark.svg)](https://zora.co/) [![Lattice](https://raw.githubusercontent.com/wagmi-dev/.github/main/content/sponsors/lattice-dark.svg)](https://lattice.xyz) [![Supa](https://raw.githubusercontent.com/wagmi-dev/.github/main/content/sponsors/supa-dark.svg)](https://twitter.com/supafinance) [![zkSync](https://raw.githubusercontent.com/wagmi-dev/.github/main/content/sponsors/zksync-dark.svg)](https://zksync.io) --- # wagmi Blog – wagmi wagmi Blog ========== ### [wagmi turns one](/blog/wagmi-turns-one) wagmi launched a year ago. [Read more →](/blog/wagmi-turns-one) January 4, 2023 ### [Paradigm x wagmi](/blog/paradigm-wagmi) The wagmi core team is now working full-time on the future of wagmi and developer tools for Ethereum, sponsored by Paradigm. [Read more →](/blog/paradigm-wagmi) November 28, 2022 --- # Getting Started – @wagmi/cli On This Page * [Install wagmi cli](#install-wagmi-cli) * [Create config file](#create-config-file) * [Add contracts and plugins](#add-contracts-and-plugins) * [Run code generation](#run-code-generation) * [Use generated code](#use-generated-code) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9CGetting%20Started%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/cli/getting-started.en-US.mdx) * CLI * Getting Started Getting Started =============== The wagmi command line interface manages ABIs (from Etherscan/block explorers, Foundry/Hardhat projects, etc.), generates code (React Hooks, VanillaJS actions, etc.), and much more. It makes working with Ethereum easier by automating manual work (e.g. no more copying and pasting ABIs from Etherscan). You can also write plugins to extend the CLI further. Install wagmi cli[](#install-wagmi-cli) ---------------------------------------- Install the `@wagmi/cli` package to your project as a dev dependency. npmpnpmyarn npm i --save-dev @wagmi/cli Create config file[](#create-config-file) ------------------------------------------ Run the `init` command to generate a configuration file: either `wagmi.config.ts` if TypeScript is detected, otherwise `wagmi.config.js`. You can also create the configuration file manually. See [Configuration](/cli/configuration/configuring-cli) for more info. npmpnpmyarn npx wagmi init The generated configuration file will look something like this: wagmi.config.ts import { defineConfig } from '@wagmi/cli' export default defineConfig({ out: 'src/generated.ts', contracts: [], plugins: [], }) Add contracts and plugins[](#add-contracts-and-plugins) -------------------------------------------------------- Once the configuration file is set up, you can add contracts and plugins to it. These contracts and plugins are used to manage ABIs (fetch from block explorers, resolve from the file system, etc.), generate code (React hooks, type-safe JS actions, etc.), and much more! For example, we can add the `ERC20` contract from `wagmi`, and the [`etherscan`](/cli/plugins/etherscan) and [`react`](/cli/plugins/react) plugins. wagmi.config.ts import { defineConfig } from '@wagmi/cli' import { etherscan, react } from '@wagmi/cli/plugins' import { erc20ABI } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export default defineConfig({ out: 'src/generated.ts', contracts: [\ {\ name: 'erc20',\ abi: erc20ABI,\ },\ ], plugins: [\ etherscan({\ apiKey: process.env.ETHERSCAN_API_KEY!,\ chainId: mainnet.id,\ contracts: [\ {\ name: 'EnsRegistry',\ address: {\ [mainnet.id]: '0x314159265dd8dbb310642f98f50c066173c1259b',\ [sepolia.id]: '0x112234455c3a32fd11230c42e7bccd4a84e02010',\ },\ },\ ],\ }),\ react(),\ ], }) Run code generation[](#run-code-generation) -------------------------------------------- Now that we added a few contracts and plugins to the configuration file, we can run the `generate` command to resolve ABIs and generate code to the `out` file. npmpnpmyarn npx wagmi generate In this example, the `generate` command will do the following: * Validate the `etherscan` and `react` plugins * Fetch and cache the ENS Registry ABI from the Mainnet Etherscan API * Pull in the `erc20ABI` using the name `'ERC20'` * Generate React Hooks for both ABIs * Save ABIs, ENS Registry deployment addresses, and React Hooks to the `out` file Use generated code[](#use-generated-code) ------------------------------------------ Once `out` is created, you can start using the generated code in your project. import { mainnet } from 'wagmi/chains' import { useEnsRegistryContract, useErc20BalanceOfRead, useErc20Read } from './generated' // Use the generated ENS Registry contract hook const contract = useEnsRegistryContract({ chainId: mainnet.id, }) // Use the generated ERC-20 read hook const { data } = useErc20Read({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', functionName: 'balanceOf', args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'], }) // Use the generated ERC-20 "balanceOf" hook const { data } = useErc20BalanceOfRead({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'], }) Instead of committing the `out` file, you likely want to add `out` to your `.gitignore` and run `generate` during the build process or before you start your dev server in a `"predev"` script (or similar). Want to learn more? Continue on reading the documentation. [FAQ](/core/faq "FAQ") [Configuring CLI](/cli/configuration/configuring-cli "Configuring CLI") --- # TypeScript – @wagmi/core On This Page * [Type Inference](#type-inference) * [Contract ABIs](#contract-abis) * [EIP-712 Typed Data](#eip-712-typed-data) * [Configuring Internal Types](#configuring-internal-types) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9CTypeScript%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/core/typescript.en-US.mdx) * Core * TypeScript TypeScript ========== wagmi is designed to be as type-safe as possible! Things to keep in mind: * Types currently require using TypeScript v5.0.4 or greater. * Changes to types in this repository are considered non-breaking and are usually released as patch semver changes (otherwise every type enhancement would be a major version!). * It is highly recommended that you lock your `@wagmi/core` package version to a specific patch release and upgrade with the expectation that types may be fixed or upgraded between any release. * The non-type-related public API of wagmi still follows semver very strictly. To ensure everything works correctly, make sure that your `tsconfig.json` has [`strict`](https://www.typescriptlang.org/tsconfig#strict) mode set to true: tsconfig.json { "compilerOptions": { "strict": true } } Type Inference[](#type-inference) ---------------------------------- wagmi can infer types based on [ABI](https://docs.soliditylang.org/en/v0.8.15/abi-spec.html#json) and [EIP-712](https://eips.ethereum.org/EIPS/eip-712) Typed Data definitions (powered by [ABIType](https://github.com/wagmi-dev/abitype) ), giving you full end-to-end type-safety from your contracts to your frontend and incredible developer experience (e.g. autocomplete ABI function names and catch misspellings, type ABI function arguments, etc.). For this to work, you must either add [const assertions](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions) to specific configuration parameters (more info on those below) or define them inline. For example, `readContract`'s `abi` configuration parameter: const result = readContract({ abi: […], // <--- defined inline }) const abi = […] as const // <--- const assertion const result = readContract({ abi }) If type inference isn't working, it's likely you forgot to add a `const` assertion or define the configuration parameter inline. Unfortunately [TypeScript doesn't support importing JSON as const](https://github.com/microsoft/TypeScript/issues/32063) . Check out [`@wagmi/cli`](/cli) to help with this! It can automatically fetchi ABIs from Etherscan, resolve ABIs from your Foundry/Hardhat projects, generate VanillaJS actions, and much more. ### Contract ABIs[](#contract-abis) The following actions support type inference when you add a const assertion to `abi`: * [getContract](/core/actions/getContract) * [multicall](/core/actions/multicall) * [prepareContractWrite](/core/prepare-hooks/usePrepareContractWrite) * [readContract](/core/actions/readContract) * [readContracts](/core/actions/readContracts) * [watchContractEvent](/core/actions/watchContractEvent) * [watchMulticall](/core/actions/watchMulticall) * [watchReadContract](/core/actions/watchReadContract) * [watchReadContracts](/core/actions/watchReadContracts) * [writeContract](/core/actions/writeContract) For example, `readContract`: import { readContract } from '@wagmi/core' const result = await readContract({ // ^? const data: bigint address: '0xecb504d39723b0be0e3a9aa33d646642d1051ee1', abi: [\ {\ name: 'getUncleanliness',\ inputs: [],\ outputs: [{ name: '', type: 'uint256' }],\ stateMutability: 'view',\ type: 'function',\ },\ {\ name: 'love',\ inputs: [{ name: '', type: 'address' }],\ outputs: [{ name: '', type: 'uint256' }],\ stateMutability: 'view',\ type: 'function',\ },\ {\ name: 'play',\ inputs: [],\ outputs: [],\ stateMutability: 'nonpayable',\ type: 'function',\ },\ ], functionName: 'love', // ^? (property) functionName: "getUncleanliness" | "love" // Notice how "play" is not included since it is not a "read" function args: ['0x27a69ffba1e939ddcfecc8c7e0f967b872bac65c'], // ^? (property) args: readonly [`0x${string}`] }) ### EIP-712 Typed Data[](#eip-712-typed-data) Adding a const assertion to `types` adds type inference to `signTypedData`'s `value` configuration parameter: import { signTypedData } from '@wagmi/core' const result = await signTypedData({ domain: { name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', }, types: { Person: [\ { name: 'name', type: 'string' },\ { name: 'wallet', type: 'address' },\ ], Mail: [\ { name: 'from', type: 'Person' },\ { name: 'to', type: 'Person' },\ { name: 'contents', type: 'string' },\ ], }, value: { // ^? (parameter) value: { name: string; wallet: `0x${string}` } | { // from: { // name: string; // wallet: `0x${string}`; // }; // to: { // name: string; // wallet: `0x${string}`; // }; // contents: string; // } from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, }) Configuring Internal Types[](#configuring-internal-types) ---------------------------------------------------------- For advanced use-cases, you may want to configure wagmi's internal types. Most of wagmi's types relating to ABIs and EIP-712 Typed Data are powered by [ABIType](https://github.com/wagmi-dev/abitype) . See ABIType's [documentation](https://github.com/wagmi-dev/abitype#configuration) for more info on how to configure types. [Migration Guide](/core/migration-guide "Migration Guide") [createConfig](/core/config "createConfig") --- # Connect Wallet Example – wagmi On This Page * [Step 1: Configuring Connectors](#step-1-configuring-connectors) * [Step 2: Display Wallet Options](#step-2-display-wallet-options) * [Step 3: Display Connected Account](#step-3-display-connected-account) * [Wrap Up](#wrap-up) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9CConnect%20Wallet%20Example%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/examples/connect-wallet.en-US.mdx) * Examples * Connect Wallet Connect Wallet ============== Connecting wallets to your app is extremely simple when you use wagmi. It takes less than five minutes to get up and running with MetaMask, WalletConnect, and Coinbase Wallet! The example below uses [`useConnect`](/react/hooks/useConnect) , [`useAccount`](/react/hooks/useAccount) , and [`useDisconnect`](/react/hooks/useDisconnect) to allow you to connect a wallet and view ENS information for the connected account. Try it out before moving on. Check out [ConnectKit](https://docs.family.co/connectkit?utm_source=wagmi-dev) , [Web3Modal](https://web3modal.com/) , [Dynamic](https://dynamic.xyz/) , or [RainbowKit](https://rainbowkit.com/docs/introduction) to get started with pre-built interface on top of wagmi for managing wallet connections. Step 1: Configuring Connectors[](#step-1-configuring-connectors) ----------------------------------------------------------------- First, we create a new wagmi config set up with the Injected (i.e. MetaMask), WalletConnect, and Coinbase Wallet connectors. This example uses the Ethereum Mainnet chain (`mainnet`) from `wagmi`, however, you can also pass in any [EVM-compatible chain](/react/chains) . import { WagmiConfig, createConfig, configureChains, mainnet } from 'wagmi' import { alchemyProvider } from 'wagmi/providers/alchemy' import { publicProvider } from 'wagmi/providers/public' import { CoinbaseWalletConnector } from 'wagmi/connectors/coinbaseWallet' import { InjectedConnector } from 'wagmi/connectors/injected' import { MetaMaskConnector } from 'wagmi/connectors/metaMask' import { WalletConnectConnector } from 'wagmi/connectors/walletConnect' // Configure chains & providers with the Alchemy provider. // Two popular providers are Alchemy (alchemy.com) and Infura (infura.io) const { chains, publicClient, webSocketPublicClient } = configureChains( [mainnet], [alchemyProvider({ apiKey: 'yourAlchemyApiKey' }), publicProvider()], ) // Set up wagmi config const config = createConfig({ autoConnect: true, connectors: [\ new MetaMaskConnector({ chains }),\ new CoinbaseWalletConnector({\ chains,\ options: {\ appName: 'wagmi',\ },\ }),\ new WalletConnectConnector({\ chains,\ options: {\ projectId: '...',\ },\ }),\ new InjectedConnector({\ chains,\ options: {\ name: 'Injected',\ shimDisconnect: true,\ },\ }),\ ], publicClient, webSocketPublicClient, }) // Pass config to React Context Provider function App() { return ( ) } Step 2: Display Wallet Options[](#step-2-display-wallet-options) ----------------------------------------------------------------- Now that our connectors are set up, we want users to be able to choose a connector to connect their wallets using `useConnect`. import { useConnect } from 'wagmi' export function Profile() { const { connect, connectors, error, isLoading, pendingConnector } = useConnect() return (
{connectors.map((connector) => ( ))} {error &&
{error.message}
}
) } Step 3: Display Connected Account[](#step-3-display-connected-account) ----------------------------------------------------------------------- Lastly, if an account is connected, we want to show some basic information, like the connected address and ENS name and avatar. We can display the connected account with `useAccount` and add a button for disconnecting with `useDisconnect`. import { useAccount, useConnect, useDisconnect, useEnsAvatar, useEnsName, } from 'wagmi' export function Profile() { const { address, connector, isConnected } = useAccount() const { data: ensName } = useEnsName({ address }) const { data: ensAvatar } = useEnsAvatar({ name: ensName }) const { connect, connectors, error, isLoading, pendingConnector } = useConnect() const { disconnect } = useDisconnect() if (isConnected) { return (
ENS Avatar
{ensName ? `${ensName} (${address})` : address}
Connected to {connector.name}
) } return (
{connectors.map((connector) => ( ))} {error &&
{error.message}
}
) } Wrap Up[](#wrap-up) -------------------- That's it! You now have a way for users to connect wallets and view information about the connected account. wagmi also listens for account and chain changes to keep connections and information up-to-date. [Getting Started](/cli/create-wagmi "Getting Started") [Send Transaction](/examples/send-transaction "Send Transaction") --- # Chains – @wagmi/core On This Page * [@wagmi/core/chains](#wagmicorechains) * [Usage](#usage) * [Supported chains](#supported-chains) * [Build your own](#build-your-own) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9CChains%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/core/chains.en-US.mdx) * Core * Chains Chains ====== `@wagmi/core` exports the **Mainnet** (`mainnet`) & **Sepolia** (`sepolia`) chains out-of-the-box. import { mainnet, sepolia } from '@wagmi/core' If you wish to extend to other EVM-compatible chains (like Polygon, Optimism, BSC, Avalanche, etc), you can either import the chain directly from the `@wagmi/core/chains` entrypoint, or build it yourself. `@wagmi/core/chains`[](#wagmicorechains) ----------------------------------------- The `@wagmi/core/chains` entrypoint proxies the [`viem/chains` entrypoint](https://viem.sh/docs/clients/chains.html#chains) ,which contains references to popular EVM-compatible chains such as: Polygon, Optimism, Avalanche, and more. ### Usage[](#usage) Import your chains from the entrypoint and use them in your wagmi app: import { configureChains } from '@wagmi/core' import { avalanche, bsc, mainnet } from '@wagmi/core/chains' const { chains, publicClient } = configureChains( [mainnet, avalanche, bsc], ... ) [Read more on configuring chains](/react/providers/configuring-chains) ### Supported chains[](#supported-chains) * `mainnet` * `goerli` * `arbitrum` * `arbitrumGoerli` * `arbitrumNova` * `aurora` * `auroraTestnet` * `avalanche` * `avalancheFuji` * `base` * `baseGoerli` * `boba` * `bronos` * `bronosTestnet` * `bsc` * `bscTestnet` * `bxn` * `bxnTestnet` * `canto` * `celo` * `celoAlfajores` * `classic` * `confluxESpace` * `confluxESpaceTestnet` * `chronos` * `chronosTestnet` * `crossbell` * `dfk` * `dogechain` * `edgeware` * `edgewareTestnet` * `eos` * `eosTestnet` * `ekta` * `ektaTestnet` * `evmos` * `evmosTestnet` * `fantom` * `fantomTestnet` * `fibo` * `filecoin` * `filecoinCalibration` * `filecoinHyperspace` * `flare` * `flareTestnet` * `fuse` * `fuseSparknet` * `gobi` * `gnosis` * `gnosisChiado` * `haqqMainnet` * `haqqTestedge2` * `harmonyOne` * `iotex` * `iotexTestnet` * `klaytn` * `linea` * `lineaTestnet` * `mantle` * `mantleTestnet` * `metis` * `metisGoerli` * `mev` * `mevTestnet` * `modeTestnet` * `moonbaseAlpha` * `moonbeam` * `moonriver` * `neonDevnet` * `neonMainnet` * `nexilix` * `nexi` * `oasys` * `okc` * `optimism` * `optimismGoerli` * `polygon` * `polygonMumbai` * `polygonZkEvm` * `polygonZkEvmTestnet` * `pulsechain` * `pulsechainV4` * `qMainnet` * `qTestnet` * `rollux` * `rolluxTestnet` * `ronin` * `saigon` * `scrollSepolia` * `scrollTestnet` * `sepolia` * `shardeumSphinx` * `skaleCalypso` * `skaleCalypsoTestnet` * `skaleChaosTestnet` * `skaleCryptoBlades` * `skaleCryptoColosseum` * `skaleEuropa` * `skaleEuropaTestnet` * `skaleExorde` * `skaleHumanProtocol` * `skaleNebula` * `skaleNebulaTestnet` * `skaleRazor` * `skaleTitan` * `skaleTitanTestnet` * `syscoin` * `syscoinTestnet` * `songbird` * `songbirdTestnet` * `taikoTestnetSepolia` * `taraxa` * `taraxaTestnet` * `telos` * `telosTestnet` * `thunderTestnet` * `titan` * `titanTestnet` * `wanchain` * `wanchainTestnet` * `xdc` * `xdcTestnet` * `zetachainAthensTestnet` * `zkSync` * `zkSyncTestnet` * `zora` * `zoraTestnet` * `foundry` * `hardhat` * `localhost` > Want to add a chain that's not listed here? Head to the [Viem](https://github.com/wagmi-dev/viem) > and read the [Contributing Guide](https://github.com/wagmi-dev/viem/blob/main/.github/CONTRIBUTING.md) > before opening a pull request. Build your own[](#build-your-own) ---------------------------------- You can also extend wagmi to support other EVM-compatible chains by building your own chain object that inherits the `Chain` type. import { Chain } from '@wagmi/core' export const avalanche = { id: 43_114, name: 'Avalanche', network: 'avalanche', nativeCurrency: { decimals: 18, name: 'Avalanche', symbol: 'AVAX', }, rpcUrls: { public: { http: ['https://api.avax.network/ext/bc/C/rpc'] }, default: { http: ['https://api.avax.network/ext/bc/C/rpc'] }, }, blockExplorers: { etherscan: { name: 'SnowTrace', url: 'https://snowtrace.io' }, default: { name: 'SnowTrace', url: 'https://snowtrace.io' }, }, contracts: { multicall3: { address: '0xca11bde05977b3631167028862be2a173976ca11', blockCreated: 11_907_934, }, }, } as const satisfies Chain [createConfig](/core/config "createConfig") [Configuring Chains](/core/providers/configuring-chains "Configuring Chains") --- # Config – @wagmi/core On This Page * [Usage](#usage) * [Configuration](#configuration) * [autoConnect (optional)](#autoconnect-optional) * [connectors (optional)](#connectors-optional) * [logger (optional)](#logger-optional) * [publicClient](#publicclient) * [storage (optional)](#storage-optional) * [webSocketPublicClient (optional)](#websocketpublicclient-optional) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9CConfig%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/core/config.en-US.mdx) * Core * createConfig Config ====== The @wagmi/core `config` is a framework agnostic (Vanilla JS) config that manages wallet connection state and configuration, such as: auto-connection, connectors, and viem clients. import { createConfig } from '@wagmi/core' Usage[](#usage) ---------------- import { createConfig, configureChains, mainnet } from '@wagmi/core' import { publicProvider } from '@wagmi/core/providers/public' const { chains, publicClient, webSocketPublicClient } = configureChains( [mainnet], [publicProvider()], ) const config = createConfig({ chains, publicClient, webSocketPublicClient, }) Configuration[](#configuration) -------------------------------- ### autoConnect (optional)[](#autoconnect-optional) Enables reconnecting to last used connector on mount. Defaults to `false`. import { createConfig, configureChains, mainnet } from '@wagmi/core' import { publicProvider } from '@wagmi/core/providers/public' const { publicClient } = configureChains([mainnet], [publicProvider()]) const config = createConfig({ autoConnect: true, publicClient, }) ### connectors (optional)[](#connectors-optional) Connectors used for linking accounts. Defaults to `[new InjectedConnector()]`. import { createConfig, configureChains, mainnet } from '@wagmi/core' import { publicProvider } from '@wagmi/core/providers/public' import { InjectedConnector } from '@wagmi/core/connectors/injected' import { WalletConnectConnector } from '@wagmi/core/connectors/walletConnect' const { chains, publicClient } = configureChains([mainnet], [publicProvider()]) const config = createConfig({ connectors: [\ new InjectedConnector({ chains }),\ new WalletConnectConnector({\ chains,\ options: {\ projectId: '...',\ },\ }),\ ], publicClient, }) ### logger (optional)[](#logger-optional) Adds the ability to provide a custom logger to override how logs are broadcasted in @wagmi/core. Defaults to `console` logging. import { createConfig, configureChains, mainnet } from '@wagmi/core' import { publicProvider } from '@wagmi/core/providers/public' import { logWarn } from './logger' const { publicClient } = configureChains([mainnet], [publicProvider()]) const config = createConfig({ logger: { warn: (message) => logWarn(message), }, publicClient, }) You can also disable a logger by passing `null` as the value. // ... const config = createConfig({ logger: { warn: null, }, publicClient, }) ### publicClient[](#publicclient) viem [Public Client](https://viem.sh/docs/clients/public.html) for reading from the Ethereum network. import { createConfig, configureChains, mainnet } from '@wagmi/core' import { publicProvider } from '@wagmi/core/providers/public' const { publicClient } = configureChains([mainnet], [publicProvider()]) const config = createConfig({ publicClient, }) You can create a "chain-aware" `provider` by using the `configureChains` API or passing a function that updates based on `chainId`. ### storage (optional)[](#storage-optional) The default strategy to persist and cache data. Defaults to `window.localStorage`. import { createConfig, createStorage, configureChains, mainnet, } from '@wagmi/core' import { publicProvider } from '@wagmi/core/providers/public' const { publicClient } = configureChains([mainnet], [publicProvider()]) const config = createConfig({ publicClient, storage: createStorage({ storage: window.localStorage }), }) ### webSocketPublicClient (optional)[](#websocketpublicclient-optional) viem [Public Client](https://viem.sh/docs/clients/public.html) with a [WebSocket Transport](https://viem.sh/docs/clients/transports/websocket.html) for connecting to the Ethereum network. If you provide a WebSocket Public Client, it will be used instead of polling in certain instances. import { createConfig, configureChains, mainnet } from '@wagmi/core' import { publicProvider } from '@wagmi/core/providers/public' const { publicClient, webSocketPublicClient } = configureChains( [mainnet], [publicProvider()], ) const config = createConfig({ publicClient, webSocketPublicClient, }) You can create a "chain-aware" `webSocketProvider` by using the `configureChains` API or passing a function that updates based on `chainId`. [TypeScript](/core/typescript "TypeScript") [Chains](/core/chains "Chains") --- # Migration Guide – @wagmi/core On This Page * [1.x.x Breaking changes](#1xx-breaking-changes) * [General](#general) * [Removed ethers peer dependency](#removed-ethers-peer-dependency) * ["Provider" & "Signer" terminology](#provider--signer-terminology) * [createClient → createConfig](#createclient--createconfig) * [WagmiClient](#wagmiclient) * [getClient → getConfig](#getclient--getconfig) * [BigNumber → native BigInt](#bignumber--native-bigint) * [from has been renamed to account](#from-has-been-renamed-to-account) * [gasLimit has been renamed to gas](#gaslimit-has-been-renamed-to-gas) * [Removed goerli export](#removed-goerli-export) * [Removed window.ethereum global type](#removed-windowethereum-global-type) * [Renamed the Ethereum type to WindowProvider](#renamed-the-ethereum-type-to-windowprovider) * [Actions](#actions) * [connect](#connect) * [fetchBalance](#fetchbalance) * [fetchBlockNumber](#fetchblocknumber) * [fetchEnsAvatar](#fetchensavatar) * [fetchFeeData](#fetchfeedata) * [fetchToken](#fetchtoken) * [fetchTransaction](#fetchtransaction) * [getContract](#getcontract) * [getProvider](#getprovider) * [getSigner](#getsigner) * [getWebSocketProvider](#getwebsocketprovider) * [multicall](#multicall) * [prepareSendTransaction](#preparesendtransaction) * [prepareWriteContract](#preparewritecontract) * [readContracts](#readcontracts) * [readContract](#readcontract) * [sendTransaction](#sendtransaction) * [signMessage](#signmessage) * [signTypedData](#signtypeddata) * [waitForTransaction](#waitfortransaction) * [watchPendingTransactions](#watchpendingtransactions) * [watchProvider](#watchprovider) * [watchSigner](#watchsigner) * [watchWebSocketProvider](#watchwebsocketprovider) * [writeContract](#writecontract) * [watchContractEvent](#watchcontractevent) * [configureChains](#configurechains) * [Removed quorum support](#removed-quorum-support) * [Connectors](#connectors) * [Renamed getSigner to getWalletClient](#renamed-getsigner-to-getwalletclient) * [Errors](#errors) * [ChainDoesNotSupportMulticallError](#chaindoesnotsupportmulticallerror) * [ContractMethodDoesNotExistError](#contractmethoddoesnotexisterror) * [ContractMethodNoResultError](#contractmethodnoresulterror) * [ContractMethodRevertedError](#contractmethodrevertederror) * [ContractResultDecodeError](#contractresultdecodeerror) * [ProviderRpcError](#providerrpcerror) * [ResourceUnavailableError](#resourceunavailableerror) * [0.10.x Breaking changes](#010x-breaking-changes) * [WalletConnectConnector](#walletconnectconnector) * [If you are already using WalletConnect v2:](#if-you-are-already-using-walletconnect-v2) * [If you are still using WalletConnect v1:](#if-you-are-still-using-walletconnect-v1) * [0.9.x Breaking changes](#09x-breaking-changes) * [Upgrade to typescript@>=4.9.4](#upgrade-to-typescript494) * [0.8.x Breaking changes](#08x-breaking-changes) * [Chain exports](#chain-exports) * [Removed chain](#removed-chain) * [Removed allChains](#removed-allchains) * [Removed defaultChains & defaultL2Chains](#removed-defaultchains--defaultl2chains) * [Removed chainId](#removed-chainid) * [Removed etherscanBlockExplorers](#removed-etherscanblockexplorers) * [Removed alchemyRpcUrls, infuraRpcUrls & publicRpcUrls](#removed-alchemyrpcurls-infurarpcurls--publicrpcurls) * [Chain type](#chain-type) * [RPC URLs](#rpc-urls) * [Contracts](#contracts) * [waitForTransaction](#waitfortransaction-1) * [Behavioral changes](#behavioral-changes) * [Configuration changes](#configuration-changes) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9CMigration%20Guide%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/core/migration-guide.en-US.mdx) * Core * Migration Guide Migration Guide =============== If you are coming from an earlier version of `@wagmi/core`, you will need to make sure to update the following APIs listed below. 1.x.x Breaking changes[](#1xx-breaking-changes) ------------------------------------------------ 💡 Not ready to migrate yet? You can find the `0.10.x` docs [here](https://0.12.x.wagmi.sh) . ### General[](#general) #### Removed `ethers` peer dependency[](#removed-ethers-peer-dependency) The `ethers` peer dependency has been removed in favour of [`viem`](https://viem.sh) . npm uninstall ethers npm i @wagmi/core@latest viem@latest If your project is using modules from `ethers` directly, that are dependant on wagmi (e.g. `BigNumber`, etc), you will need to migrate to the `viem`\-equivalent module. Check out the [Ethers.js → viem migration guide](https://viem.sh/docs/ethers-migration.html) . If you have usages of `ethers` that are independent of wagmi, it is highly recommended to migrate to `viem` to take advantage of the smaller bundle size. #### "Provider" & "Signer" terminology[](#provider--signer-terminology) Ethers [Provider](https://docs.ethers.org/v5/api/providers/) & [Signer](https://docs.ethers.org/v5/api/signer/) terminology is now known as viem's [Public Client](https://viem.sh/docs/clients/public.html) & [Wallet Client](https://viem.sh/docs/clients/wallet.html) terminology. This directly affects: * `createClient` * `configureChains` * `getProvider` (now `getPublicClient`) * `fetchSigner` (now `getWalletClient`) * `getWebSocketProvider` (now `getWebSocketPublicClient`) **`createClient`** import { WagmiConfig, createConfig, mainnet } from 'wagmi' - import { getDefaultProvider } from 'ethers' + import { createPublicClient, http } from 'viem' + import { mainnet } from 'viem/chains' const config = createConfig({ autoConnect: true, - provider: getDefaultProvider(), + publicClient: createPublicClient({ + chain: mainnet, + transport: http() + }) }) > Note: You may notice that `createClient` is now `createConfig`. Don't worry – the migration for that is below. **`configureChains`** import { WagmiConfig, createConfig, configureChains, mainnet } from '@wagmi/core' import { publicProvider } from '@wagmi/core/providers/public' const { chains, - provider, + publicClient, - webSocketProvider, + webSocketPublicClient } = configureChains( [mainnet], [publicProvider()], ) const config = createConfig({ autoConnect: true, - provider, + publicClient, - webSocketProvider, + webSocketPublicClient }) **`getProvider`** - import { getProvider } from '@wagmi/core' + import { getPublicClient } from '@wagmi/core' - const provider = getProvider() + const publicClient = getPublicClient() **`fetchSigner`** - import { fetchSigner } from 'wagmi' + import { getWalletClient } from 'wagmi' - const signer = await fetchSigner() + const walletClient = await getWalletClient() **`getWebSocketProvider`** - import { getWebSocketProvider } from 'wagmi' + import { getWebSocketPublicClient } from 'wagmi' - const webSocketProvider = getWebSocketProvider() + const webSocketPublicClient = getWebSocketPublicClient() **Types** * `Provider` → `PublicClient` * `Signer` → `WalletClient` * `WebSocketProvider` → `WebSocketPublicClient` #### `createClient` → `createConfig`[](#createclient--createconfig) The `createClient` function has been renamed to `createConfig`. - import { createClient } from '@wagmi/core' + import { createConfig } from '@wagmi/core' - const client = createClient({ + const config = createConfig({ ... }) #### `WagmiClient`[](#wagmiclient) The `WagmiConfig` Context now takes the `config` prop instead of `client`. import { createConfig, WagmiConfig } from 'wagmi' const config = createConfig({ ... }) function App() { return ( - + /** your app */ ) } #### `getClient` → `getConfig`[](#getclient--getconfig) If you are using `getClient`, that has been renamed to `getConfig`: - import { getClient } from '@wagmi/core' + import { getConfig } from '@wagmi/core' - const client = getClient() + const config = getConfig() #### `BigNumber` → native `BigInt`[](#bignumber--native-bigint) All `BigNumber` instances are now [platform native `BigInt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) instances. This means you can no longer use arithmatic methods such as `.add`, `.subtract`, etc because `BigInt` is just a primitive type like `number`. - const value = BigNumber.from('69420') + const value = 69420n - const value = BigNumber.from('69420') + const value = 69420n - const value2 = BigNumber.from('42069') + const value2 = 42069n - const value3 = value.add(value2) + const value3 = value + value2 ⚠️ Using native `BigInt` with `JSON.stringify` will raise a `TypeError` as `BigInt` values are not serializable. [Read here for instructions to mitigate](/core/faq) . #### `from` has been renamed to `account`[](#from-has-been-renamed-to-account) The `from` attribute has been renamed to `account`. Directly affects Actions that consist of a `from` parameter. const config = prepareWriteContract({ ..., - from: '0x...' + account: '0x...' }) #### `gasLimit` has been renamed to `gas`[](#gaslimit-has-been-renamed-to-gas) The `gasLimit` attribute has been renamed to `gas`, and still implies the same meaning. It was renamed to align closer to [EIP-1474](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1474.md) and enforce consistency. Aligning closer to EIP-1474 means that you will not need to re-map from `gas` to `gasLimit` if you are deriving from an external source. sendTransaction({ request: { to: 'jxom.eth', - gasLimit: 69420n, + gas: 69420n, value: 1n } }) #### Removed `goerli` export[](#removed-goerli-export) Removed the `goerli` export from `@wagmi/core`. Goerli is now a deprecated testnet. You will now have to import it from `wagmi/chains`. -import { goerli } from '@wagmi/core' +import { goerli } from 'wagmi/chains' #### Removed `window.ethereum` global type[](#removed-windowethereum-global-type) The `window.ethereum` global type has been removed in favor of an explicit `@wagmi/core/window` import. +import '@wagmi/core/window'; const isMetaMask = window.ethereum.isMetaMask #### Renamed the `Ethereum` type to `WindowProvider`[](#renamed-the-ethereum-type-to-windowprovider) The `Ethereum` type has been renamed to `WindowProvider`. ### Actions[](#actions) #### `connect`[](#connect) **No longer returns the `provider` property. Use `connector.getProvider()` instead.** const result = await connect({ ... }) - const provider = result.provider + const provider = await result.connector.getProvider() #### `fetchBalance`[](#fetchbalance) **Returns a `bigint`** Returns a `bigint` instead of `BigNumber` for `value`. Maps to viem's [`getBalance`](https://viem.sh/docs/actions/public/getBalance.html) . const balance = await fetchBalance({ ... }) const value = balance.value // ^? const value: bigint #### `fetchBlockNumber`[](#fetchblocknumber) **Returns a `bigint`** Returns a `bigint` instead of `number`. Maps to viem's [`getBlockNumber`](https://viem.sh/docs/actions/public/getBlockNumber.html) . const blockNumber = await fetchBlockNumber({ // ^? const blockNumber: bigint ... }) #### `fetchEnsAvatar`[](#fetchensavatar) **Replaced `address` with `name`** Replaced `address` with `name` in order to remove internal async call to resolve `address` to `name`. Maps to viem's [`getEnsAvatar`](https://viem.sh/docs/ens/actions/getEnsAvatar.html) . + const ensName = await fetchEnsName({ + address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', + }) const avatar = await fetchEnsAvatar({ - address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', + name: ensName, }) #### `fetchFeeData`[](#fetchfeedata) **Return type changes** Returns `bigint` instead of a `BigNumber` for `gasPrice` , `maxFeePerGas` , and `maxPriorityFeePerGas`. const feeData = await fetchFeeData() feeData.gasPrice // ^? const gasPrice: bigint feeData.maxFeePerGas // ^? const maxFeePerGas: bigint feeData.maxPriorityFeePerGas // ^? const maxPriorityFeePerGas: bigint #### `fetchToken`[](#fetchtoken) **Returns a `bigint`** Returns `bigint` instead of a `BigNumber` for `totalSupply.value`. const token = await fetchToken({ ... }) const value = token.totalSupply.value // ^? const value: bigint #### `fetchTransaction`[](#fetchtransaction) **Returns viem `Transaction`** Returns viem [`Transaction`](https://github.com/wagmi-dev/viem/blob/136c4022c3ab4020f37333876bed788a111bff47/src/types/transaction.ts#L105) instead of an ethers `Transaction`. Maps to viem's [`getTransaction`](https://viem.sh/docs/actions/public/getTransaction.html) . const transaction = await fetchTransaction({ // ^? const transaction: Transaction ... }) #### `getContract`[](#getcontract) **Returns viem Contract Instance** Returns viem [Contract Instance](https://viem.sh/docs/contract/getContract.html) instead of ethers `Contract`. #### `getProvider`[](#getprovider) **Renamed to `getPublicClient`** Returns viem [Public Client](https://viem.sh/docs/clients/public.html) instead of ethers `Provider`. - const provider = getProvider(...) + const publicClient = getPublicClient(...) #### `getSigner`[](#getsigner) **Renamed to `getWalletClient`** Returns viem [Wallet Client](https://viem.sh/docs/clients/wallet.html) instead of ethers `Signer`. - const signer = await getSigner(...) + const walletClient = await getWalletClient(...) #### `getWebSocketProvider`[](#getwebsocketprovider) **Renamed to `getWebSocketPublicClient`** Returns viem [Public Client](https://viem.sh/docs/clients/public.html) instead of ethers `Provider`. - const webSocketProvider = getWebSocketProvider(...) + const webSocketPublicClient = getWebSocketPublicClient(...) #### `multicall`[](#multicall) **Return type structure changed** When `allowFailure` is truthy (default), the return structure is now in the form of `{ error, result, status }[]` instead of an array of contract function results (`Result[]`). const data = await multicall({ ... }) - const result = data[0] + const { result } = data[0] The return type when `allowFailure` is falsy has not changed. **Removed `console.warn` logs for failing contract methods** The `console.warn` logs for failing contract methods has been removed. Failing methods can now be extracted from the `error` property of the return type. const data = await multicall({ ... }) + data.forEach(({ error, status }) => { + if (status === 'failure') console.warn(error.message) + }) **Removed `overrides`** The `overrides` parameter has been removed in favor of top-level `blockNumber` & `blockTag` parameters. const data = await multicall({ ... - overrides: { - blockTag: 'safe' - } + blockTag: 'safe' }) #### `prepareSendTransaction`[](#preparesendtransaction) **Removed `request`** The `request` parameter has been removed in favor of top-level parameters. Maps to [viem's `sendTransaction` parameters](https://viem.sh/docs/actions/public/sendTransaction.html#account) . const request = await prepareSendTransaction({ - request: { - to: 'jxom.eth', - value: BigNumber.from('69420'), - }, + to: 'jxom.eth', + value: 69420n }) #### `prepareWriteContract`[](#preparewritecontract) **Removed `overrides`** The `overrides` parameter has been removed in favor of top-level parameters. Maps to [viem's `simulateContract` parameters](https://viem.sh/docs/contract/simulateContract.html#account) . const { config } = await prepareWriteContract({ address: '0xecb504d39723b0be0e3a9aa33d646642d1051ee1', abi: wagmigotchiABI, functionName: 'feed', - overrides: { - from: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', - value: BigNumber.from('69420'), - }, + account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', + value: 69420n }) **Return type structure changed** The returned `request` now returns the shape of [viem's `WriteContractParameters`](https://viem.sh/docs/contract/writeContract.html#parameters) , instead of Ethers' `TransactionRequest`. Removed `abi`, `address`, `functionName` from the return value, they now belong in `request`. #### `readContracts`[](#readcontracts) **Return type structure changed** When `allowFailure` is truthy (default), the return structure is now in the form of `{ error, result, status }[]` instead of an array of contract function results (`Result[]`). const data = await readContracts({ ... }) - const result = data[0] + const { result } = data[0] The return type when `allowFailure` is falsy has not changed. **Removed `console.warn` logs for failing contract methods** The `console.warn` logs for failing contract methods has been removed. Failing methods can now be extracted from the `error` property of the return type. const data = await readContracts({ ... }) + data.forEach(({ error, status }) => { + if (status === 'failure') console.warn(error.message) + }) **Removed `overrides`** The `overrides` parameter has been removed in favor of top-level `blockNumber` & `blockTag` parameters. const data = await readContracts({ ... - overrides: { - blockTag: 'safe' - } + blockTag: 'safe' }) #### `readContract`[](#readcontract) **Removed `overrides`** The `overrides` parameter has been removed in favor of top-level `blockNumber` & `blockTag` parameters. const data = await readContract({ ... - overrides: { - blockTag: 'safe' - } + blockTag: 'safe' }) #### `sendTransaction`[](#sendtransaction) **Removed `request`** The `request` parameter has been removed in favor of top-level parameters. Maps to [viem's `sendTransaction` parameters](https://viem.sh/docs/actions/public/sendTransaction.html#account) . const { hash } = await sendTransaction({ ... - request: { - to: 'jxom.eth', - value: BigNumber.from('69420'), - }, + to: 'jxom.eth', + value: 69420n }) **`wait` has been removed from the return type** `wait` has been removed from the return type, favor `waitForTransaction` instead. + import { waitForTransaction } from '@wagmi/core' const { - wait + hash } = await sendTransaction(...) - const receipt = await wait() + const receipt = await waitForTransaction({ hash }) #### `signMessage`[](#signmessage) **`message` no longer accepts a byte array** `message` no longer accepts a byte array, only a string value #### `signTypedData`[](#signtypeddata) **`value` has been renamed to `message`** const signature = await signTypedData({ domain, types, primaryType: 'Mail', - value, + message }) **`primaryType` is now required** The `primaryType` attribute is now required. Aligns closer to EIP-712, and allows consumers to specify an alternative primary type. Previously, Ethers.js did some internal stuff to figure out the primary type. But it's not hard for a consumer to just provide that – and we believe it is more clear. const signature = await signTypedData({ domain, types, + primaryType: 'Mail', message }) #### `waitForTransaction`[](#waitfortransaction) **Renamed `onSpeedUp` to `onReplaced`** const waitForTransaction = await waitForTransaction({ hash: '0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060', - onSpeedUp: (transaction) => console.log(transaction), + onReplaced: (transaction) => console.log(transaction) }) **Return type changed** Now returns a viem [TransactionReceipt](https://github.com/wagmi-dev/viem/blob/136c4022c3ab4020f37333876bed788a111bff47/src/types/transaction.ts#L12) instead of an Ethers `TransactionReceipt`. #### `watchPendingTransactions`[](#watchpendingtransactions) **Callback now returns batched transaction hashes** The callback now returns a batched array of transaction hashes, instead of callback being emitted several times with singular hashes. const unwatch = watchPendingTransactions( {}, - (hash) => console.log(hash), + (hashes) => console.log(hashes[0]), ) #### `watchProvider`[](#watchprovider) **Renamed to `watchPublicClient`** Returns viem [Public Client](https://viem.sh/docs/clients/public.html) instead of ethers `Provider`. - const unwatch = watchProvider({}, (provider) => { ... }) + const unwatch = watchPublicClient({}, (publicClient) => { ... }) #### `watchSigner`[](#watchsigner) **Renamed to `watchWalletClient`** Returns viem [Wallet Client](https://viem.sh/docs/clients/wallet.html) instead of ethers `Signer`. - const unwatch = watchSigner({}, (signer) => { ... }) + const unwatch = watchWalletClient({}, (walletClient) => { ... }) #### `watchWebSocketProvider`[](#watchwebsocketprovider) **Renamed to `watchWebSocketPublicClient`** Returns viem [Public Client](https://viem.sh/docs/clients/public.html) instead of ethers `Provider`. - const unwatch = watchWebSocketProvider({}, (webSocketProvider) => { ... }) + const unwatch = watchWebSocketPublicClient({}, (webSocketPublicClient) => { ... }) #### `writeContract`[](#writecontract) **`wait` has been removed from the return type** `wait` has been removed from the return type, favor `waitForTransaction` instead. + import { waitForTransaction } from '@wagmi/core' const { - wait + hash } = await writeContract(...) - const receipt = await wait() + const receipt = await waitForTransaction({ hash }) **Removed `overrides`** The `overrides` parameter has been removed in favor of top-level parameters. Maps to [viem's `writeContract` parameters](https://viem.sh/docs/contract/writeContract.html#account) . const { config } = await writeContract({ ... - overrides: { - from: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', - value: BigNumber.from('69420'), - }, + account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', + value: 69420n }) #### `watchContractEvent`[](#watchcontractevent) **Callback now returns array of logs** Callback now returns an array of Event Logs (with included decoded args), instead of positional decoded args with the log. const unwatch = watchContractEvent( { address: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e', abi: ensRegistryABI, eventName: 'NewOwner', }, - (node, label, owner) => { + (logs) => { - console.log(node, label, owner) + const { args } = logs[0] + console.log(args.node, args.label, args.owner) }, ) **Removed `once`** The `once` parameter has been removed. Use `unwatch` to cleanup the listener instead. const unwatch = watchContractEvent( { address: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e', abi: ensRegistryABI, eventName: 'NewOwner', - once: true }, (logs) => { const { args } = logs[0] console.log(args.node, args.label, args.owner) + unwatch() }, ) ### `configureChains`[](#configurechains) #### Removed quorum support[](#removed-quorum-support) Removed quorum support: `priority`, `minQuorum` and `targetQuorum` (for now). viem does not support quorum in the [`fallback` Transport](https://viem.sh/docs/clients/transports/fallback.html) yet, but will in the future! ### Connectors[](#connectors) The breaking changes below only applies if you are building a Connector on top of wagmi. #### Renamed `getSigner` to `getWalletClient`[](#renamed-getsigner-to-getwalletclient) The `getSigner` method has been renamed to `getWalletClient`, and also returns [viem's `WalletClient`](https://viem.sh/docs/clients/wallet.html) instead of an Ethers.js `Signer` - async getSigner({ chainId }: { chainId?: number } = {}) { + async getWalletClient({ chainId }: { chainId?: number } = {}) { const [provider, account] = await Promise.all([\ this.getProvider(),\ this.getAccount(),\ ]) + const chain = this.chains.find((x) => x.id === chainId) || this.chains[0] - return new providers.Web3Provider( - provider, - chainId, - ).getSigner(account) + return createWalletClient({ + account, + chain, + transport: custom(provider), + }) } ### Errors[](#errors) #### `ChainDoesNotSupportMulticallError`[](#chaindoesnotsupportmulticallerror) Use [`ChainDoesNotSupportContract` from viem](https://viem.sh/docs/glossary/errors.html#chaindoesnotsupportcontract) instead. #### `ContractMethodDoesNotExistError`[](#contractmethoddoesnotexisterror) Use [`ContractFunctionExecutionError` from viem](https://viem.sh/docs/glossary/errors.html#contractfunctionexecutionerror) instead. #### `ContractMethodNoResultError`[](#contractmethodnoresulterror) Use [`ContractFunctionZeroDataError` from viem](https://viem.sh/docs/glossary/errors.html#contractfunctionzerodataerror) instead. #### `ContractMethodRevertedError`[](#contractmethodrevertederror) Use [`ContractFunctionRevertedError` from viem](https://viem.sh/docs/glossary/errors.html#contractfunctionrevertederror) instead. #### `ContractResultDecodeError`[](#contractresultdecodeerror) Use [`ContractFunctionExecutionError` from viem](https://viem.sh/docs/glossary/errors.html#contractfunctionexecutionerror) instead. #### `ProviderRpcError`[](#providerrpcerror) Use [`ProviderRpcError` from viem](https://viem.sh/docs/glossary/errors.html#providerrpcerror) instead. #### `ResourceUnavailableError`[](#resourceunavailableerror) Use [`ResourceUnavailableRpcError` from viem](https://viem.sh/docs/glossary/errors.html#resourceunavailablerpcerror) instead. 0.10.x Breaking changes[](#010x-breaking-changes) -------------------------------------------------- ### WalletConnectConnector[](#walletconnectconnector) WalletConnect v1 has been sunset and `WalletConnectConnector` now uses WalletConnect v2 by default. wagmi still supports WalletConnect v1 via a [`WalletConnectLegacyConnector`](/core/migration-guide#if-you-are-still-using-walletconnect-v1) , however, it is recommended to migrate to WalletConnect v2. Instructions can be found [here](/core/connectors/walletConnect) . ##### If you are already using WalletConnect v2:[](#if-you-are-already-using-walletconnect-v2) The `version` flag has been omitted, and `qrcode` has been renamed to `showQrModal`. import { WalletConnectConnector } from 'wagmi/connectors/walletConnect' const connector = new WalletConnectConnector({ options: { - version: '2', projectId: '...', - qrcode: true, + showQrModal: true, }, }) [Read more on `WalletConnectConnector`](/core/connectors/walletConnect) ##### If you are still using WalletConnect v1:[](#if-you-are-still-using-walletconnect-v1) ⚠️ You must migrate to the [WalletConnect v2 Connector](/core/connectors/walletConnect) before June 28, after which, the `WalletConnectLegacyConnector` will be removed. -import { WalletConnectConnector } from '@wagmi/core/connectors/walletConnect' +import { WalletConnectLegacyConnector } from '@wagmi/core/connectors/walletConnectLegacy' -const connector = new WalletConnectConnector({ +const connector = new WalletConnectLegacyConnector({ options: { qrcode: true, }, }) [Read more on `WalletConnectLegacyConnector`](/core/connectors/walletConnectLegacy) 0.9.x Breaking changes[](#09x-breaking-changes) ------------------------------------------------ ### Upgrade to typescript@>=4.9.4[](#upgrade-to-typescript494) [TypeScript 5.0](https://github.com/microsoft/TypeScript/issues/51362) is coming soon and has some great features we are excited to bring into wagmi. To prepare for this, update your TypeScript version to 4.9.4 or higher. There are likely no [breaking changes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html#correctness-fixes-and-breaking-changes) if you are coming from `typescript@4.7.x || typescript@4.8.x`. 0.8.x Breaking changes[](#08x-breaking-changes) ------------------------------------------------ ### Chain exports[](#chain-exports) With the introduction of the [`@wagmi/core/chains` entrypoint](/core/chains) , `@wagmi/core` no longer exports the following: * `chain` * `allChains` * `defaultChains` * `defaultL2Chains` * `chainId` * `etherscanBlockExplorers` * `alchemyRpcUrls`, `infuraRpcUrls`, `publicRpcUrls` Read below for migration steps. #### Removed `chain`[](#removed-chain) The `chain` export has been removed. `@wagmi/core` now only exports the `mainnet` & `goerli` chains. If you need to use an alternative chain (`polygon`, `optimism`, etc), you will need to import it from the [`@wagmi/core/chains` entrypoint](/core/chains) . import { - chain configureChains } from '@wagmi/core' + import { mainnet, polygon, optimism } from '@wagmi/core/chains' const { ... } = configureChains( - [chain.mainnet, chain.polygon, chain.optimism], + [mainnet, polygon, optimism], { ... } ) #### Removed `allChains`[](#removed-allchains) The `allChains` export has been removed. If you need a list of all chains, you can utilize [`@wagmi/core/chains` entrypoint](/core/chains) . - import { allChains } from '@wagmi/core' + import * as allChains from '@wagmi/core/chains' const { ... } = configureChains(allChains, ...) #### Removed `defaultChains` & `defaultL2Chains`[](#removed-defaultchains--defaultl2chains) The `defaultChains` & `defaultL2Chains` exports have been removed. If you still need the `defaultChains` or `defaultL2Chains` exports, you can build them yourself: - import { defaultChains } from '@wagmi/core' + import { mainnet, goerli } from '@wagmi/core/chains' + const defaultChains = [mainnet, goerli] > The `defaultChains` export was previously populated with `mainnet` & `goerli`. - import { defaultL2Chains } from '@wagmi/core' + import { + arbitrum, + arbitrumGoerli, + polygon, + polygonMumbai, + optimism, + optimismGoerli + } from '@wagmi/core/chains' + const defaultL2Chains = [\ + arbitrum,\ + arbitrumGoerli,\ + polygon,\ + polygonMumbai,\ + optimism\ + optimismGoerli\ + ] > The `defaultL2Chains` export was previously populated with `arbitrum` & `optimism`. #### Removed `chainId`[](#removed-chainid) The `chainId` export has been removed. You can extract a chain ID from the chain itself. - import { chainId } from '@wagmi/core' + import { mainnet, polygon, optimism } from '@wagmi/core/chains' -const mainnetChainId = chainId.mainnet -const polygonChainId = chainId.polygon -const optimismChainId = chainId.optimism +const mainnetChainId = mainnet.chainId +const polygonChainId = polygon.chainId +const optimismChainId = optimism.chainId #### Removed `etherscanBlockExplorers`[](#removed-etherscanblockexplorers) The `etherscanBlockExplorers` export has been removed. You can extract a block explorer from the chain itself. - import { etherscanBlockExplorers } from '@wagmi/core' + import { mainnet, polygon, optimism } from '@wagmi/core/chains' -const mainnetEtherscanBlockExplorer = etherscanBlockExplorers.mainnet -const polygonEtherscanBlockExplorer = etherscanBlockExplorers.polygon -const optimismEtherscanBlockExplorer = etherscanBlockExplorers.optimism +const mainnetEtherscanBlockExplorer = mainnet.blockExplorers.default +const polygonEtherscanBlockExplorer = polygon.blockExplorers.default +const optimismEtherscanBlockExplorer = optimism.blockExplorers.default #### Removed `alchemyRpcUrls`, `infuraRpcUrls` & `publicRpcUrls`[](#removed-alchemyrpcurls-infurarpcurls--publicrpcurls) The `alchemyRpcUrls`, `infuraRpcUrls` & `publicRpcUrls` exports have been removed. You can extract a RPC URL from the chain itself. - import { alchemyRpcUrls, infuraRpcUrls, publicRpcUrls } from '@wagmi/core' + import { mainnet } from '@wagmi/core/chains' -const mainnetAlchemyRpcUrl = alchemyRpcUrls.mainnet -const mainnetInfuraRpcUrl = infuraRpcUrls.mainnet -const mainnetOptimismRpcUrl = publicRpcUrls.mainnet +const mainnetAlchemyRpcUrl = mainnet.rpcUrls.alchemy +const mainnetInfuraRpcUrl = mainnet.rpcUrls.infura +const mainnetOptimismRpcUrl = mainnet.rpcUrls.optimism ### `Chain` type[](#chain-type) #### RPC URLs[](#rpc-urls) The `rpcUrls` shape has changed to include an array of URLs, and also the transport method (`http` or `webSocket`): type Chain = { ... rpcUrls: { - [key: string]: string + [key: string]: { + http: string[] + webSocket: string[] + } } ... } Note that you will also need to ensure that usage is migrated: - const rpcUrl = mainnet.rpcUrls.alchemy + const rpcUrl = mainnet.rpcUrls.alchemy.http[0] #### Contracts[](#contracts) The `multicall` and `ens` attributes have been moved into the `contracts` object: type Contract = { address: Address blockCreated?: number } type Chain = { ... - multicall: Contract - ens: Contract + contracts: { + multicall3: Contract + ensRegistry: Contract + } ... } Note that you will also need to ensure that usage is migrated: - const multicallContract = mainnet.multicall + const multicallContract = mainnet.contracts.multicall3 ### waitForTransaction[](#waitfortransaction-1) #### Behavioral changes[](#behavioral-changes) `waitForTransaction` will throw an error if the transaction has been reverted or cancelled. #### Configuration changes[](#configuration-changes) Removed the `wait` config option on `waitForTransaction`. Use the transaction `hash` instead. const { data } = await waitForTransaction({ - wait: transaction.wait + hash: transaction.hash }) [Getting Started](/core/getting-started "Getting Started") [TypeScript](/core/typescript "TypeScript") --- # Configuring Chains – @wagmi/core On This Page * [Usage](#usage) * [Multiple RPC Providers](#multiple-rpc-providers) * [Arguments](#arguments) * [chains](#chains) * [providers](#providers) * [Configuration](#configuration) * [batch.multicall (optional)](#batchmulticall-optional) * [pollingInterval (optional)](#pollinginterval-optional) * [rank (optional)](#rank-optional) * [retryCount (optional)](#retrycount-optional) * [retryDelay (optional)](#retrydelay-optional) * [stallTimeout (optional)](#stalltimeout-optional) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9CConfiguring%20Chains%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/core/providers/configuring-chains.en-US.mdx) * Core * Providers * Configuring Chains Configuring Chains ================== The `configureChains` function allows you to configure your chains with RPC Providers such as: Alchemy, Infura, or something else. This means you don't need to worry about defining RPC URLs and chain configuration in your [Connector](/react/connectors/injected#chains-optional) or [Public Client](/core/config#publicclient-optional) . This is managed internally by wagmi. import { configureChains } from '@wagmi/core' Usage[](#usage) ---------------- `configureChains` accepts an array of [chains](/core/chains) and an array of RPC Providers. It returns: * `chains`: to pass to your connector(s) * `publicClient`: to pass to `createConfig` * `webSocketPublicClient`: to optionally pass to `createConfig` import { configureChains, createConfig } from '@wagmi/core' import { mainnet, polygon, optimism } from '@wagmi/core/chains' import { alchemyProvider } from '@wagmi/core/providers/alchemy' import { publicProvider } from '@wagmi/core/providers/public' import { InjectedConnector } from '@wagmi/core/connectors/injected' const { chains, publicClient } = configureChains( [mainnet, polygon, optimism], [alchemyProvider({ apiKey: 'yourAlchemyApiKey' }), publicProvider()], ) const config = createConfig({ autoConnect: true, connectors: [new InjectedConnector({ chains })], publicClient, }) Find a list of supported chains in wagmi [here](/core/chains) . ### Multiple RPC Providers[](#multiple-rpc-providers) The `configureChains` function accepts multiple RPC Providers. This is useful if not all your chains support a single RPC Provider. For example, you may want to use [Alchemy](https://alchemy.com) for Ethereum, and [avax.network](https://avax.network) for Avalanche. `configureChains` wraps the RPC Provider that you provide into viem's [`fallback` Transport](https://viem.sh/docs/clients/transports/fallback.html) , that comes with support for falling back to another RPC Provider if the RPC Provider goes down (e.g. If Infura goes down, we can fall back to Alchemy) import { configureChains } from '@wagmi/core' import { avalanche, polygon } from '@wagmi/core/chains' import { alchemyProvider } from '@wagmi/core/providers/alchemy' import { infuraProvider } from '@wagmi/core/providers/infura' import { publicProvider } from '@wagmi/core/providers/public' const { publicClient } = configureChains( [mainnet, polygon, avalanche], [\ alchemyProvider({ apiKey: 'yourAlchemyApiKey' }),\ infuraProvider({ apiKey: 'yourInfuraApiKey' }),\ publicProvider(),\ ], ) Arguments[](#arguments) ------------------------ ### chains[](#chains) Chains that need to be configured. import { configureChains } from '@wagmi/core' import { mainnet, optimism, polygon } from '@wagmi/core/chains' import { publicProvider } from '@wagmi/core/providers/public' const { chains } = configureChains( [mainnet, optimism, polygon], [publicProvider()], ) ### providers[](#providers) The providers the app supports. If a provider does not support a chain, it will fall back onto the next one in the array. If no RPC URLs are found, `configureChains` will throw an error. import { configureChains } from '@wagmi/core' import { mainnet, optimism, polygon } from '@wagmi/core/chains' import { alchemyProvider } from '@wagmi/core/providers/alchemy' import { publicProvider } from '@wagmi/core/providers/public' const { chains } = configureChains( [mainnet, optimism, polygon], [alchemyProvider({ apiKey: 'yourAlchemyApiKey' }), publicProvider()], ) ### Configuration[](#configuration) ### batch.multicall (optional)[](#batchmulticall-optional) Toggle to enable `eth_call` multicall aggregation. Default: `true`. import { configureChains } from '@wagmi/core' import { mainnet, optimism, polygon } from '@wagmi/core/chains' import { alchemyProvider } from '@wagmi/core/providers/alchemy' import { publicProvider } from '@wagmi/core/providers/public' const { chains } = configureChains( [mainnet, optimism, polygon], [\ alchemyProvider({ apiKey: 'yourAlchemyApiKey' }),\ infuraProvider({ apiKey: 'yourInfuraApiKey' }),\ publicProvider(),\ ], { batch: { multicall: true } }, ) > You can also pass [custom `multicall` options](https://viem.sh/docs/clients/public.html#batch-multicall-batchsize-optional) > . ### pollingInterval (optional)[](#pollinginterval-optional) The frequency in milliseconds at which the provider polls. Defaults to `4000`. import { configureChains } from '@wagmi/core' import { mainnet, optimism, polygon } from '@wagmi/core/chains' import { alchemyProvider } from '@wagmi/core/providers/alchemy' import { publicProvider } from '@wagmi/core/providers/public' const { chains } = configureChains( [mainnet, optimism, polygon], [\ alchemyProvider({ apiKey: 'yourAlchemyApiKey' }),\ infuraProvider({ apiKey: 'yourInfuraApiKey' }),\ publicProvider(),\ ], { pollingInterval: 10_000 }, ) #### rank (optional)[](#rank-optional) Whether or not to automatically rank the RPC Providers based on their latency & stability. Default: `false`. import { configureChains } from '@wagmi/core' import { mainnet, optimism, polygon } from '@wagmi/core/chains' import { alchemyProvider } from '@wagmi/core/providers/alchemy' import { publicProvider } from '@wagmi/core/providers/public' const { chains } = configureChains( [mainnet, optimism, polygon], [\ alchemyProvider({ apiKey: 'yourAlchemyApiKey' }),\ infuraProvider({ apiKey: 'yourInfuraApiKey' }),\ publicProvider(),\ ], { rank: true }, ) > You can also pass [custom `rank` options](https://viem.sh/docs/clients/transports/fallback.html#rank-interval-optional) > . #### retryCount (optional)[](#retrycount-optional) The max number of times to retry when a request fails. Default: `3`. > Note: wagmi will first try all the RPC Providers before retrying. import { configureChains } from '@wagmi/core' import { mainnet, optimism, polygon } from '@wagmi/core/chains' import { alchemyProvider } from '@wagmi/core/providers/alchemy' import { publicProvider } from '@wagmi/core/providers/public' const { chains } = configureChains( [mainnet, optimism, polygon], [\ alchemyProvider({ apiKey: 'yourAlchemyApiKey' }),\ infuraProvider({ apiKey: 'yourInfuraApiKey' }),\ publicProvider(),\ ], { retryCount: 5 }, ) #### retryDelay (optional)[](#retrydelay-optional) The base delay (in ms) between retries. By default, the RPC Provider will use [exponential backoff](https://en.wikipedia.org/wiki/Exponential_backoff) (`~~(1 << count) \* retryDelay`), which means the time between retries is not constant. import { configureChains } from '@wagmi/core' import { mainnet, optimism, polygon } from '@wagmi/core/chains' import { alchemyProvider } from '@wagmi/core/providers/alchemy' import { publicProvider } from '@wagmi/core/providers/public' const { chains } = configureChains( [mainnet, optimism, polygon], [\ alchemyProvider({ apiKey: 'yourAlchemyApiKey' }),\ infuraProvider({ apiKey: 'yourInfuraApiKey' }),\ publicProvider(),\ ], { retryDelay: 150 }, ) #### stallTimeout (optional)[](#stalltimeout-optional) The timeout in milliseconds after which another provider will be attempted. import { configureChains } from '@wagmi/core' import { mainnet, optimism, polygon } from '@wagmi/core/chains' import { alchemyProvider } from '@wagmi/core/providers/alchemy' import { publicProvider } from '@wagmi/core/providers/public' const { chains } = configureChains( [mainnet, optimism, polygon], [\ alchemyProvider({ apiKey: 'yourAlchemyApiKey' }),\ infuraProvider({ apiKey: 'yourInfuraApiKey' }),\ publicProvider(),\ ], { stallTimeout: 5000 }, ) [Chains](/core/chains "Chains") [Alchemy](/core/providers/alchemy "Alchemy") --- # Alchemy – @wagmi/core On This Page * [Usage](#usage) * [Return Value](#return-value) * [Configuration](#configuration) * [apiKey](#apikey) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9CAlchemy%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/core/providers/alchemy.en-US.mdx) * Core * Providers * Alchemy Alchemy ======= The `alchemyProvider` configures the chains with Alchemy RPC URLs. import { alchemyProvider } from '@wagmi/core/providers/alchemy' Usage[](#usage) ---------------- import { configureChains } from '@wagmi/core' import { mainnet, optimism, polygon } from '@wagmi/core/chains' import { alchemyProvider } from '@wagmi/core/providers/alchemy' const { chains, publicClient } = configureChains( [mainnet, optimism, polygon], [alchemyProvider({ apiKey: 'yourAlchemyApiKey' })], ) Note: The above example is using chains from [`@wagmi/core/chains`](/core/chains#wagmicorechains) . Return Value[](#return-value) ------------------------------ { chains: Chain[], publicClient: PublicClient, webSocketPublicClient: PublicClient } Configuration[](#configuration) -------------------------------- ### apiKey[](#apikey) Your Alchemy API key from the [Alchemy Dashboard](https://dashboard.alchemyapi.io/) . import { configureChains, mainnet } from '@wagmi/core' import { alchemyProvider } from '@wagmi/core/providers/alchemy' const { chains, publicClient } = configureChains( [mainnet], [alchemyProvider({ apiKey: 'yourAlchemyApiKey' })], ) [Configuring Chains](/core/providers/configuring-chains "Configuring Chains") [Infura](/core/providers/infura "Infura") --- # Infura – @wagmi/core On This Page * [Usage](#usage) * [Return Value](#return-value) * [Configuration](#configuration) * [apiKey](#apikey) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9CInfura%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/core/providers/infura.en-US.mdx) * Core * Providers * Infura Infura ====== The `infuraProvider` configures the chains with Infura RPC URLs. import { infuraProvider } from '@wagmi/core/providers/infura' Usage[](#usage) ---------------- import { configureChains } from '@wagmi/core' import { mainnet, polygon } from '@wagmi/core/chains' import { infuraProvider } from '@wagmi/core/providers/infura' const { chains, publicClient } = configureChains( [mainnet, polygon], [infuraProvider({ apiKey: 'yourInfuraApiKey' })], ) Note: The above example is using chains from [`@wagmi/core/chains`](/core/chains#wagmicorechains) . Return Value[](#return-value) ------------------------------ { chains: Chain[], publicClient: PublicClient, webSocketPublicClient: PublicClient } Configuration[](#configuration) -------------------------------- ### apiKey[](#apikey) Your Infura API key from the [Infura Dashboard](https://infura.io/login) . import { configureChains } from '@wagmi/core' import { mainnet, polygon } from '@wagmi/core/chains' import { infuraProvider } from '@wagmi/core/providers/infura' const { chains, publicClient } = configureChains( [mainnet, polygon], [infuraProvider({ apiKey: 'yourInfuraApiKey' })], ) [Alchemy](/core/providers/alchemy "Alchemy") [Public](/core/providers/public "Public") --- # Public – @wagmi/core On This Page * [Usage](#usage) * [Return Value](#return-value) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9CPublic%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/core/providers/public.en-US.mdx) * Core * Providers * Public Public ====== The `publicProvider` configures the chains with a public RPC URL. import { publicProvider } from '@wagmi/core/providers/public' Usage[](#usage) ---------------- import { configureChains } from '@wagmi/core' import { mainnet, polygon } from '@wagmi/core/chains' import { publicProvider } from '@wagmi/core/providers/public' const { chains, publicClient } = configureChains( [mainnet, polygon], [publicProvider()], ) Note: The above example is using chains from [`@wagmi/core/chains`](/core/chains#wagmicorechains) . ⚠️ Only having `publicProvider` in your providers will make the chain use the public RPC URL which could lead to rate-limiting. It is recommended to also include another provider in your list (such as: `alchemyProvider`, `infuraProvider` or `jsonRpcProvider`). Return Value[](#return-value) ------------------------------ { chains: Chain[], publicClient: PublicClient, webSocketPublicClient: PublicClient } [Infura](/core/providers/infura "Infura") [JSON RPC](/core/providers/jsonRpc "JSON RPC") --- # JSON RPC – @wagmi/core On This Page * [Usage](#usage) * [Return Value](#return-value) * [Configuration](#configuration) * [rpc](#rpc) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9CJSON%20RPC%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/core/providers/jsonRpc.en-US.mdx) * Core * Providers * JSON RPC JSON RPC ======== The `jsonRpcProvider` configures the chains with the RPC URLs that you specify. import { jsonRpcProvider } from '@wagmi/core/providers/jsonRpc' Usage[](#usage) ---------------- import { configureChains } from '@wagmi/core' import { mainnet, polygon } from '@wagmi/core/chains' import { jsonRpcProvider } from '@wagmi/core/providers/jsonRpc' const { chains, publicClient } = configureChains( [mainnet, polygon], [\ jsonRpcProvider({\ rpc: (chain) => ({\ http: `https://${chain.id}.example.com`,\ }),\ }),\ ], ) Note: The above example is using chains from [`@wagmi/core/chains`](/core/chains#wagmicorechains) . Return Value[](#return-value) ------------------------------ { chains: Chain[], publicClient: PublicClient, webSocketPublicClient: PublicClient } Configuration[](#configuration) -------------------------------- ### rpc[](#rpc) Accepts a function which provides the `chain` and expects to receive a `http` URL and optionally a `webSocket` URL. import { configureChains } from '@wagmi/core' import { mainnet, polygon } from '@wagmi/core/chains' import { jsonRpcProvider } from '@wagmi/core/providers/jsonRpc' const { chains, publicClient } = configureChains( [mainnet, polygon], [\ jsonRpcProvider({\ rpc: (chain) => ({\ http: `https://${chain.id}.example.com`,\ webSocket: `wss://${chain.id}.example.com`,\ }),\ }),\ ], ) [Public](/core/providers/public "Public") [Injected](/core/connectors/injected "Injected") --- # Injected – @wagmi/core On This Page * [Usage](#usage) * [Configuration](#configuration) * [chains (optional)](#chains-optional) * [options (optional)](#options-optional) * [getProvider](#getprovider) * [name](#name) * [shimDisconnect](#shimdisconnect) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9CInjected%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/core/connectors/injected.en-US.mdx) * Core * Connectors * Injected Injected ======== The `InjectedConnector` supports wallets that inject an Ethereum Provider into the browser or window. The MetaMask browser extension is the most popular example of this. import { InjectedConnector } from '@wagmi/core' Usage[](#usage) ---------------- import { InjectedConnector } from '@wagmi/core' const connector = new InjectedConnector() Injected wallets can set up custom name mappings in wagmi. You can [see the full list and add to it here](https://github.com/wagmi-dev/wagmi/blob/main/packages/connectors/src/utils/getInjectedName.ts) . By default, "Injected" is the name for unmapped wallets. Configuration[](#configuration) -------------------------------- ### chains (optional)[](#chains-optional) Chains supported by app. Defaults to `defaultChains`. import { mainnet, optimism, polygon } from '@wagmi/core/chains' import { InjectedConnector } from '@wagmi/core' const connector = new InjectedConnector({ chains: [mainnet, optimism, polygon], }) Note: The above example is using chains from [`@wagmi/core/chains`](/core/chains#wagmicorechains) . ### options (optional)[](#options-optional) Options for configuring the connector. import { InjectedConnector } from '@wagmi/core' const connector = new InjectedConnector({ options: { shimDisconnect: true, }, }) #### getProvider[](#getprovider) Function for selecting the [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193) Ethereum Provider to target. Defaults to `() => typeof window !== 'undefined' ? window.ethereum : undefined`. import { InjectedConnector } from '@wagmi/core' const connector = new InjectedConnector({ options: { name: 'My Injected Wallet', getProvider: () => typeof window !== 'undefined' ? window.myInjectedWallet : undefined, }, }) #### name[](#name) Name of connector instead of trying to detect from browser. import { InjectedConnector } from '@wagmi/core' const connector = new InjectedConnector({ options: { name: 'Injected', }, }) `name` can also be set to a function, which has the `detectedName` as the first parameter. `detectedName` can be a list of multiple detected names if there are multiple injected wallets detected. import { InjectedConnector } from '@wagmi/core' const connector = new InjectedConnector({ options: { name: (detectedName) => `Injected (${ typeof detectedName === 'string' ? detectedName : detectedName.join(', ') })`, }, }) #### shimDisconnect[](#shimdisconnect) MetaMask and other injected providers [do not support programmatic disconnect](https://github.com/MetaMask/metamask-extension/issues/10353) . This flag simulates the disconnect behavior by keeping track of connection status in storage. Defaults to `true`. import { InjectedConnector } from '@wagmi/core' const connector = new InjectedConnector({ options: { shimDisconnect: false, }, }) [JSON RPC](/core/providers/jsonRpc "JSON RPC") [Coinbase Wallet](/core/connectors/coinbaseWallet "Coinbase Wallet") --- # Coinbase Wallet – @wagmi/core On This Page * [Usage](#usage) * [Configuration](#configuration) * [chains (optional)](#chains-optional) * [options](#options) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9CCoinbase%20Wallet%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/core/connectors/coinbaseWallet.en-US.mdx) * Core * Connectors * Coinbase Wallet Coinbase Wallet =============== The `CoinbaseWalletConnector` supports connecting with Coinbase Wallet using the [Coinbase Wallet SDK](https://docs.cloud.coinbase.com/wallet-sdk/docs) . import { CoinbaseWalletConnector } from '@wagmi/core/connectors/coinbaseWallet' Usage[](#usage) ---------------- import { CoinbaseWalletConnector } from '@wagmi/core/connectors/coinbaseWallet' const connector = new CoinbaseWalletConnector({ options: { appName: 'wagmi.sh', jsonRpcUrl: 'https://eth-mainnet.alchemyapi.io/v2/yourAlchemyId', }, }) Configuration[](#configuration) -------------------------------- ### chains (optional)[](#chains-optional) Chains supported by app. Defaults to `defaultChains`. import { mainnet, optimism, polygon } from '@wagmi/core/chains' import { CoinbaseWalletConnector } from '@wagmi/core/connectors/coinbaseWallet' const connector = new CoinbaseWalletConnector({ chains: [mainnet, optimism, polygon], options: { appName: 'wagmi.sh', jsonRpcUrl: 'https://eth-mainnet.alchemyapi.io/v2/yourAlchemyId', }, }) Note: The above example is using chains from [`@wagmi/core/chains`](/core/chains#wagmicorechains) . ### options[](#options) Options to pass to the [Coinbase Wallet SDK](https://docs.cloud.coinbase.com/wallet-sdk/docs) . import { CoinbaseWalletConnector } from '@wagmi/core/connectors/coinbaseWallet' const connector = new CoinbaseWalletConnector({ options: { appName: 'wagmi.sh', jsonRpcUrl: 'https://eth-mainnet.alchemyapi.io/v2/yourAlchemyId', }, }) [Injected](/core/connectors/injected "Injected") [MetaMask](/core/connectors/metaMask "MetaMask") --- # MetaMask – @wagmi/core On This Page * [Usage](#usage) * [Configuration](#configuration) * [chains (optional)](#chains-optional) * [options (optional)](#options-optional) * [shimDisconnect](#shimdisconnect) * [UNSTABLE\_shimOnConnectSelectAccount](#unstable_shimonconnectselectaccount) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9CMetaMask%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/core/connectors/metaMask.en-US.mdx) * Core * Connectors * MetaMask MetaMask ======== The `MetaMaskConnector` supports connecting with MetaMask. import { MetaMaskConnector } from '@wagmi/core/connectors/metaMask' Usage[](#usage) ---------------- import { MetaMaskConnector } from '@wagmi/core/connectors/metaMask' const connector = new MetaMaskConnector() Configuration[](#configuration) -------------------------------- ### chains (optional)[](#chains-optional) Chains supported by app. Defaults to `defaultChains`. import { mainnet, optimism, polygon } from '@wagmi/core/chains' import { MetaMaskConnector } from '@wagmi/core/connectors/metaMask' const connector = new MetaMaskConnector({ chains: [mainnet, optimism, polygon], }) Note: The above example is using chains from [`@wagmi/core/chains`](/core/chains#wagmicorechains) . ### options (optional)[](#options-optional) Options for configuring the connector. import { MetaMaskConnector } from '@wagmi/core/connectors/metaMask' const connector = new MetaMaskConnector({ options: { shimDisconnect: true, }, }) #### shimDisconnect[](#shimdisconnect) MetaMask [does not support programmatic disconnect](https://github.com/MetaMask/metamask-extension/issues/10353) . This flag simulates the disconnect behavior by keeping track of connection status in storage. Defaults to `true`. import { MetaMaskConnector } from '@wagmi/core/connectors/metaMask' const connector = new MetaMaskConnector({ options: { shimDisconnect: false, }, }) #### UNSTABLE\_shimOnConnectSelectAccount[](#unstable_shimonconnectselectaccount) ⚠️ This is an experimental feature. It's stable enough to show up in the docs, but should be used with care. If you have any feedback, [create a discussion](https://github.com/wagmi-dev/wagmi/discussions) . While "disconnected" with `shimDisconnect`, allows user to select a different MetaMask account (than the currently connected account) when trying to connect. Defaults to `false`. import { MetaMaskConnector } from '@wagmi/core/connectors/metaMask' const connector = new MetaMaskConnector({ options: { shimDisconnect: true, UNSTABLE_shimOnConnectSelectAccount: true, }, }) [Coinbase Wallet](/core/connectors/coinbaseWallet "Coinbase Wallet") [Mock](/core/connectors/mock "Mock") --- # Mock – @wagmi/core On This Page * [Usage](#usage) * [Configuration](#configuration) * [chains (optional)](#chains-optional) * [options](#options) * [chainId (optional)](#chainid-optional) * [flags (optional)](#flags-optional) * [walletClient](#walletclient) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9CMock%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/core/connectors/mock.en-US.mdx) * Core * Connectors * Mock Mock ==== The `MockConnector` is a mocked `Connector` implementation useful for things like testing. import { MockConnector } from '@wagmi/core/connectors/mock' Usage[](#usage) ---------------- import { MockConnector } from '@wagmi/core/connectors/mock' const connector = new MockConnector() Configuration[](#configuration) -------------------------------- ### chains (optional)[](#chains-optional) Chains supported by app. Defaults to `defaultChains`. import { MockConnector } from '@wagmi/core/connectors/mock' import { mainnet, optimism } from '@wagmi/core/chains' const connector = new MockConnector({ chains: [mainnet, optimism], }) ### options[](#options) Options for configuring the connector. import { MockConnector } from '@wagmi/core/connectors/mock' import { createWalletClient } from 'viem' const connector = new MockConnector({ options: { walletClient: createWalletClient(…), }, }) #### chainId (optional)[](#chainid-optional) Chain ID to use for the connector. Defaults to first chain in `chains`. import { MockConnector } from '@wagmi/core/connectors/mock' import { mainnet } from '@wagmi/core/chains' import { createWalletClient } from 'viem' const connector = new MockConnector({ options: { chainId: mainnet.id, walletClient: createWalletClient(…), }, }) #### flags (optional)[](#flags-optional) Flags to simulate specific behavior of the connector. import { MockConnector } from '@wagmi/core/connectors/mock' import { mainnet } from '@wagmi/core/chains' import { createWalletClient } from 'viem' const connector = new MockConnector({ options: { flags: { failConnect: true, }, walletClient: createWalletClient(…), }, }) | Name | Type | Description | | --- | --- | --- | | `isAuthorized` | `boolean` | Turns on authorized status to connector allowing autoconnect behavior to work. | | `failConnect` | `boolean` | Throws an error when attempting to connect. | | `failSwitchChain` | `boolean` | Throws an error when attempting to switch chains. | | `noSwitchChain` | `boolean` | Disables the ability to switch chains. | #### walletClient[](#walletclient) [Wallet Client](https://viem.sh/docs/clients/wallet.html) to initialize connector with. import { MockConnector } from '@wagmi/core/connectors/mock' import { mainnet } from '@wagmi/core/chains' import { createWalletClient } from 'viem' const connector = new MockConnector({ options: { walletClient: createWalletClient(…), }, }) [MetaMask](/core/connectors/metaMask "MetaMask") [Safe](/core/connectors/safe "Safe") --- # Safe Wallet – @wagmi/core On This Page * [Usage](#usage) * [Configuration](#configuration) * [chains (optional)](#chains-optional) * [options (optional)](#options-optional) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9CSafe%20Wallet%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/core/connectors/safe.en-US.mdx) * Core * Connectors * Safe Safe Wallet =========== The `SafeConnector` supports connecting with Safe Wallet using the [Safe Apps SDK](https://github.com/safe-global/safe-apps-sdk) . import { SafeConnector } from '@wagmi/connectors/safe' Usage[](#usage) ---------------- import { SafeConnector } from '@wagmi/connectors/safe' const connector = new SafeConnector({ chains, options: { allowedDomains: [/gnosis-safe.io$/, /app.safe.global$/], debug: false, }, }) Configuration[](#configuration) -------------------------------- ### chains (optional)[](#chains-optional) Chains supported by app. Defaults to `defaultChains`. import { SafeConnector } from '@wagmi/core/connectors/safe' import { mainnet, optimism } from '@wagmi/core/chains' const connector = new SafeConnector({ chains: [mainnet, optimism], options: { allowedDomains: [/gnosis-safe.io$/, /app.safe.global$/], debug: false, }, }) Note: The above example is using chains from [`@wagmi/core/chains` entrypoint](/react/chains#wagmicorechains) . ### options (optional)[](#options-optional) Options to pass to the [Safe Apps SDK](https://github.com/safe-global/safe-apps-sdk/tree/main/packages/safe-apps-sdk) . For the most up-to-date information on the available options, please refer to the Safe Apps SDK documentation. import { SafeConnector } from '@wagmi/core/connectors/safe' import { mainnet, optimism } from '@wagmi/core/chains' const connector = new SafeConnector({ chains: [mainnet, optimism], options: { allowedDomains: [/gnosis-safe.io$/, /app.safe.global$/], debug: false, }, }) [Mock](/core/connectors/mock "Mock") [WalletConnect](/core/connectors/walletConnect "WalletConnect") --- # WalletConnect – @wagmi/core On This Page * [Usage](#usage) * [Configuration](#configuration) * [chains (optional)](#chains-optional) * [options](#options) * [projectId](#projectid) * [isNewChainsStale (optional)](#isnewchainsstale-optional) * [metadata (optional)](#metadata-optional) * [showQrModal (optional)](#showqrmodal-optional) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9CWalletConnect%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/core/connectors/walletConnect.en-US.mdx) * Core * Connectors * WalletConnect WalletConnect ============= The `WalletConnectConnector` uses WalletConnect v2 by default and wraps the [WalletConnect Ethereum Provider](https://walletconnect.com) and supports its configuration options. This is a great option for adding support for many wallets to your app. import { WalletConnectConnector } from '@wagmi/core/connectors/walletConnect' Usage[](#usage) ---------------- To get started with Wallet Connect v2, you will need to retrieve a Project ID. You can find your Project ID [here](https://cloud.walletconnect.com/sign-in) . import { WalletConnectConnector } from '@wagmi/core/connectors/walletConnect' const connector = new WalletConnectConnector({ options: { projectId: '...', }, }) Configuration[](#configuration) -------------------------------- ### chains (optional)[](#chains-optional) Chains supported by app. Defaults to `defaultChains`. import { mainnet, optimism, polygon } from '@wagmi/core/chains' import { WalletConnectConnector } from '@wagmi/core/connectors/walletConnect' const connector = new WalletConnectConnector({ chains: [mainnet, optimism, polygon], options: { projectId: '...', }, }) * The above example is using chains from [`@wagmi/core/chains`](/core/chains#wagmicorechains) . * Upon connection, the connector will connect to the previously connected chain unless otherwise specified by a [`chainId` config on useConnect](/core/hooks/useConnect#chainid-optional) . ### options[](#options) #### projectId[](#projectid) WalletConnect Cloud Project ID. You can find your Project ID [here](https://cloud.walletconnect.com/sign-in) . import { WalletConnectConnector } from '@wagmi/core/connectors/walletConnect' const connector = new WalletConnectConnector({ options: { projectId: '...', }, }) #### isNewChainsStale (optional)[](#isnewchainsstale-optional) Determines whether or not new chains added to `chains` should be considered as stale. Defaults to `true`. import { WalletConnectConnector } from '@wagmi/core/connectors/walletConnect' const connector = new WalletConnectConnector({ options: { projectId: '...', isNewChainsStale: false, }, }) What is a stale chain & what does this flag do? If a new chain is added to your previously existing `chains`, this flag will determine if that chain should be considered as stale. A stale chain is a chain that WalletConnect has yet to establish a relationship with (ie. the user has not approved or rejected the chain). Preface: Whereas WalletConnect v1 supported dynamic chain switching, WalletConnect v2 requires the user to pre-approve a set of chains up-front. This comes with consequent UX nuances (see below) when a user tries to switch to a chain that they have not approved. This flag mainly affects the behavior when a wallet does not support dynamic chain authorization with WalletConnect v2. If `true` (default), the new chain will be treated as a stale chain. If the user has yet to establish a relationship (approved/rejected) with this chain in their WalletConnect session, the connector will disconnect upon the dapp auto-connecting, and the user will have to reconnect to the dapp (revalidate the chain) in order to approve the newly added chain. This is the default behavior to avoid an unexpected error upon switching chains which may be a confusing user experience (ie. the user will not know they have to reconnect unless the dapp handles these types of errors). If `false`, the new chain will be treated as a validated chain. This means that if the user has yet to establish a relationship with the chain in their WalletConnect session, wagmi will successfully auto-connect the user. This comes with the trade-off that the connector will throw an error when attempting to switch to the unapproved chain. This may be useful in cases where a dapp constantly modifies their configured chains, and they do not want to disconnect the user upon auto-connecting. If the user decides to switch to the unapproved chain, it is important that the dapp handles this error and prompts the user to reconnect to the dapp in order to approve the newly added chain. #### metadata (optional)[](#metadata-optional) Metadata for your app. [See more](https://docs.walletconnect.com/2.0/advanced/providers/ethereum#initialization) import { WalletConnectConnector } from '@wagmi/core/connectors/walletConnect' const connector = new WalletConnectConnector({ options: { projectId: '...', metadata: { name: 'wagmi', description: 'my wagmi app', url: 'https://wagmi.sh', icons: ['https://wagmi.sh/icon.png'], }, }, }) #### showQrModal (optional)[](#showqrmodal-optional) Whether or not to show the QR Code Modal upon connection. [See more](https://docs.walletconnect.com/2.0/advanced/providers/ethereum#initialization) . Defaults to `true`. import { WalletConnectConnector } from '@wagmi/core/connectors/walletConnect' const connector = new WalletConnectConnector({ options: { projectId: '...', showQrModal: false, }, }) [Safe](/core/connectors/safe "Safe") [WalletConnect Legacy](/core/connectors/walletConnectLegacy "WalletConnect Legacy") --- # WalletConnectLegacy – @wagmi/core On This Page * [Usage](#usage) * [Configuration](#configuration) * [chains (optional)](#chains-optional) * [options](#options) * [projectId (optional)](#projectid-optional) * [Other options](#other-options) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9CWalletConnectLegacy%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/core/connectors/walletConnectLegacy.en-US.mdx) * Core * Connectors * WalletConnect Legacy 🚫 WalletConnect v1 has been sunset. You must migrate to the [WalletConnect v2 Connector](/core/connectors/walletConnect) before June 28, after which, this Connector will be removed. WalletConnect Legacy ==================== The `WalletConnectLegacyConnector` uses WallectConnect v1 by default and wraps the [WalletConnect Ethereum Provider](https://walletconnect.com) and supports its configuration options. This is a great option for adding support for many wallets to your app. import { WalletConnectLegacyConnector } from '@wagmi/core/connectors/walletConnectLegacy' Usage[](#usage) ---------------- import { WalletConnectLegacyConnector } from '@wagmi/core/connectors/walletConnectLegacy' const connector = new WalletConnectLegacyConnector({ options: { qrcode: true, }, }) Configuration[](#configuration) -------------------------------- ### chains (optional)[](#chains-optional) Chains supported by app. Defaults to `defaultChains`. import { mainnet, optimism, polygon } from '@wagmi/core/chains' import { WalletConnectLegacyConnector } from '@wagmi/core/connectors/walletConnectLegacy' const connector = new WalletConnectLegacyConnector({ chains: [mainnet, optimism, polygon], options: { qrcode: true, }, }) * The above example is using chains from [`@wagmi/core/chains`](/core/chains#wagmicorechains) . * Upon connection, the connector will connect to the previously connected chain unless otherwise specified by a [`chainId` config on useConnect](/core/hooks/useConnect#chainid-optional) . ### options[](#options) #### projectId (optional)[](#projectid-optional) WalletConnect Cloud Project ID. Required for WalletConnect v2. You can find your Project ID [here](https://cloud.walletconnect.com/sign-in) . import { WalletConnectLegacyConnector } from '@wagmi/core/connectors/walletConnectLegacy' const connector = new WalletConnectLegacyConnector({ options: { qrcode: true, projectId: '...', }, }) #### Other options[](#other-options) You can pass through options supported by the [WalletConnect v1 `WalletConnectProvider`](https://github.com/WalletConnect/walletconnect-monorepo/blob/v1.0/packages/helpers/types/index.d.ts#L300-L314) or the [WalletConnect v2 `UniversalProvider`](https://github.com/WalletConnect/walletconnect-monorepo/blob/3f0f22b9b85294caed60cdf74f61363ce5ce686b/providers/universal-provider/src/types/misc.ts#L8-L16) : import { WalletConnectLegacyConnector } from '@wagmi/core/connectors/walletConnectLegacy' const connector = new WalletConnectLegacyConnector({ options: { qrcode: true, rpc: { 1: 'https://eth-mainnet.alchemyapi.io/v2/yourAlchemyId', }, }, }) [WalletConnect](/core/connectors/walletConnect "WalletConnect") [connect](/core/actions/connect "connect") --- # disconnect – @wagmi/core On This Page * [Usage](#usage) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9Cdisconnect%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/core/actions/disconnect.en-US.mdx) * Core * Actions * disconnect disconnect ========== Action for disconnecting the connected account. import { disconnect } from '@wagmi/core' Usage[](#usage) ---------------- import { disconnect } from '@wagmi/core' await disconnect() [connect](/core/actions/connect "connect") [fetchBalance](/core/actions/fetchBalance "fetchBalance") --- # connect – @wagmi/core On This Page * [Usage](#usage) * [Return Value](#return-value) * [Configuration](#configuration) * [chainId (optional)](#chainid-optional) * [connector](#connector) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9Cconnect%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/core/actions/connect.en-US.mdx) * Core * Actions * connect connect ======= Action for connecting to account with connectors. import { connect } from '@wagmi/core' Usage[](#usage) ---------------- import { connect } from '@wagmi/core' import { InjectedConnector } from '@wagmi/core/connectors/injected' const result = await connect({ connector: new InjectedConnector(), }) Return Value[](#return-value) ------------------------------ { address: `0x${string}` chain: { id: number unsupported?: boolean } connector: Connector } Configuration[](#configuration) -------------------------------- ### chainId (optional)[](#chainid-optional) Chain ID to connect. import { connect } from '@wagmi/core' import { optimism } from '@wagmi/core/chains' import { InjectedConnector } from '@wagmi/core/connectors/injected' const result = await connect({ chainId: optimism.id, connector: new InjectedConnector(), }) Note: The above example is using the `optimism` chain from [`@wagmi/core/chains`](/core/chains#wagmicorechains) . ### connector[](#connector) Connector to use for connecting wallet. import { connect, InjectedConnector } from '@wagmi/core' const result = await connect({ connector: new InjectedConnector(), }) [WalletConnect Legacy](/core/connectors/walletConnectLegacy "WalletConnect Legacy") [disconnect](/core/actions/disconnect "disconnect") --- # fetchBalance – @wagmi/core On This Page * [Usage](#usage) * [Return Value](#return-value) * [Configuration](#configuration) * [address](#address) * [chainId (optional)](#chainid-optional) * [formatUnits (optional)](#formatunits-optional) * [token (optional)](#token-optional) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9CfetchBalance%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/core/actions/fetchBalance.en-US.mdx) * Core * Actions * fetchBalance fetchBalance ============ Action for fetching balance information for Ethereum or ERC-20 tokens. This is a wrapper around viem's [`getBalance`](https://viem.sh/docs/actions/public/getBalance.html) . import { fetchBalance } from '@wagmi/core' Usage[](#usage) ---------------- import { fetchBalance } from '@wagmi/core' const balance = await fetchBalance({ address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', }) Return Value[](#return-value) ------------------------------ { decimals: number formatted: string symbol: string value: bigint } Configuration[](#configuration) -------------------------------- ### address[](#address) Address to fetch balance for. import { fetchBalance } from '@wagmi/core' const balance = await fetchBalance({ address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', }) ### chainId (optional)[](#chainid-optional) Force a specific chain id for the request. The @wagmi/core `Client`'s `publicClient` must be set up as a [chain-aware function](/core/config#publicclient-optional) for this to work correctly. import { fetchBalance } from '@wagmi/core' const balance = await fetchBalance({ address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', chainId: 1, }) ### formatUnits (optional)[](#formatunits-optional) Formats balance. Defaults to `ether` or `token`'s decimal value. import { fetchBalance } from '@wagmi/core' const balance = await fetchBalance({ address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', formatUnits: 'gwei', }) ### token (optional)[](#token-optional) Address for ERC-20 token. If `token` is provided, action fetches token balance instead of Ethereum balance. For example, we can fetch `0xA0Cf798816D4b9b9866b5330EEa46a18382f251e`'s current [$UNI](https://etherscan.io/address/0x1f9840a85d5af5bf1d1762f925bdaddc4201f984) balance. import { fetchBalance } from '@wagmi/core' const balance = await fetchBalance({ address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', token: '0x1f9840a85d5af5bf1d1762f925bdaddc4201f984', }) [disconnect](/core/actions/disconnect "disconnect") [fetchBlockNumber](/core/actions/fetchBlockNumber "fetchBlockNumber") --- # fetchBlockNumber – @wagmi/core On This Page * [Usage](#usage) * [Return Value](#return-value) * [Configuration](#configuration) * [chainId (optional)](#chainid-optional) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9CfetchBlockNumber%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/core/actions/fetchBlockNumber.en-US.mdx) * Core * Actions * fetchBlockNumber fetchBlockNumber ================ Action for fetching the current block number. This is a wrapper around viem's [`getBlockNumber`](https://viem.sh/docs/actions/public/getBlockNumber.html) . import { fetchBlockNumber } from '@wagmi/core' Usage[](#usage) ---------------- import { fetchBlockNumber } from '@wagmi/core' const blockNumber = await fetchBlockNumber() Return Value[](#return-value) ------------------------------ bigint Configuration[](#configuration) -------------------------------- ### chainId (optional)[](#chainid-optional) Force a specific chain id for the request. The wagmi `Client`'s `publicClient` must be set up as a [chain-aware function](/core/config#publicclient-optional) for this to work correctly. import { fetchBlockNumber } from '@wagmi/core' const blockNumber = fetchBlockNumber({ chainId: 1, }) [fetchBalance](/core/actions/fetchBalance "fetchBalance") [fetchEnsAddress](/core/actions/fetchEnsAddress "fetchEnsAddress") --- # fetchEnsAddress – @wagmi/core On This Page * [Usage](#usage) * [Return Value](#return-value) * [Configuration](#configuration) * [name](#name) * [chainId (optional)](#chainid-optional) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9CfetchEnsAddress%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/core/actions/fetchEnsAddress.en-US.mdx) * Core * Actions * fetchEnsAddress fetchEnsAddress =============== Action for fetching address for ENS name. This is a wrapper around viem's [`getEnsAddress`](https://viem.sh/docs/ens/actions/getEnsAddress.html) . import { fetchEnsAddress } from '@wagmi/core' Usage[](#usage) ---------------- import { fetchEnsAddress } from '@wagmi/core' const address = await fetchEnsAddress({ name: 'awkweb.eth', }) Return Value[](#return-value) ------------------------------ string Configuration[](#configuration) -------------------------------- ### name[](#name) ENS name to fetch address for. import { fetchEnsAddress } from '@wagmi/core' const address = await fetchEnsAddress({ name: 'moxey.eth', }) ### chainId (optional)[](#chainid-optional) Force a specific chain id for the request. The wagmi `Client`'s `publicClient` must be set up as a [chain-aware function](/core/config#publicclient-optional) for this to work correctly. import { fetchEnsAddress } from '@wagmi/core' const address = await fetchEnsAddress({ name: 'awkweb.eth', chainId: 1, }) [fetchBlockNumber](/core/actions/fetchBlockNumber "fetchBlockNumber") [fetchEnsAvatar](/core/actions/fetchEnsAvatar "fetchEnsAvatar") --- # Library Comparison – wagmi On This Page * [Overview](#overview) * [wagmi](#wagmi) * [Pros](#pros) * [Cons](#cons) * [web3-react](#web3-react) * [Pros](#pros-1) * [Cons](#cons-1) * [useDApp](#usedapp) * [Pros](#pros-2) * [Cons](#cons-2) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9CLibrary%20Comparison%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/react/comparison.en-US.mdx) * React * Library Comparison Comparison To Other Libraries ============================= This comparison strives to be as accurate and as unbiased as possible. If you use any of these libraries and feel the information could be improved, feel free to suggest changes. There are multiple options when it comes to React libraries for Ethereum that help manage wallet connections, provide utility methods/hooks, etc. Overview[](#overview) ---------------------- | | [wagmi](https://github.com/wagmi-dev/wagmi) | [web3-react](https://github.com/NoahZinsmeister/web3-react) | [useDApp](https://github.com/EthWorks/useDApp) | | --- | --- | --- | --- | | GitHub Stars | ![wagmi star count](https://img.shields.io/github/stars/wagmi-dev/wagmi?colorB=161b22&label=) | ![web3-react star count](https://img.shields.io/github/stars/Uniswap/web3-react?colorB=161b22&label=) | ![useDApp star count](https://img.shields.io/github/stars/EthWorks/useDApp?colorB=161b22&label=) | | Open Issues | ![wagmi issue count](https://img.shields.io/github/issues/wagmi-dev/wagmi?colorB=161b22&label=) | ![web3-react issue count](https://img.shields.io/github/issues/Uniswap/web3-react?colorB=161b22&label=) | ![useDApp issue count](https://img.shields.io/github/issues/EthWorks/useDApp?colorB=161b22&label=) | | Downloads | ![wagmi downloads](https://img.shields.io/npm/dw/wagmi?colorB=161b22&label=) | ![web3-react downloads](https://img.shields.io/npm/dw/@web3-react/core?colorB=161b22&label=) | ![useDApp downloads](https://img.shields.io/npm/dw/@usedapp/core?colorB=161b22&label=) | | License | ![wagmi license](https://img.shields.io/github/license/wagmi-dev/wagmi?colorB=161b22&label=) | ![web3-react license](https://img.shields.io/github/license/Uniswap/web3-react?colorB=161b22&label=) | ![useDApp license](https://img.shields.io/github/license/EthWorks/useDApp?colorB=161b22&label=) | | Their Comparison | – | none | none | | Supported Frameworks | React, Vanilla JS | React | React | | Documentation | ✅ | 🛑 | ✅ | | TypeScript[1](/react/comparison.en-US#user-content-fn-1) | ✅ | 🔶 | 🔶 | | Test Suite[2](/react/comparison.en-US#user-content-fn-2) | ✅ | 🔶 | 🔶 | | Examples[3](/react/comparison.en-US#user-content-fn-3) | ✅ | 🔶 | ✅ | [wagmi](https://github.com/wagmi-dev/wagmi) [](#wagmi) ------------------------------------------------------- ### Pros[](#pros) * 20+ hooks for working with wallets, ENS, contracts, transactions, signing, etc. * Built-in wallet connectors for MetaMask, WalletConnect, Coinbase Wallet, and Injected * Caching, request deduplication, and persistence powered * Auto-refresh data on wallet, block, and network changes * Multicall support * Test suite running against forked Ethereum network * TypeScript ready (infer types from ABIs and EIP-712 Typed Data) * Extensive documentation and examples * Used by [ENS](https://ens.domains) , [Foundation](https://foundation.app) , [SushiSwap](https://sushi.com) , and [more](https://github.com/wagmi-dev/wagmi/discussions/201) * MIT License ### Cons[](#cons) * Not as many built-in connectors as `web3-react` [web3-react](https://github.com/Uniswap/web3-react) [](#web3-react) -------------------------------------------------------------------- ### Pros[](#pros-1) * Supports many different connectors (conceptually similar to wagmi's connectors) * Basic hooks for managing account * Used by [Uniswap](https://uniswap.org) and some other popular projects ### Cons[](#cons-1) * Need to set up connectors and method for connecting wallet on your own * Need to install connectors separately * Almost no tests or documentation; infrequent updates * GPL-3.0 License [useDApp](https://github.com/EthWorks/useDApp) [](#usedapp) ------------------------------------------------------------ ### Pros[](#pros-2) * Auto-refresh on new blocks and wallet changes * Multicall support * Transaction notifications * Chrome extension and Firefox add-on * MIT License ### Cons[](#cons-2) * Non-standard hook API * * * Footnotes[](#footnote-label) ----------------------------- 1. Infer types from ABIs, EIP-712 Typed Data, etc. ✅. Can add types with explicit generics, type annotations, etc. 🔶. [↩](/react/comparison.en-US#user-content-fnref-1) 2. Runs against forked Ethereum network ✅. Mocking functionality (i.e. RPC calls) is 🔶. [↩](/react/comparison.en-US#user-content-fnref-2) 3. Has multiple examples ✅. Has single example 🔶. [↩](/react/comparison.en-US#user-content-fnref-3) [Getting Started](/react/getting-started "Getting Started") [Migration Guide](/react/migration-guide "Migration Guide") --- # fetchEnsAvatar – @wagmi/core On This Page * [Usage](#usage) * [Return Value](#return-value) * [Configuration](#configuration) * [name](#name) * [chainId (optional)](#chainid-optional) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9CfetchEnsAvatar%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/core/actions/fetchEnsAvatar.en-US.mdx) * Core * Actions * fetchEnsAvatar fetchEnsAvatar ============== Action for fetching avatar for ENS name. This is a wrapper around viem's [`getEnsAvatar`](https://viem.sh/docs/ens/actions/getEnsAvatar.html) . import { fetchEnsAvatar } from '@wagmi/core' Usage[](#usage) ---------------- import { fetchEnsAvatar } from '@wagmi/core' const avatarUrl = await fetchEnsAvatar({ name: 'jxom.eth', }) Return Value[](#return-value) ------------------------------ string Configuration[](#configuration) -------------------------------- ### name[](#name) ENS name to fetch avatar for. import { fetchEnsAvatar } from '@wagmi/core' const ensAvatar = await fetchEnsAvatar({ name: 'jxom.eth', }) ### chainId (optional)[](#chainid-optional) Force a specific chain id for the request. The wagmi `Client`'s `publicClient` must be set up as a [chain-aware function](/core/config#publicclient-optional) for this to work correctly. import { fetchEnsAvatar } from '@wagmi/core' const ensAvatar = await fetchEnsAvatar({ name: 'jxom.eth', chainId: 1, }) [fetchEnsAddress](/core/actions/fetchEnsAddress "fetchEnsAddress") [fetchEnsName](/core/actions/fetchEnsName "fetchEnsName") --- # fetchEnsName – @wagmi/core On This Page * [Usage](#usage) * [Return Value](#return-value) * [Configuration](#configuration) * [address](#address) * [chainId (optional)](#chainid-optional) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9CfetchEnsName%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/core/actions/fetchEnsName.en-US.mdx) * Core * Actions * fetchEnsName fetchEnsName ============ Action for fetching ENS name for address. This is a wrapper around viem's [`getEnsName`](https://viem.sh/docs/ens/actions/getEnsName.html) . import { fetchEnsName } from '@wagmi/core' Usage[](#usage) ---------------- import { fetchEnsName } from '@wagmi/core' const ensName = await fetchEnsName({ address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', }) Return Value[](#return-value) ------------------------------ string Configuration[](#configuration) -------------------------------- ### address[](#address) Address to fetch ENS name for. import { fetchEnsName } from '@wagmi/core' function App() { const ensName = await fetchEnsName({ address: '0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac', }) } ### chainId (optional)[](#chainid-optional) Force a specific chain id for the request. The wagmi `Client`'s `publicClient` must be set up as a [chain-aware function](/core/config#publicclient-optional) for this to work correctly. import { fetchEnsName } from '@wagmi/core' function App() { const ensName = await fetchEnsName({ address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', chainId: 1, }) } [fetchEnsAvatar](/core/actions/fetchEnsAvatar "fetchEnsAvatar") [fetchEnsResolver](/core/actions/fetchEnsResolver "fetchEnsResolver") --- # fetchEnsResolver – @wagmi/core On This Page * [Usage](#usage) * [Return Value](#return-value) * [Configuration](#configuration) * [name](#name) * [chainId (optional)](#chainid-optional) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9CfetchEnsResolver%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/core/actions/fetchEnsResolver.en-US.mdx) * Core * Actions * fetchEnsResolver fetchEnsResolver ================ Action for fetching the resolver for ENS name. This is a wrapper around viem's [`getEnsResolver`](https://viem.sh/docs/ens/actions/getEnsResolver.html) . import { fetchEnsResolver } from '@wagmi/core' Usage[](#usage) ---------------- import { fetchEnsResolver } from '@wagmi/core' const resolver = await fetchEnsResolver({ name: 'awkweb.eth', }) Return Value[](#return-value) ------------------------------ EnsResolver Configuration[](#configuration) -------------------------------- ### name[](#name) ENS name to fetch resolver for. import { fetchEnsResolver } from '@wagmi/core' const resolver = await fetchEnsResolver({ name: 'moxey.eth', }) ### chainId (optional)[](#chainid-optional) Force a specific chain id for the request. The wagmi `Client`'s `publicClient` must be set up as a [chain-aware function](/core/config#publicclient-optional) for this to work correctly. import { fetchEnsResolver } from '@wagmi/core' const resolver = await fetchEnsResolver({ name: 'awkweb.eth', chainId: 1, }) [fetchEnsName](/core/actions/fetchEnsName "fetchEnsName") [fetchFeeData](/core/actions/fetchFeeData "fetchFeeData") --- # Config – wagmi On This Page * [Usage](#usage) * [Configuration](#configuration) * [autoConnect (optional)](#autoconnect-optional) * [connectors (optional)](#connectors-optional) * [logger (optional)](#logger-optional) * [publicClient](#publicclient) * [storage (optional)](#storage-optional) * [webSocketPublicClient (optional)](#websocketpublicclient-optional) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9CConfig%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/react/config.en-US.mdx) * React * createConfig Config ====== The wagmi `config` is a framework agnostic (Vanilla JS) config that manages wallet connection state and configuration, such as: auto-connection, connectors, and viem clients. import { createConfig } from 'wagmi' Usage[](#usage) ---------------- import { createConfig, configureChains, mainnet } from 'wagmi' import { publicProvider } from 'wagmi/providers/public' const { chains, publicClient, webSocketPublicClient } = configureChains( [mainnet], [publicProvider()], ) const config = createConfig({ publicClient, webSocketPublicClient, }) Configuration[](#configuration) -------------------------------- ### autoConnect (optional)[](#autoconnect-optional) Enables reconnecting to last used connector on mount. Defaults to `false`. import { createConfig, configureChains, mainnet } from 'wagmi' import { publicProvider } from 'wagmi/providers/public' const { publicClient } = configureChains([mainnet], [publicProvider()]) const config = createConfig({ autoConnect: true, publicClient, }) ### connectors (optional)[](#connectors-optional) Connectors used for linking accounts. Defaults to `[new InjectedConnector()]`. import { createConfig, configureChains, mainnet } from 'wagmi' import { publicProvider } from 'wagmi/providers/public' import { InjectedConnector } from 'wagmi/connectors/injected' import { WalletConnectConnector } from 'wagmi/connectors/walletConnect' const { chains, publicClient } = configureChains([mainnet], [publicProvider()]) const config = createConfig({ connectors: [\ new InjectedConnector({ chains }),\ new WalletConnectConnector({\ chains,\ options: {\ projectId: '...',\ },\ }),\ ], publicClient, }) ### logger (optional)[](#logger-optional) Adds the ability to provide a custom logger to override how logs are broadcasted in wagmi. Defaults to `console` logging. import { createConfig, configureChains, mainnet } from 'wagmi' import { publicProvider } from 'wagmi/providers/public' import { logWarn } from './logger' const { publicClient } = configureChains([mainnet], [publicProvider()]) const config = createConfig({ logger: { warn: (message) => logWarn(message), }, publicClient, }) You can also disable a logger by passing `null` as the value. // ... const config = createConfig({ logger: { warn: null, }, publicClient, }) ### publicClient[](#publicclient) viem [Public Client](https://viem.sh/docs/clients/public.html) for reading from the Ethereum network. import { createConfig, configureChains, mainnet } from 'wagmi' import { publicProvider } from 'wagmi/providers/public' const { publicClient } = configureChains([mainnet], [publicProvider()]) const config = createConfig({ publicClient, }) You can create a "chain-aware" `provider` by using the `configureChains` API or passing a function that updates based on `chainId`. ### storage (optional)[](#storage-optional) The default strategy to persist and cache data. Defaults to `window.localStorage`. import { createConfig, createStorage, configureChains, mainnet } from 'wagmi' import { publicProvider } from 'wagmi/providers/public' const { publicClient } = configureChains([mainnet], [publicProvider()]) const config = createConfig({ publicClient, storage: createStorage({ storage: window.localStorage }), }) ### webSocketPublicClient (optional)[](#websocketpublicclient-optional) viem [Public Client](https://viem.sh/docs/clients/public.html) with a [WebSocket Transport](https://viem.sh/docs/clients/transports/websocket.html) for connecting to the Ethereum network. If you provide a WebSocket Public Client, it will be used instead of polling in certain instances. import { createConfig, configureChains, mainnet } from 'wagmi' import { publicProvider } from 'wagmi/providers/public' const { publicClient, webSocketPublicClient } = configureChains( [mainnet], [publicProvider()], ) const config = createConfig({ publicClient, webSocketPublicClient, }) You can create a "chain-aware" `webSocketProvider` by using the `configureChains` API or passing a function that updates based on `chainId`. [TypeScript](/react/typescript "TypeScript") [WagmiConfig](/react/WagmiConfig "WagmiConfig") --- # Config Options – @wagmi/cli On This Page * [contracts (optional)](#contracts-optional) * [address (optional)](#address-optional) * [abi](#abi) * [name](#name) * [out](#out) * [plugins (optional)](#plugins-optional) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9CConfig%20Options%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/cli/configuration/options.en-US.mdx) * CLI * Configuration * Config Options Options ======= Configuration options for `@wagmi/cli`. contracts (optional)[](#contracts-optional) -------------------------------------------- Array of contracts to use when running [commands](/cli/commands) . `abi` and `name` are required, all other properties are optional. ### address (optional)[](#address-optional) Contract address or addresses. Accepts an object `{ [chainId]: address }` for targeting specific chains. wagmi.config.ts export default { out: 'src/generated.ts', contracts: [\ {\ abi: […],\ address: '0x…',\ name: 'MyCoolContract',\ },\ {\ abi: […],\ address: {\ 1: '0xfoo…',\ 5: '0xbar…',\ },\ name: 'MyCoolMultichainContract'\ }\ ], } ### abi[](#abi) ABI for contract. Used by [plugins](/cli/plugins) to generate code base on properties. wagmi.config.ts export default { out: 'src/generated.ts', contracts: [\ {\ abi: […],\ name: 'MyCoolContract'\ },\ ], } ### name[](#name) Name of contract. Must be unique. Used by [plugins](/cli/plugins) to name generated code. wagmi.config.ts export default { out: 'src/generated.ts', contracts: [\ {\ abi: […],\ name: 'MyCoolContract'\ },\ ], } out[](#out) ------------ Path to output generated code. Must be unique per config. Use an [Array Config](/cli/configuration/configuring-cli#array-config) for multiple outputs. wagmi.config.ts export default { out: 'src/generated.ts', contracts: [\ {\ abi: […],\ name: 'MyCoolContract'\ },\ ], } plugins (optional)[](#plugins-optional) ---------------------------------------- Plugins to use and their configuration. `@wagmi/cli` has multiple [built-in plugins](/cli/plugins) that are used to manage ABIs (fetch from block explorers, resolve from the file system, etc.), generate code (React hooks, type-safe JS actions, etc.), and much more! wagmi.config.ts import { etherscan, react } from '@wagmi/cli/plugins' export default { out: 'src/generated.js', plugins: [\ etherscan({\ apiKey: process.env.ETHERSCAN_API_KEY,\ chainId: 5,\ contracts: [\ {\ name: 'EnsRegistry',\ address: {\ 1: '0x314159265dd8dbb310642f98f50c066173c1259b',\ 5: '0x112234455c3a32fd11230c42e7bccd4a84e02010',\ },\ },\ ],\ }),\ react(),\ ], } [Configuring CLI](/cli/configuration/configuring-cli "Configuring CLI") [Commands](/cli/commands "Commands") --- # fetchFeeData – @wagmi/core On This Page * [Usage](#usage) * [Return Value](#return-value) * [Configuration](#configuration) * [chainId (optional)](#chainid-optional) * [formatUnits (optional)](#formatunits-optional) [Question? Give us feedback →](https://github.com/wagmi-dev/wagmi/issues/new?title=Feedback%20for%20%E2%80%9CfetchFeeData%E2%80%9D&labels=feedback) [Edit this page on GitHub →](https://github.com/wagmi-dev/wagmi/tree/main/docs/pages/core/actions/fetchFeeData.en-US.mdx) * Core * Actions * fetchFeeData fetchFeeData ============ Action for fetching network fee information. import { fetchFeeData } from '@wagmi/core' Usage[](#usage) ---------------- import { fetchFeeData } from '@wagmi/core' const feeData = await fetchFeeData() Return Value[](#return-value) ------------------------------ { gasPrice: bigint maxFeePerGas: bigint maxPriorityFeePerGas: bigint formatted: { gasPrice: string maxFeePerGas: string maxPriorityFeePerGas: string } } Configuration[](#configuration) -------------------------------- ### chainId (optional)[](#chainid-optional) Force a specific chain id for the request. The wagmi `Client`'s `publicClient` must be set up as a [chain-aware function](/core/config#publicclient-optional) for this to work correctly. import { fetchFeeData } from '@wagmi/core' const feeData = await fetchFeeData({ chainId: 1, }) ### formatUnits (optional)[](#formatunits-optional) Formats fee data. Defaults to `wei`. import { fetchFeeData } from '@wagmi/core' const feeData = await fetchFeeData({ formatUnits: 'gwei', }) [fetchEnsResolver](/core/actions/fetchEnsResolver "fetchEnsResolver") [fetchTransaction](/core/actions/fetchTransaction "fetchTransaction") ---