### Install Wagmi v3 Source: https://wagmi.sh/react/guides/migrate-from-v2-to-v3 Install the latest version of Wagmi to begin the migration. ```pnpm pnpm add wagmi@3 ``` ```npm npm install wagmi@3 ``` ```yarn yarn add wagmi@3 ``` ```bun bun add wagmi@3 ``` -------------------------------- ### Install Base Account SDK Source: https://wagmi.sh/react/api/connectors/baseAccount Install the required dependency using your preferred package manager. ```bash pnpm add @base-org/account@{{connectorDependencyVersion}} ``` ```bash npm install @base-org/account@{{connectorDependencyVersion}} ``` ```bash yarn add @base-org/account@{{connectorDependencyVersion}} ``` ```bash bun add @base-org/account@{{connectorDependencyVersion}} ``` -------------------------------- ### Install Coinbase Wallet SDK Source: https://wagmi.sh/react/api/connectors/coinbaseWallet Install the required dependency using your preferred package manager. ```bash pnpm add @coinbase/wallet-sdk@{{connectorDependencyVersion}} ``` ```bash npm install @coinbase/wallet-sdk@{{connectorDependencyVersion}} ``` ```bash yarn add @coinbase/wallet-sdk@{{connectorDependencyVersion}} ``` ```bash bun add @coinbase/wallet-sdk@{{connectorDependencyVersion}} ``` -------------------------------- ### TanStack Query Import Example Source: https://wagmi.sh/react/api/hooks/useVerifyMessage Example of how to import necessary types and functions for TanStack Query. ```APIDOC ## TanStack Query Import Example ```ts-vue import { type {{typeName}}Data, type {{typeName}}Options, type {{typeName}}QueryFnData, type {{typeName}}QueryKey, {{actionName}}QueryKey, {{actionName}}QueryOptions, } from '{{packageName}}/query' ``` ``` -------------------------------- ### Install porto dependency Source: https://wagmi.sh/react/guides/migrate-from-v2-to-v3 Install the required peer dependency for the porto connector. ```pnpm pnpm add porto@{{packageJson?.peerDependencies?.['porto']}} ``` ```npm npm install porto@{{packageJson?.peerDependencies?.['porto']}} ``` ```yarn yarn add porto@{{packageJson?.peerDependencies?.['porto']}} ``` ```bun bun add porto@{{packageJson?.peerDependencies?.['porto']}} ``` -------------------------------- ### Install TanStack Query Devtools Source: https://wagmi.sh/react/guides/tanstack-query Install the necessary devtools package using your preferred package manager. ```bash pnpm i @tanstack/react-query-devtools ``` ```bash npm i @tanstack/react-query-devtools ``` ```bash yarn add @tanstack/react-query-devtools ``` ```bash bun i @tanstack/react-query-devtools ``` -------------------------------- ### Manual installation of Wagmi dependencies Source: https://wagmi.sh/react/getting-started Install Wagmi, Viem, and TanStack Query manually into an existing project. ```bash pnpm add wagmi viem@{{viemVersion}} @tanstack/react-query ``` ```bash npm install wagmi viem@{{viemVersion}} @tanstack/react-query ``` ```bash yarn add wagmi viem@{{viemVersion}} @tanstack/react-query ``` ```bash bun add wagmi viem@{{viemVersion}} @tanstack/react-query ``` -------------------------------- ### Install metaMask dependency Source: https://wagmi.sh/react/guides/migrate-from-v2-to-v3 Install the required peer dependency for the metaMask connector. ```pnpm pnpm add @metamask/connect-evm@{{packageJson?.peerDependencies?.['@metamask/connect-evm']}} ``` ```npm npm install @metamask/connect-evm@{{packageJson?.peerDependencies?.['@metamask/connect-evm']}} ``` ```yarn yarn add @metamask/connect-evm@{{packageJson?.peerDependencies?.['@metamask/connect-evm']}} ``` ```bun bun add @metamask/connect-evm@{{packageJson?.peerDependencies?.['@metamask/connect-evm']}} ``` -------------------------------- ### Install coinbaseWallet dependency Source: https://wagmi.sh/react/guides/migrate-from-v2-to-v3 Install the required peer dependency for the coinbaseWallet connector. ```pnpm pnpm add @coinbase/wallet-sdk@{{packageJson?.peerDependencies?.['@coinbase/wallet-sdk']}} ``` ```npm npm install @coinbase/wallet-sdk@{{packageJson?.peerDependencies?.['@coinbase/wallet-sdk']}} ``` ```yarn yarn add @coinbase/wallet-sdk@{{packageJson?.peerDependencies?.['@coinbase/wallet-sdk']}} ``` ```bun bun add @coinbase/wallet-sdk@{{packageJson?.peerDependencies?.['@coinbase/wallet-sdk']}} ``` -------------------------------- ### Action Example Source: https://wagmi.sh/react/api/hooks/useEstimateMaxPriorityFeePerGas Reference to an example action, likely for estimating fees. ```APIDOC ## Action Example * [`estimateMaxPriorityFeePerGas`](/core/api/actions/estimateMaxPriorityFeePerGas) ``` -------------------------------- ### Install baseAccount dependency Source: https://wagmi.sh/react/guides/migrate-from-v2-to-v3 Install the required peer dependency for the baseAccount connector. ```pnpm pnpm add @base-org/account@{{packageJson?.peerDependencies?.['@base-org/account']}} ``` ```npm npm install @base-org/account@{{packageJson?.peerDependencies?.['@base-org/account']}} ``` ```yarn yarn add @base-org/account@{{packageJson?.peerDependencies?.['@base-org/account']}} ``` ```bun bun add @base-org/account@{{packageJson?.peerDependencies?.['@base-org/account']}} ``` -------------------------------- ### Install TanStack Query Persisters (bun) Source: https://wagmi.sh/react/guides/tanstack-query Install the necessary packages for TanStack Query sync storage persistence using bun. ```bash bun i @tanstack/query-sync-storage-persister @tanstack/react-query-persist-client ``` -------------------------------- ### Install Wagmi with bun Source: https://wagmi.sh/react/installation Use this command to install Wagmi and its peer dependencies with bun. ```bash bun add wagmi viem@{{viemVersion}} @tanstack/react-query ``` -------------------------------- ### Install WalletConnect Ethereum Provider Source: https://wagmi.sh/react/api/connectors/walletConnect Install the WalletConnect Ethereum provider dependency using your preferred package manager. ```bash pnpm add @walletconnect/ethereum-provider@{{connectorDependencyVersion}} ``` ```bash npm install @walletconnect/ethereum-provider@{{connectorDependencyVersion}} ``` ```bash yarn add @walletconnect/ethereum-provider@{{connectorDependencyVersion}} ``` ```bash bun add @walletconnect/ethereum-provider@{{connectorDependencyVersion}} ``` -------------------------------- ### Install Dependencies for Async Storage Persister Source: https://wagmi.sh/react/guides/tanstack-query Install the necessary packages for using async storage persistence with TanStack Query and Wagmi. ```bash pnpm i @tanstack/query-async-storage-persister @tanstack/react-query-persist-client ``` ```bash npm i @tanstack/query-async-storage-persister @tanstack/react-query-persist-client ``` ```bash yarn add @tanstack/query-async-storage-persister @tanstack/react-query-persist-client ``` ```bash bun i @tanstack/query-async-storage-persister @tanstack/react-query-persist-client ``` -------------------------------- ### Install MetaMask Connector Dependency Source: https://wagmi.sh/react/api/connectors/metaMask Install the required @metamask/connect-evm package using your preferred package manager. ```bash pnpm add @metamask/connect-evm@{{connectorDependencyVersion}} ``` ```bash npm install @metamask/connect-evm@{{connectorDependencyVersion}} ``` ```bash yarn add @metamask/connect-evm@{{connectorDependencyVersion}} ``` ```bash bun add @metamask/connect-evm@{{connectorDependencyVersion}} ``` -------------------------------- ### Install TanStack Query Persisters (yarn) Source: https://wagmi.sh/react/guides/tanstack-query Install the necessary packages for TanStack Query sync storage persistence using yarn. ```bash yarn add @tanstack/query-sync-storage-persister @tanstack/react-query-persist-client ``` -------------------------------- ### Install Wagmi with yarn Source: https://wagmi.sh/react/installation Use this command to install Wagmi and its peer dependencies with yarn. ```bash yarn add wagmi viem@{{viemVersion}} @tanstack/react-query ``` -------------------------------- ### Install Wagmi with pnpm Source: https://wagmi.sh/react/installation Use this command to install Wagmi and its peer dependencies with pnpm. ```bash pnpm add wagmi viem@{{viemVersion}} @tanstack/react-query ``` -------------------------------- ### Install TanStack Query Persisters (npm) Source: https://wagmi.sh/react/guides/tanstack-query Install the necessary packages for TanStack Query sync storage persistence using npm. ```bash npm i @tanstack/query-sync-storage-persister @tanstack/react-query-persist-client ``` -------------------------------- ### Install WalletConnect Dependency Source: https://wagmi.sh/react/guides/migrate-from-v2-to-v3 Install the required dependency for WalletConnect integration using your preferred package manager. ```bash pnpm add @walletconnect/ethereum-provider@{{packageJson?.peerDependencies?.['@walletconnect/ethereum-provider']}} ``` ```bash npm install @walletconnect/ethereum-provider@{{packageJson?.peerDependencies?.['@walletconnect/ethereum-provider']}} ``` ```bash yarn add @walletconnect/ethereum-provider@{{packageJson?.peerDependencies?.['@walletconnect/ethereum-provider']}} ``` ```bash bun add @walletconnect/ethereum-provider@{{packageJson?.peerDependencies?.['@walletconnect/ethereum-provider']}} ``` -------------------------------- ### Install Wagmi with npm Source: https://wagmi.sh/react/installation Use this command to install Wagmi and its peer dependencies with npm. ```bash npm install wagmi viem@{{viemVersion}} @tanstack/react-query ``` -------------------------------- ### Install Safe Connector Dependencies Source: https://wagmi.sh/react/api/connectors/safe Install the necessary Safe Apps provider and SDK packages using your preferred package manager. ```bash pnpm add @safe-global/safe-apps-provider@{{connectorDependencyVersions?.[0]}} @safe-global/safe-apps-sdk@{{connectorDependencyVersions?.[1]}} ``` ```bash npm install @safe-global/safe-apps-provider@{{connectorDependencyVersions?.[0]}} @safe-global/safe-apps-sdk@{{connectorDependencyVersions?.[1]}} ``` ```bash yarn add @safe-global/safe-apps-provider@{{connectorDependencyVersions?.[0]}} @safe-global/safe-apps-sdk@{{connectorDependencyVersions?.[1]}} ``` ```bash bun add @safe-global/safe-apps-provider@{{connectorDependencyVersions?.[0]}} @safe-global/safe-apps-sdk@{{connectorDependencyVersions?.[1]}} ``` -------------------------------- ### Install TanStack Query Persisters (pnpm) Source: https://wagmi.sh/react/guides/tanstack-query Install the necessary packages for TanStack Query sync storage persistence using pnpm. ```bash pnpm i @tanstack/query-sync-storage-persister @tanstack/react-query-persist-client ``` -------------------------------- ### Install Wagmi from a pull request with bun Source: https://wagmi.sh/react/installation Install Wagmi from a specific pull request using bun. ```bash bun add https://pkg.pr.new/{{packageName}}@123 ``` -------------------------------- ### Install latest Wagmi canary with bun Source: https://wagmi.sh/react/installation Install the latest Wagmi version from the canary tag using bun. ```bash bun add {{packageName}}@canary ``` -------------------------------- ### Install Porto Connector Source: https://wagmi.sh/react/api/connectors/porto Install the Porto connector package using your preferred package manager. Ensure you use the correct version specified for compatibility. ```bash pnpm add porto@{{connectorDependencyVersion}} ``` ```bash npm install porto@{{connectorDependencyVersion}} ``` ```bash yarn add porto@{{connectorDependencyVersion}} ``` ```bash bun add porto@{{connectorDependencyVersion}} ``` -------------------------------- ### Install Wagmi from a pull request with yarn Source: https://wagmi.sh/react/installation Install Wagmi from a specific pull request using yarn. ```bash yarn add https://pkg.pr.new/{{packageName}}@123 ``` -------------------------------- ### Install Wagmi from a pull request with npm Source: https://wagmi.sh/react/installation Install Wagmi from a specific pull request using npm. ```bash npm install https://pkg.pr.new/{{packageName}}@123 ``` -------------------------------- ### useReadContract Example Source: https://wagmi.sh/react/api/hooks/useReadContract This example demonstrates how to use the `useReadContract` hook to read the `balanceOf` function from the DAI contract. ```APIDOC ## POST /api/users ### Description This endpoint allows you to create a new user in the system. ### Method POST ### Endpoint /api/users ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (string) - Required - The name of the user. - **email** (string) - Required - The email address of the user. ### Request Example ```json { "name": "John Doe", "email": "john.doe@example.com" } ``` ### Response #### Success Response (201) - **id** (string) - The unique identifier of the created user. - **name** (string) - The name of the created user. - **email** (string) - The email address of the created user. #### Response Example ```json { "id": "123e4567-e89b-12d3-a456-426614174000", "name": "John Doe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Install Wagmi from a pull request with pnpm Source: https://wagmi.sh/react/installation Install Wagmi from a specific pull request using pnpm. ```bash pnpm add https://pkg.pr.new/{{packageName}}@123 ``` -------------------------------- ### Install latest Wagmi canary with yarn Source: https://wagmi.sh/react/installation Install the latest Wagmi version from the canary tag using yarn. ```bash yarn add {{packageName}}@canary ``` -------------------------------- ### Install Safe Apps Dependencies Source: https://wagmi.sh/react/guides/migrate-from-v2-to-v3 Install the required dependencies for Safe Apps integration using your preferred package manager. ```bash pnpm add @safe-global/safe-apps-provider@{{packageJson?.peerDependencies?.['@safe-global/safe-apps-provider']}} @safe-global/safe-apps-sdk@{{packageJson?.peerDependencies?.['@safe-global/safe-apps-sdk']}} ``` ```bash npm install @safe-global/safe-apps-provider@{{packageJson?.peerDependencies?.['@safe-global/safe-apps-provider']}} @safe-global/safe-apps-sdk@{{packageJson?.peerDependencies?.['@safe-global/safe-apps-sdk']}} ``` ```bash yarn add @safe-global/safe-apps-provider@{{packageJson?.peerDependencies?.['@safe-global/safe-apps-provider']}} @safe-global/safe-apps-sdk@{{packageJson?.peerDependencies?.['@safe-global/safe-apps-sdk']}} ``` ```bash bun add @safe-global/safe-apps-provider@{{packageJson?.peerDependencies?.['@safe-global/safe-apps-provider']}} @safe-global/safe-apps-sdk@{{packageJson?.peerDependencies?.['@safe-global/safe-apps-sdk']}} ``` -------------------------------- ### Install latest Wagmi canary with npm Source: https://wagmi.sh/react/installation Install the latest Wagmi version from the canary tag using npm. ```bash npm install {{packageName}}@canary ``` -------------------------------- ### StorageKeys Parameter Source: https://wagmi.sh/react/api/hooks/useProof Example usage focusing on the storageKeys parameter. ```tsx import { useProof } from 'wagmi' function App() { const result = useProof({ address: '0x4200000000000000000000000000000000000016', storageKeys: [ // [!code focus:3] '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Install latest Wagmi canary with pnpm Source: https://wagmi.sh/react/installation Install the latest Wagmi version from the canary tag using pnpm. ```bash pnpm add {{packageName}}@canary ``` -------------------------------- ### Use Switch Chain Hook Example Source: https://wagmi.sh/react/api/hooks/useSwitchChain Demonstrates how to use the `useSwitchChain` hook to allow users to switch between configured chains. It maps over the available chains and creates buttons for each. ```tsx import { useSwitchChain } from 'wagmi' function App() { const switchChain = useSwitchChain() return (
{switchChain.chains.map((chain) => ( ))}
) } ``` -------------------------------- ### Wagmi and React Query Provider Setup Source: https://wagmi.sh/react/guides/connect-wallet Wraps the application with `WagmiProvider` and `QueryClientProvider` to provide Wagmi's context and React Query's client to the application. Ensure React Query client is set up before Wagmi. ```tsx // 1. Import modules import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { WagmiProvider } from 'wagmi' import { config } from './config' // 2. Set up a React Query client. const queryClient = new QueryClient() function App() { // 3. Wrap app with Wagmi and React Query context. return ( {/* ... */} ) } ``` -------------------------------- ### Inline Type Inference Example Source: https://wagmi.sh/react/api/hooks/useSignTypedData This example demonstrates how TypeScript infers types for domain, message, and primaryType when 'types' are correctly configured. Ensure your TypeScript setup is accurate for this to work. ```typescript // @ts-expect-error const { domain, types, message } = signTypedData({ domain, types, primaryType, }) ``` -------------------------------- ### Basic Usage of useSignTransaction Source: https://wagmi.sh/react/api/hooks/useSignTransaction Example showing how to trigger a transaction signature using the hook. ```tsx import { useSignTransaction } from 'wagmi' import { parseEther } from 'viem' function App() { const signTransaction = useSignTransaction() return ( ) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Basic Usage Source: https://wagmi.sh/react/api/hooks/useVerifyMessage Example of using the hook to verify a signed message. ```tsx import { useVerifyMessage } from 'wagmi' function App() { const result = useVerifyMessage({ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message: 'hello world', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Setup TanStack Query Source: https://wagmi.sh/react/getting-started Integrates TanStack Query by wrapping the application in a QueryClientProvider. ```tsx import { QueryClient, QueryClientProvider } from '@tanstack/react-query' // [!code focus] import { WagmiProvider } from 'wagmi' import { config } from './config' const queryClient = new QueryClient() // [!code focus] function App() { return ( // [!code focus] {/** ... */} // [!code focus] // [!code focus] ) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Integrating Viem Client with createConfig Source: https://wagmi.sh/react/api/createConfig Provide a custom Viem Client using the `client` property for more control over Wagmi's internal client creation. This example uses `createClient` from Viem. ```ts-vue import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' import { createClient } from 'viem' const config = createConfig({ chains: [mainnet, sepolia], client({ chain }) { return createClient({ chain, transport: http() }) }, }) ``` -------------------------------- ### Basic WagmiProvider Setup Source: https://wagmi.sh/react/api/WagmiProvider Set up the WagmiProvider with a configuration object. This is the minimum required to use Wagmi in your React application. ```tsx import { WagmiProvider } from 'wagmi' import { config } from './config' function App() { return ( {/** ... **/ ) } ``` ```typescript import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### TanStack Query Imports Source: https://wagmi.sh/react/api/hooks/useStorageAt Example import statements for TanStack Query types and actions. ```APIDOC ## TanStack Query Imports ### Description Import necessary types and functions for TanStack Query operations. ### Code Example ```ts-vue import { type {{typeName}}Data, type {{typeName}}Options, type {{typeName}}QueryFnData, type {{typeName}}QueryKey, {{actionName}}QueryKey, {{actionName}}QueryOptions, } from '{{packageName}}/query' ``` ``` -------------------------------- ### Configure Wagmi and Use Read Contract Source: https://wagmi.sh/react/api/hooks/useReadContract Setup the Wagmi configuration and demonstrate type inference with the useReadContract hook. ```ts import { createConfig, http, useReadContract } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) // ---cut--- const result = useReadContract({ abi: [ { type: 'function', name: 'balanceOf', stateMutability: 'view', inputs: [{ name: 'account', type: 'address' }], outputs: [{ type: 'uint256' }], }, { type: 'function', name: 'totalSupply', stateMutability: 'view', inputs: [], ``` -------------------------------- ### Implement useSwitchConnection Source: https://wagmi.sh/react/api/hooks/useSwitchConnection Example usage of the hook to render a list of connectors and trigger a connection switch. Requires a configured Wagmi environment. ```tsx import { useSwitchConnection } from 'wagmi' function App() { const switchConnection = useSwitchConnection() return (
{switchConnection.connectors.map((connector) => ( ))}
) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Address Parameter Source: https://wagmi.sh/react/api/hooks/useProof Example usage focusing on the address parameter. ```tsx import { useProof } from 'wagmi' function App() { const result = useProof({ address: '0x4200000000000000000000000000000000000016', // [!code focus] storageKeys: [ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### TanStack Query Imports Source: https://wagmi.sh/react/api/hooks/useCallsStatus Example import statement for TanStack Query types. ```APIDOC ## TanStack Query Imports ```ts-vue import { type {{typeName}}Data, type {{typeName}}Options, type {{typeName}}QueryFnData, type {{typeName}}QueryKey, {{actionName}}QueryKey, {{actionName}}QueryOptions, } from '{{packageName}}/query' ``` ``` -------------------------------- ### Configuring Connectors with createConfig Source: https://wagmi.sh/react/api/createConfig Add connectors to the Wagmi configuration. This example includes the `injected` connector. ```ts-vue import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' import { injected } from '{{connectorsPackageName}}' const config = createConfig({ chains: [mainnet, sepolia], connectors: [injected()], transports: { [mainnet.id]: http('https://mainnet.example.com'), [sepolia.id]: http('https://sepolia.example.com'), }, }) ``` -------------------------------- ### Get Configured Chains with useConfig Source: https://wagmi.sh/react/guides/migrate-from-v1-to-v2 Replaces `useNetwork` hook to get the list of configured chains by using the `useConfig` hook. ```ts import { useNetwork } from 'wagmi' // [!code --] import { useConfig } from 'wagmi' // [!code ++] const { chains } = useNetwork() // [!code --] const { chains } = useConfig() // [!code ++] ``` -------------------------------- ### Build and link Wagmi from source Source: https://wagmi.sh/react/installation Clone the Wagmi repository, build it, and link the package locally. ```bash gh repo clone wevm/wagmi cd wagmi pnpm install pnpm build cd packages/{{packageDir}} pnpm link --global ``` -------------------------------- ### Usage Example Source: https://wagmi.sh/react/api/hooks/useTransactionConfirmations Basic implementation of the hook within a React component. ```tsx import { useTransactionConfirmations } from 'wagmi' function App() { const result = useTransactionConfirmations({ hash: '0x0fa64daeae54e207aa98613e308c2ba8abfe274f75507e741508cc4db82c8cb5', }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Configure useSwitchConnection Source: https://wagmi.sh/react/api/hooks/useSwitchConnection Example of providing a custom config object to the hook. ```tsx import { useSwitchConnection } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useSwitchConnection({ config, // [!code focus] }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Configure useSignTransaction Source: https://wagmi.sh/react/api/hooks/useSignTransaction Example of providing a custom configuration to the hook. ```tsx import { useSignTransaction } from 'wagmi' import { config } from './config' // [!code focus] function App() { const signTransaction = useSignTransaction({ config, // [!code focus] }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### WalletConnect Connector Source: https://wagmi.sh/react/api/connectors/walletConnect This section covers the import, installation, and basic usage of the WalletConnect connector. ```APIDOC ## WalletConnect Connector Connector for [WalletConnect](https://walletconnect.com). ### Import ```ts import { walletConnect } from '{{connectorsPackageName}}' ``` ### Install ::: code-group ```bash [pnpm] pnpm add @walletconnect/ethereum-provider@{{connectorDependencyVersion}} ``` ```bash [npm] npm install @walletconnect/ethereum-provider@{{connectorDependencyVersion}} ``` ```bash [yarn] yarn add @walletconnect/ethereum-provider@{{connectorDependencyVersion}} ``` ```bash [bun] bun add @walletconnect/ethereum-provider@{{connectorDependencyVersion}} ``` ::: ### Usage ```ts import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' import { walletConnect } from '{{connectorsPackageName}}' export const config = createConfig({ chains: [mainnet, sepolia], connectors: [ walletConnect({ projectId: '3fcc6bba6f1de962d911bb5b5c3dba68', }), ], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` ``` -------------------------------- ### Install Wagmi via CDN Source: https://wagmi.sh/react/installation Include these imports in a ` ``` -------------------------------- ### useVerifyMessage Hook Configuration Source: https://wagmi.sh/react/api/hooks/useVerifyMessage Example of configuring the `useVerifyMessage` hook with the `scopeKey` option. ```APIDOC ## POST /api/verifyMessage (Example) ### Description This endpoint is an example of how to use the `useVerifyMessage` hook with a specific `scopeKey` to scope the cache. ### Method POST ### Endpoint /api/verifyMessage ### Parameters #### Query Parameters - **scopeKey** (string | undefined) - Optional - Scopes the cache to a given context. Hooks that have identical context will share the same cache. #### Request Body - **address** (string) - Required - The Ethereum address to verify. - **message** (string) - Required - The message to verify. - **signature** (string) - Required - The signature of the message. ### Request Example ```json { "address": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266", "message": "hello world", "signature": "0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c" } ``` ### Response #### Success Response (200) - **result** (object) - The result of the verification. #### Response Example ```json { "result": { "data": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266" } } ``` ``` -------------------------------- ### Setup Async Storage Persister with Wagmi and TanStack Query Source: https://wagmi.sh/react/guides/tanstack-query Configure TanStack Query to use an asynchronous storage solution like AsyncStorage for persistence. This requires importing `createAsyncStoragePersister` and providing the storage implementation. ```tsx import AsyncStorage from '@react-native-async-storage/async-storage' import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister' import { QueryClient } from '@tanstack/react-query' import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client' import { WagmiProvider, deserialize, serialize } from 'wagmi' const queryClient = new QueryClient({ defaultOptions: { queries: { gcTime: 1_000 * 60 * 60 * 24, // 24 hours }, }, }) const persister = createAsyncStoragePersister({ serialize, storage: AsyncStorage, deserialize, }) function App() { return ( {/* ... */} ) } ``` -------------------------------- ### Initialize a new Wagmi project Source: https://wagmi.sh/react/getting-started Use the create-wagmi CLI to scaffold a new project with TypeScript and necessary dependencies. ```bash pnpm create wagmi ``` ```bash npm create wagmi@latest ``` ```bash yarn create wagmi ``` ```bash bun create wagmi ``` -------------------------------- ### Import Statement Source: https://wagmi.sh/react/api/hooks/usePrepareTransactionRequest Example import statement for TanStack Query types and functions. ```APIDOC ## TanStack Query Import ```ts-vue import { type {{typeName}}Data, type {{typeName}}Options, type {{typeName}}QueryFnData, type {{typeName}}QueryKey, {{actionName}}QueryKey, {{actionName}}QueryOptions, } from '{{packageName}}/query' ``` ``` -------------------------------- ### BlockTag Parameter Source: https://wagmi.sh/react/api/hooks/useProof Example usage focusing on the blockTag parameter. ```tsx import { useProof } from 'wagmi' function App() { const result = useProof({ address: '0x4200000000000000000000000000000000000016', blockTag: 'latest', // [!code focus] storageKeys: [ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### BlockNumber Parameter Source: https://wagmi.sh/react/api/hooks/useProof Example usage focusing on the blockNumber parameter. ```tsx import { useProof } from 'wagmi' function App() { const result = useProof({ address: '0x4200000000000000000000000000000000000016', blockNumber: 42069n, // [!code focus] storageKeys: [ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Setup Sync Storage Persister with Wagmi and TanStack Query Source: https://wagmi.sh/react/guides/tanstack-query Use this to enable persistence for TanStack Query cache using browser's localStorage. Ensure `createSyncStoragePersister`, `QueryClient`, and `PersistQueryClientProvider` are imported. ```tsx import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister' import { QueryClient } from '@tanstack/react-query' import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client' import { WagmiProvider, deserialize, serialize } from 'wagmi' const queryClient = new QueryClient({ defaultOptions: { queries: { gcTime: 1_000 * 60 * 60 * 24, // 24 hours }, }, }) const persister = createSyncStoragePersister({ serialize, storage: window.localStorage, deserialize, }) function App() { return ( {/* ... */} ) } ``` -------------------------------- ### baseAccount Connector Configuration Source: https://wagmi.sh/react/api/connectors/baseAccount Details on how to import, install, and configure the baseAccount connector within a Wagmi config. ```APIDOC ## baseAccount Connector ### Description Connector for the Base Account SDK, allowing integration with Base accounts in Wagmi applications. ### Installation - pnpm: `pnpm add @base-org/account@{{connectorDependencyVersion}}` - npm: `npm install @base-org/account@{{connectorDependencyVersion}}` - yarn: `yarn add @base-org/account@{{connectorDependencyVersion}}` - bun: `bun add @base-org/account@{{connectorDependencyVersion}}` ### Parameters - **appName** (string) - Optional - Application name displayed upon connection. - **appLogoUrl** (string | null | undefined) - Optional - Application logo image URL; defaults to favicon if unspecified. ``` -------------------------------- ### Tree-shakable Viem Actions with Wagmi Source: https://wagmi.sh/react/guides/viem Utilizes `useClient` and `useConnectorClient` to import and use Viem actions directly. Recommended for optimal bundle size. ```tsx // 1. Import modules. import { useMutation, useQuery } from '@tanstack/react-query' import { http, createConfig, useClient, useConnectorClient } from 'wagmi' import { base, mainnet, optimism, zora } from 'wagmi/chains' import { getLogs, watchAsset } from 'viem/actions' // 2. Set up a Wagmi Config export const config = createConfig({ chains: [base, mainnet, optimism, zora], transports: { [base.id]: http(), [mainnet.id]: http(), [optimism.id]: http(), [zora.id]: http(), }, }) function Example() { // 3. Extract a Viem Client for the current active chain. // [!code hl] const publicClient = useClient({ config }) // [!code hl] // 4. Create a "custom" Query Hook that utilizes the Client. // [!code hl] const { data: logs } = useQuery({ // [!code hl] queryKey: ['logs', publicClient.uid], // [!code hl] queryFn: () => getLogs(publicClient, /* ... */) // [!code hl] }) // [!code hl] // 5. Extract a Viem Client for the current active chain & account. // [!code hl] const { data: walletClient } = useConnectorClient({ config }) // [!code hl] // 6. Create a "custom" Mutation Hook that utilizes the Client. // [!code hl] const { mutate } = useMutation({ mutationFn: (asset) => watchAsset(walletClient, asset) // [!code hl] }) // [!code hl] return (
{/* ... */}
) } ``` -------------------------------- ### useConnectors Hook Source: https://wagmi.sh/react/api/hooks/useConnectors Hook for getting configured connectors. ```APIDOC ## useConnectors ### Description Hook for getting configured connectors. ### Import ```typescript import { useConnectors } from 'wagmi' ``` ### Usage ```typescript import { useConnectors } from 'wagmi' function App() { const connectors = useConnectors() } ``` ### Return Type `readonly Connector[]` Connectors from [`config.connectors`](/react/api/createConfig#connectors-1). ### Action * [`getConnectors`](/core/api/actions/getConnectors) ``` -------------------------------- ### Import useProof Source: https://wagmi.sh/react/api/hooks/useProof Import the hook from the wagmi package. ```ts import { useProof } from 'wagmi' ``` -------------------------------- ### Switch Connection Usage Source: https://wagmi.sh/react/api/hooks/useSwitchConnection Example of using the hook to switch between available connections via a button click. ```tsx import { useConnections, useSwitchConnection } from 'wagmi' function App() { const switchConnection = useSwitchConnection() const connections = useConnections() return (
{connections.map((connection) => ( ))}
) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### useConnection Hook Source: https://wagmi.sh/react/api/hooks/useConnection Hook for getting current connection. ```APIDOC ## useConnection Hook for getting current connection. ### Import ```ts import { useConnection } from 'wagmi' ``` ### Usage ```tsx import { useConnection } from 'wagmi' function App() { const connection = useConnection() } ``` ### Parameters #### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ```tsx import { useConnection } from 'wagmi' import { config } from './config' function App() { const connection = useConnection({ config, }) } ``` ### Return Type #### address `Address | undefined` * Connected address from connector. * Defaults to first address in [`addresses`](#addresses). #### addresses `readonly Address[] | undefined` Connected addresses from connector. #### chain `Chain | undefined` Connected chain from connector. If chain is not configured by config, it will be `undefined`. #### chainId `number | undefined` Connected chain id from connector. #### connector `Connector | undefined` Connected connector. #### isConnecting / isReconnecting / isConnected / isDisconnected `boolean` Boolean variables derived from [`status`](#status). ``` -------------------------------- ### getEnsResolver Action Source: https://wagmi.sh/react/api/hooks/useEnsResolver Example of an available action for interacting with ENS resolvers. ```APIDOC ## Action ### getEnsResolver * [`getEnsResolver`](/core/api/actions/getEnsResolver) ``` -------------------------------- ### Set Up Wagmi and TanStack Query Providers Source: https://wagmi.sh/react/getting-started Wrap your application with `WagmiProvider` and `QueryClientProvider` to enable Wagmi hooks. Ensure the `config` is imported. ```tsx import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { WagmiProvider } from 'wagmi' import { config } from './config' import { Profile } from './profile' const queryClient = new QueryClient() function App() { return ( ) } ``` -------------------------------- ### useConnections Hook Source: https://wagmi.sh/react/api/hooks/useConnections Hook for getting active connections. ```APIDOC ## useConnections Hook ### Description Hook for getting active connections. ### Import ```ts import { useConnections } from 'wagmi' ``` ### Usage ```tsx import { useConnections } from 'wagmi' function App() { const connections = useConnections() } ``` ### Parameters #### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ```tsx import { useConnections } from 'wagmi' import { config } from './config' function App() { const connections = useConnections({ config, }) } ``` ### Return Type ```ts import { type UseConnectionsReturnType } from 'wagmi' ``` ### Related Actions * [`getConnections`](/core/api/actions/getConnections) * [`watchConnections`](/core/api/actions/watchConnections) ``` -------------------------------- ### useCall with Account Parameter Source: https://wagmi.sh/react/api/hooks/useCall Example of using the `account` parameter in the `useCall` hook to specify the caller. ```tsx import { useCall } from 'wagmi' function App() { const result = useCall({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', // [!code focus] data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) } ``` ```typescript import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Basic Usage of useWriteContract Source: https://wagmi.sh/react/api/hooks/useWriteContract Use the `useWriteContract` hook to initiate a contract write operation. This example demonstrates transferring tokens by calling the `transferFrom` function. ```tsx import { useWriteContract } from 'wagmi' import { abi } from './abi' function App() { const writeContract = useWriteContract() return ( ) } ``` -------------------------------- ### Basic useReadContract Usage Source: https://wagmi.sh/react/api/hooks/useReadContract Call a read-only contract function like 'totalSupply'. Ensure the ABI and contract address are correctly provided. This example assumes the ABI is imported from './abi'. ```tsx import { useReadContract } from 'wagmi' import { abi } from './abi' function App() { const result = useReadContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'totalSupply', }) } ``` ```typescript import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Get Connected Chain with useAccount Source: https://wagmi.sh/react/guides/migrate-from-v1-to-v2 Replaces `useNetwork` hook to get the connected chain by using the `useAccount` hook. ```ts import { useNetwork } from 'wagmi' // [!code --] import { useAccount } from 'wagmi' // [!code ++] const { chain } = useNetwork() // [!code --] const { chain } = useAccount() // [!code ++] ``` -------------------------------- ### getClient Source: https://wagmi.sh/react/api/createConfig Creates a new Viem Client object based on the provided configuration. ```APIDOC ## getClient ### Description Creates a new Viem Client object using the current configuration. ### Parameters #### Query Parameters - **chainId** (chainId | chains[number]['id']) - Optional - The chain ID to associate with the client. ### Request Example ```ts const client = config.getClient({ chainId: 1 }) ``` ``` -------------------------------- ### Define a Chain Configuration Source: https://wagmi.sh/react/api/chains Use defineChain to create a typed chain object. This example demonstrates the structure for the Ethereum mainnet, including native currency, RPC endpoints, and contract addresses. ```typescript import { defineChain } from 'viem' export const mainnet = defineChain({ id: 1, name: 'Ethereum', nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 }, rpcUrls: { default: { http: ['https://eth.merkle.io'] }, }, blockExplorers: { default: { name: 'Etherscan', url: 'https://etherscan.io' }, }, contracts: { ensRegistry: { address: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e', }, ensUniversalResolver: { address: '0xE4Acdd618deED4e6d2f03b9bf62dc6118FC9A4da', blockCreated: 16773775, }, multicall3: { address: '0xca11bde05977b3631167028862be2a173976ca11', blockCreated: 14353601, }, }, }) ``` -------------------------------- ### useWalletClient Hook Source: https://wagmi.sh/react/api/hooks/useWalletClient Hook for getting a Viem `WalletClient` object for the current or provided connector. ```APIDOC ## useWalletClient ### Description Hook for getting a Viem [`WalletClient`](https://viem.sh/docs/clients/wallet) object for the current or provided connector. ### Import ```ts import { useWalletClient } from 'wagmi' ``` ### Usage ```tsx import { useWalletClient } from 'wagmi' function App() { const result = useWalletClient() } ``` ### Parameters #### account `Address | Account | undefined` Account to use with client. Throws if account is not found on [`connector`](#connector). ```tsx import { useWalletClient } from 'wagmi' function App() { const result = useWalletClient({ account: '0xd2135CfB216b74109775236E36d4b433F1DF507B', }) } ``` #### chainId `config['chains'][number]['id'] | undefined` ID of chain to use with client. ```tsx import { useWalletClient } from 'wagmi' import { mainnet } from 'wagmi/chains' function App() { const result = useWalletClient({ chainId: mainnet.id, }) } ``` #### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ```tsx import { useWalletClient } from 'wagmi' import { config } from './config' function App() { const result = useWalletClient({ config, }) } ``` #### connector `Connector | undefined` * Connector to get client for. * Defaults to current connector. ```tsx import { useConnections, useWalletClient } from 'wagmi' function App() { const connections = useConnections(config) const result = useWalletClient({ connector: connections[0]?.connector, }) } ``` ### query TanStack Query parameters. See the [TanStack Query query docs](https://tanstack.com/query/v5/docs/react/reference/useQuery) for more info. #### enabled `boolean | undefined` * Set this to `false` to disable this query from automatically running. * Can be used for [Dependent Queries](https://tanstack.com/query/v5/docs/react/guides/dependent-queries). #### gcTime `number | Infinity | undefined` * Defaults to `5 * 60 * 1000` (5 minutes) or `Infinity` during SSR * The time in milliseconds that unused/inactive cache data remains in memory. When a query's cache becomes unused or inactive, that cache data will be garbage collected after this duration. When different garbage collection times are specified, the longest one will be used. * If set to `Infinity`, will disable garbage collection ``` -------------------------------- ### Usage of useChains Source: https://wagmi.sh/react/api/hooks/useChains Basic implementation of the hook within a React component and the required configuration setup. ```tsx import { useChains } from 'wagmi' function App() { const chains = useChains() } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Basic useInfiniteReadContracts Usage Source: https://wagmi.sh/react/api/hooks/useInfiniteReadContracts Demonstrates fetching multiple contract attributes with "fetch more" support. Requires contract ABI and configuration. ```typescript import { useInfiniteReadContracts } from 'wagmi' import { abi } from './abi' const mlootContractConfig = { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi, } as const function App() { const result = useInfiniteReadContracts({ cacheKey: 'mlootAttributes', contracts(pageParam) { const args = [pageParam] as const return [ { ...mlootContractConfig, functionName: 'getChest', args }, { ...mlootContractConfig, functionName: 'getFoot', args }, { ...mlootContractConfig, functionName: 'getHand', args }, ] } query: { initialPageParam: 0, getNextPageParam: (_lastPage, _allPages, lastPageParam) => { return lastPageParam + 1 } } }) } ``` ```typescript import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Basic Usage of useEstimateFeesPerGas Source: https://wagmi.sh/react/api/hooks/useEstimateFeesPerGas A basic example of using the useEstimateFeesPerGas hook in a React component. ```tsx import { useEstimateFeesPerGas } from 'wagmi' function App() { const result = useEstimateFeesPerGas() } ``` -------------------------------- ### Create Viem Client Source: https://wagmi.sh/react/api/createConfig Creates a new Viem Client object. Import `createConfig` and `http` from wagmi. Ensure chains and transports are correctly configured. ```typescript import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http('https://mainnet.example.com'), [sepolia.id]: http('https://sepolia.example.com'), }, }) ``` ```typescript import { config } from './config' const client = config.getClient({ chainId: 1 }) ``` -------------------------------- ### Send Transaction Usage Source: https://wagmi.sh/react/api/hooks/useSendTransaction Example of using the hook to send a transaction via a button click. ```tsx import { useSendTransaction } from 'wagmi' import { parseEther } from 'viem' function App() { const sendTransaction = useSendTransaction() return ( ) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### useCall with AccessList Parameter Source: https://wagmi.sh/react/api/hooks/useCall Example of using the `accessList` parameter in the `useCall` hook to specify an access list for the call. ```tsx import { useCall } from 'wagmi' function App() { const result = useCall({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', accessList: [ // [!code focus:6] { address: '0x1', storageKeys: ['0x1'], }, ], data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) } ``` ```typescript import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### WagmiProvider Setup in Next.js App Router Client Component Source: https://wagmi.sh/react/guides/ssr Ensure your `Providers` component in `app/providers.tsx` is a Client Component (`'use client'`) and accepts the `initialState` prop. Pass this `initialState` to the `WagmiProvider` to hydrate the client-side state with server-rendered data. ```typescript 'use client' import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { type ReactNode, useState } from 'react' import { type State, WagmiProvider } from 'wagmi' import { getConfig } from './config' type Props = { children: ReactNode, initialState: State | undefined, } export function Providers({ children, initialState }: Props) { const [config] = useState(() => getConfig()) const [queryClient] = useState(() => new QueryClient()) return ( {children} ) } ``` -------------------------------- ### Initialize with Connector Source: https://wagmi.sh/react/api/transports/unstable_connector Basic initialization of the transport using a specific connector. ```ts import { unstable_connector } from 'wagmi' import { safe } from 'wagmi/connectors' const transport = unstable_connector(safe) // [!code focus] ``` -------------------------------- ### useCall with To Parameter Source: https://wagmi.sh/react/api/hooks/useCall Example of using the `to` parameter in the `useCall` hook to specify the contract address or recipient. ```tsx import { useCall } from 'wagmi' function App() { const result = useCall({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', // [!code focus] }) } ``` ```typescript import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Importing Hooks Source: https://wagmi.sh/react/api/hooks Demonstrates how to import specific hooks from the wagmi library. ```APIDOC ## Import Hooks ### Description Import necessary hooks from the 'wagmi' library to integrate web3 functionalities into your React application. ### Code Example ```ts import { useConnection } from 'wagmi' ``` ``` -------------------------------- ### Configure App Providers Source: https://wagmi.sh/react/guides/connect-wallet Wraps the application with WagmiProvider and QueryClientProvider to enable wallet connection state management. ```tsx // 1. Import modules import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { WagmiProvider } from 'wagmi' import { config } from './config' // 2. Set up a React Query client. const queryClient = new QueryClient() function App() { // 3. Wrap app with Wagmi and React Query context. return ( {/* ... */} ) } ``` -------------------------------- ### Basic Usage of useConnectorClient Source: https://wagmi.sh/react/api/hooks/useConnectorClient Use the useConnectorClient hook to get a Viem Client object. This is the most basic usage without any specific parameters. ```tsx import { useConnectorClient } from 'wagmi' function App() { const result = useConnectorClient() } ``` -------------------------------- ### Update chain imports from wagmi to wagmi/chains Source: https://wagmi.sh/react/guides/migrate-from-v1-to-v2 The `'wagmi/chains'` entrypoint now proxies all chains from `'viem/chains'`. Import `mainnet` and `sepolia` from `'wagmi/chains'` instead of the main `'wagmi'` entrypoint. ```typescript import { mainnet, sepolia } from 'wagmi' // [!code --] import { mainnet, sepolia } from 'wagmi/chains' // [!code ++] ``` -------------------------------- ### Specify Config for useSwitchChain Source: https://wagmi.sh/react/api/hooks/useSwitchChain Example of passing a specific wagmi configuration object to the useSwitchChain hook. This is useful when managing multiple configurations. ```tsx import { useSwitchChain } from 'wagmi' import { config } from './config' // [!code focus] function App() { const switchChain = useSwitchChain({ config, // [!code focus] }) } ``` ```typescript import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### useCall with Data Parameter Source: https://wagmi.sh/react/api/hooks/useCall Example of using the `data` parameter in the `useCall` hook for contract call data. ```tsx import { useCall } from 'wagmi' function App() { const result = useCall({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) } ``` ```typescript import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Emit on Subscription Begin Source: https://wagmi.sh/react/api/hooks/useWatchBlockNumber Set `emitOnBegin: true` to immediately receive the current block number when the hook subscription starts. This is useful for initializing state with the latest block. ```typescript import { useWatchBlockNumber } from 'wagmi' function App() { useWatchBlockNumber({ emitOnBegin: true, // [!code focus] onBlockNumber(blockNumber) { console.log('New block number', blockNumber) }, }) } ``` ```typescript import { createConfig, http } from '@wagmi/core' import { mainnet, sepolia } from '@wagmi/core/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Use Ethers Signer in Components Source: https://wagmi.sh/react/guides/ethers Example of consuming the custom useEthersSigner hook within a React component. ```ts import { useEthersSigner } from './ethers' function example() { const signer = useEthersSigner() ... } ``` -------------------------------- ### Create WalletOptions Component Source: https://wagmi.sh/react/guides/connect-wallet Displays a list of available connectors and triggers the connection process upon user interaction. ```tsx import * as React from 'react' import { Connector, useConnect, useConnectors } from 'wagmi' export function WalletOptions() { const { connect } = useConnect() const connectors = useConnectors() return connectors.map((connector) => ( )) } ``` -------------------------------- ### Specify Scope Key for useEstimateFeesPerGas Source: https://wagmi.sh/react/api/hooks/useEstimateFeesPerGas Example of how to use the scopeKey parameter to scope the cache for the useEstimateFeesPerGas hook. ```ts import { useEstimateFeesPerGas } from 'wagmi' function App() { const result = useEstimateFeesPerGas({ scopeKey: 'foo', // [!code focus] }) } ``` -------------------------------- ### Import UseFeeHistoryReturnType Source: https://wagmi.sh/react/api/hooks/useFeeHistory Imports the return type for the useFeeHistory hook. This is a common setup for using Wagmi hooks. ```typescript import { type UseFeeHistoryReturnType } from 'wagmi' ``` -------------------------------- ### Import useBlobBaseFee Source: https://wagmi.sh/react/api/hooks/useBlobBaseFee Import the hook from the wagmi package. ```ts import { useBlobBaseFee } from 'wagmi' ``` -------------------------------- ### Specify Contract Address for useStorageAt Source: https://wagmi.sh/react/api/hooks/useStorageAt Provide the contract address to the useStorageAt hook. This example highlights the address parameter. ```typescript import { useStorageAt } from 'wagmi' function App() { const result = useStorageAt({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', // [!code focus] slot: '0x0', }) } ``` ```typescript import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Wagmi Configuration with SSR and Cookie Storage Source: https://wagmi.sh/react/api/utilities/cookieToInitialState Define the Wagmi configuration, enabling server-side rendering (SSR) and configuring cookie storage. This setup is necessary for cookieToInitialState to function correctly. ```typescript import { createConfig, http, cookieStorage, createStorage } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' export const config = createConfig({ chains: [mainnet, sepolia], ssr: true, storage: createStorage({ storage: cookieStorage, }), transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Basic createConfig Usage Source: https://wagmi.sh/react/api/createConfig Create a basic Wagmi config with mainnet and sepolia chains, specifying HTTP transports for each. ```ts-vue import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http('https://mainnet.example.com'), [sepolia.id]: http('https://sepolia.example.com'), }, }) ``` -------------------------------- ### Specify Config for useEstimateFeesPerGas Source: https://wagmi.sh/react/api/hooks/useEstimateFeesPerGas Example of how to pass a custom config object to the useEstimateFeesPerGas hook. ```tsx import { useEstimateFeesPerGas } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useEstimateFeesPerGas({ config, }) } ``` -------------------------------- ### Configure Infinite Read Contracts Source: https://wagmi.sh/react/api/hooks/useInfiniteReadContracts Demonstrates the use of chainId within the contracts definition of useInfiniteReadContracts and the required Wagmi configuration setup. ```tsx import { useInfiniteReadContracts } from 'wagmi' import { abi } from './abi' function App() { const result = useInfiniteReadContracts({ cacheKey: 'mlootAttributes', contracts(pageParam) { const args = [pageParam] as const return [ // ... { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi, functionName: 'getChest', args, chainId: 1 // [!code hl] }, // ... ] } query: { initialPageParam: 0, getNextPageParam: (_lastPage, _allPages, lastPageParam) => { return lastPageParam + 1 } } }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Use Contract Events with From Block Source: https://wagmi.sh/react/api/hooks/useContractEvents Fetches contract events starting from a specified block. Mutually exclusive with `blockHash`. ```tsx import { useContractEvents } from 'wagmi' import { abi } from './abi' import { config } from './config' function App() { const result = useContractEvents({ abi, fromBlock: 69420n, }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Use useConnectorClient with a Specific Chain ID Source: https://wagmi.sh/react/api/hooks/useConnectorClient Get a Viem Client for a specific chain by providing its ID to the useConnectorClient hook. ```tsx import { useConnectorClient } from 'wagmi' function App() { const result = useConnectorClient({ chainId: mainnet.id, }) } ``` -------------------------------- ### Import UseProofParameters Source: https://wagmi.sh/react/api/hooks/useProof Import the type definition for useProof parameters. ```ts import { type UseProofParameters } from 'wagmi' ``` -------------------------------- ### useReadContract with Const-Asserted ABI Source: https://wagmi.sh/react/typescript Example of `useReadContract` utilizing a const-asserted ABI for type-safe contract interactions. ```typescript // @twoslash-cache: {"v":1,"hash":"d7475b91e63cc31608c546a0ebb47f73a765bd7e10587f2f8d3a8df8fdf837c6","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAIAzAK5gAxmnYQwvQXBgAlGMygBhSWlLMxAHhGS4aXswBG7XnRpgocXgEETvAD69SiqJNYZpYANaQA7mDIALoUAsJiEmAAcswAtjBm9DCW1qpg6ppoAGLh4pIx8VrG7KEAOiBYgi7ljrzlROwwfuUAfKG6YPqGpADm1ubJVrxpGWI5onlgNr1wRSZlFVUwNU71jc2UYRORBTBtvB387D2JFkNpRycAvMOSl6GyrDBiACLMaMy8NwpKIxqv72YcxKWwi+TiMFCzBmLRajCw0IhNFIcAA/IheABVWQ/FRqf5oAAKiPiyNmxVCQm24PiUJm7TuxweMCeAI+LW4GOx8lcf0yCjQVTAABVsDBgZTcjsIXS+szWWg3uzSmB2LEsBBSAYZDzfvjMpQQG4RAhEAQ0GgsHBEAB6G1+Zg9WLsAB0cHwNpcmRtzCw7BthAg3jgNp1uL5YkN+mhDEQAE4qE8wD00PgkABGACsVA+vRgsZAYd5+sjifYYFwiAADFQRPhEWIyEg4wBfCjoMV4Qgkcg58x4DpdKCAjEmHrlgxOYSwI4VqCG42mkDC/AJVhcAxwQQiETwOBCVgeZzwCCsEhQXjDj4CTW8VMJACOgjIGBdUdzsYALAmQEmU2nEE/HNoR6fM8CvZhDQ4CskAAJlresCSbRAAA42w7HAu2IJs+3oJg2E4HhpBxYt0gJLQvTcMAj1QFVeHo48lHcTwwAhDFyiMNhmFEGAAHl+HKABuOiGMo5i7zFdiQCpMEwCEkT6LE6jPGjGgAFlBA+EwOEwKSGiaeSpFE1xxPLSo0GtRiqJo4AFIYxSTOUiScCkpQoBcOA4EM+z7KUo9WPiKSIACMhvIYlsgmEoyHKYpyIE08zLL8zxaOinzkucmApMECdYMzAA2ML6IiqK214Wy0oygKsrqEB2DgGwsCwUhsKgLJNRsQ8iqs8TMBc2qZMmbqMtUmANK09gdIwPT1mGxyjzMzSkvmlKKp84zYqPPqavKNyPK8kAovWmLrJYtjauCitSG6sq1uOjLttcqB3L3brfJW3hqqCnANDQTUbsiuyMviy0loxDLUuOnqnMe2qjAgU8AdK0I7pO8Svtq0C0Ea5rWrmzbPFh8pBsifHTt4UbxuKKaZoMw6gY+xaLPBj7kBddnAcqj6QcSlmCd4NmOeR8q7PZl1hdR3gxdKkI4a4nj+PKUIIbF2WLiZXgxwnOEEQ0UkyDRLkSL1MjMmJPX8wNrQxY5I3dTxU2xAFIVRRwa32ZaFU1Q1LViPtiMGCoRcuwtK1bXtR1nTdD0vTEH0/QDBHg1DY2HdGQOQGjLUkEzFDE2Sf8M2zagQLAs0ixN9OoPLSt4JAOsG2RDMAHZ0OoTszW7HDqH7M14Ran7MD4Pa93RXgAAMq1oAASYB9FIcsehbcfamnGBZxgecqCz2Nm7z38C9TJBm+AvMCxHzzq5gxAAGYEMb5DYLb7asJ7Q0aDwvvccHjBh5MMeIaSyqudDi8tdyK3plzfmRNpJSkkGTcSlNNLU3YLpWq+kNhHQ2uTJmy1+aQ3uh9GBF8DpYPWsAwKF0QrXUgfZEqDN+Y8zBtDGydl3rQMkrVHK6Q8qFVoeFTmt0GHkwxuUeqOMWrnnaqQTqrAEEw04cTOBcl+FoyckgiaNN0GzVUSwzwuC+bkwIeQohiiQAkLetg9GICQCXVCrooRaV2Hk2Ic9fali1H+RsRAH67x/oOM5s48STDmZ6IFpLIJCj+ocQRnIgJEthHWMoeULGEi8a6IemYkm8CMkfQ0SgtBaw6ZkLCQYsJgsXSBKsXFBKzCVZCxVI4+y0tGko1FuzGWq9LDrxrlvTOH4Mw32Ln+I+t9T5YzwMUK+lYgL10QpkR+z8O4EGwr2Hun9656AMGQEQzdYLpjsOwQx4ljFhNESATi64FYCVyRw6JsDqQqJKSND46lkHaVQdNbRxTElOTKYAth1StpmIsboyJXjkm2OoUjX5R4Ql4KMREoFhMzHcLQLwmFYAmnIs+jY8RTVJGb2kbI+RwL7nZKebClSryxrvMmp82mmCqW8H+azJFniUX3NBSU8FZ1IV2JoSU7FJi7k7XMW416YKcXnJ8WQPxgq7L0KgeTeFxynKnN5ZlKS8NEbxNaSLZVSSxWpIJek55pjyXKNJdS94tLNEMu+Uyw1fywC83Karc1jDamhPqZUhJaUWlYraQGjpjSgjvhjBmT8NYD7JlGT+XMEyzQ7L2Qckw0ykCzIbkhcgiBW7tnbphTuqz369xAP3WVWpf6gkmLsMeoCrngJubUMRDVTVSI6l1EALaQAmtxueFYVCroQJ7X9bwyRMRyAAJKDrXhvPpO8i531jYXRA6Y66JrLg82SuwM2IGLtmhZuan4FpfmaJ8L5S0bIrT/PgFK63arAXxZtqw6ptv7USztcSe19sJVAQd5QBUjtfWOid07Z3dPnRG7Oa7MzLpGQBdd4yt33 ``` -------------------------------- ### Import useSwitchConnection Source: https://wagmi.sh/react/api/hooks/useSwitchConnection Import the hook from the wagmi package. ```ts import { useSwitchConnection } from 'wagmi' ``` -------------------------------- ### Import useWatchBlocks Source: https://wagmi.sh/react/api/hooks/useWatchBlocks Import the hook from the wagmi package. ```ts import { useWatchBlocks } from 'wagmi' ``` -------------------------------- ### Import useWalletClient Source: https://wagmi.sh/react/api/hooks/useWalletClient Import the hook from the wagmi package. ```ts import { useWalletClient } from 'wagmi' ``` -------------------------------- ### Specify Chain ID for useEstimateFeesPerGas Source: https://wagmi.sh/react/api/hooks/useEstimateFeesPerGas Example of how to specify a chain ID when using the useEstimateFeesPerGas hook. ```tsx import { useEstimateFeesPerGas } from 'wagmi' import { mainnet } from 'wagmi/chains' // [!code focus] function App() { const result = useEstimateFeesPerGas({ chainId: mainnet.id, // [!code focus] }) } ``` -------------------------------- ### Client Factory Source: https://wagmi.sh/react/api/createConfig Custom client creation logic for advanced control over internal Viem clients. ```APIDOC ## client ### Description Function for creating new Viem Clients to be used internally. Exposes more control over the internal Client creation logic versus using the transports property. ### Signature `(parameters: { chain: chains[number] }) => Client` ### Request Example ```ts const config = createConfig({ chains: [mainnet, sepolia], client({ chain }) { return createClient({ chain, transport: http('https://...') }) }, }) ``` ``` -------------------------------- ### onError Callback Source: https://wagmi.sh/react/api/hooks/useWatchContractEvent A callback function that is executed when an error occurs during the process of getting the block number. ```APIDOC ## onError ### Description Error thrown from getting the block number. ### Type `((error: Error) => void) | undefined` ### Request Example ```tsx import { useWatchContractEvent } from 'wagmi' import { abi } from './abi' function App() { useWatchContractEvent({ address: '0x6b175474e89094c44da98b954eedeac495271d0f', abi, eventName: 'Transfer', onLogs(logs) { console.log('New logs!', logs) }, onError(error) { // [!code focus] console.log('Error', error) // [!code focus] } // [!code focus] }) } ``` ``` -------------------------------- ### getNextPageParam Source: https://wagmi.sh/react/api/hooks/useEnsResolver Function to get the previous cursor for infinite queries, also used to determine `hasPreviousPage`. ```APIDOC ## getNextPageParam ### Description This function can be set to automatically get the previous cursor for infinite queries. The result will also be used to determine the value of `hasPreviousPage`. ### Signature `(lastPage: {{TData}}, allPages: {{TData}}[], lastPageParam: {{TPageParam}}, allPageParams: {{TPageParam}}[]) => {{TPageParam}} | undefined | null` ``` -------------------------------- ### Import useConfig Source: https://wagmi.sh/react/api/hooks/useConfig Import the hook from the wagmi package. ```ts import { useConfig } from 'wagmi' ``` -------------------------------- ### Coinbase Wallet Connector Configuration Source: https://wagmi.sh/react/api/connectors/coinbaseWallet How to import and initialize the Coinbase Wallet connector within the Wagmi configuration. ```APIDOC ## Coinbase Wallet Connector ### Description The `coinbaseWallet` connector allows users to connect their Coinbase Wallet to your application. It requires the `@coinbase/wallet-sdk` dependency. ### Usage ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' import { coinbaseWallet } from '@wagmi/connectors' export const config = createConfig({ chains: [mainnet, sepolia], connectors: [ coinbaseWallet({ appName: 'My Wagmi App', appLogoUrl: 'https://example.com/logo.png' }) ], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` ### Parameters - **appName** (string) - Optional - Application name displayed upon connection. - **appLogoUrl** (string) - Optional - Application logo image URL. - **preference** (object) - Optional - Configuration for wallet display options. - **attribution** (object) - Optional - Configuration for Coinbase Smart Wallet (auto: boolean, dataSuffix: hex string). - **keysUrl** (string) - Optional - URL for the keys popup. - **options** ("all" | "eoaOnly" | "smartWalletOnly") - Optional - Preference for the type of wallet to display. ``` -------------------------------- ### Provide Custom Config to useGasPrice Source: https://wagmi.sh/react/api/hooks/useGasPrice Use a custom wagmi configuration with the useGasPrice hook by passing the config object. This is useful for advanced setups or when not using the nearest WagmiProvider. ```tsx import { useGasPrice } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useGasPrice({ config, // [!code focus] }) } ``` ```typescript import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Use Ethers Provider in Components Source: https://wagmi.sh/react/guides/ethers Example of consuming the custom useEthersProvider hook within a React component. ```typescript import { useEthersProvider } from './ethers' function Example() { const provider = useEthersProvider() ... } ``` -------------------------------- ### Import useBlock Source: https://wagmi.sh/react/api/hooks/useBlock Import the hook from the wagmi package. ```ts import { useBlock } from 'wagmi' ``` -------------------------------- ### Display ENS Name with Wagmi Hooks Source: https://wagmi.sh/react/getting-started Use `useConnection` to get the user's address and `useEnsName` to fetch their ENS name. Handles loading and error states. ```tsx import { useConnection, useEnsName } from 'wagmi' export function Profile() { const { address } = useConnection() const { data, error, status } = useEnsName({ address }) if (status === 'pending') return
Loading ENS name
if (status === 'error') return
Error fetching ENS name: {error.message}
return
ENS name: {data}
} ``` -------------------------------- ### Implement MintNFT Component Source: https://wagmi.sh/react/guides/write-to-contract Uses useWriteContract to initiate transactions and useWaitForTransactionReceipt to track confirmation status. ```tsx import * as React from 'react' import { type BaseError, useWaitForTransactionReceipt, useWriteContract } from 'wagmi' import { abi } from './abi' export function MintNFT() { const { data: hash, error, isPending, writeContract } = useWriteContract() async function submit(e: React.FormEvent) { e.preventDefault() const formData = new FormData(e.target as HTMLFormElement) const tokenId = formData.get('tokenId') as string writeContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi, functionName: 'mint', args: [BigInt(tokenId)], }) } const { isLoading: isConfirming, isSuccess: isConfirmed } = useWaitForTransactionReceipt({ hash, }) return (
{hash &&
Transaction Hash: {hash}
} {isConfirming &&
Waiting for confirmation...
} {isConfirmed &&
Transaction confirmed.
} {error && (
Error: {(error as BaseError).shortMessage || error.message}
)}
) } ``` -------------------------------- ### Import useBytecode Source: https://wagmi.sh/react/api/hooks/useBytecode Import the hook from the wagmi package. ```ts import { useBytecode } from 'wagmi' ``` -------------------------------- ### useStorageAt Hook Configuration Source: https://wagmi.sh/react/api/hooks/useStorageAt Demonstrates how to use the `useStorageAt` hook with custom configuration and scope. ```APIDOC ## useStorageAt Hook Configuration ### Description This section shows how to configure the `useStorageAt` hook with a custom `config` object and a `scopeKey` for cache management. ### Method N/A (Hook usage) ### Endpoint N/A (Hook usage) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **config** (`Config | undefined`) - Optional: A `Config` object to use instead of retrieving from the nearest `WagmiProvider`. - **scopeKey** (`string | undefined`) - Optional: Scopes the cache to a given context. Hooks with identical contexts share the same cache. - **address** (`string`) - Required: The address of the storage. - **slot** (`string`) - Required: The slot of the storage. ### Request Example ```tsx import { useStorageAt } from 'wagmi' import { config } from './config' function App() { const result = useStorageAt({ config, scopeKey: 'foo', address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', slot: '0x0', }) } ``` ### Response #### Success Response (200) N/A (Hook return value is not detailed here) #### Response Example N/A ``` -------------------------------- ### Query Configuration Options Source: https://wagmi.sh/react/api/hooks/useBlobBaseFee Configuration options for setting initial data, pagination, metadata, and network behavior for queries. ```APIDOC ## Query Configuration Options ### initialData `{{TData}} | (() => {{TData}}) | undefined` * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been created or cached yet) * If set to a function, the function will be called **once** during the shared/root query initialization, and be expected to synchronously return the initialData * Initial data is considered stale by default unless a `staleTime` has been set. * `initialData` **is persisted** to the cache ### initialDataUpdatedAt `number | ((() => number | undefined)) | undefined` If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. ### initialPageParam `{{TPageParam}}` The initial page parameter to be passed to the query function. ### getPreviousPageParam This function can be set to automatically get the previous cursor for infinite queries. The result will also be used to determine the value of `hasPreviousPage`. `(firstPage: {{TData}}, allPages: {{TData}}[], firstPageParam: {{TPageParam}}, allPageParams: {{TPageParam}}[]) => {{TPageParam}} | undefined | null` ### getNextPageParam This function can be set to automatically get the previous cursor for infinite queries. The result will also be used to determine the value of `hasPreviousPage`. `(lastPage: {{TData}}, allPages: {{TData}}[], lastPageParam: {{TPageParam}}, allPageParams: {{TPageParam}}[]) => {{TPageParam}} | undefined | null` ### meta `Record | undefined` If set, stores additional information on the query cache entry that can be used as needed. It will be accessible wherever the `query` is available, and is also part of the `QueryFunctionContext` provided to the `queryFn`. ### networkMode `'online' | 'always' | 'offlineFirst' | undefined` * Defaults to `'online'` * see [Network Mode](https://tanstack.com/query/v5/docs/react/guides/network-mode) for more information. ### notifyOnChangeProps `string[] | 'all' | (() => string[] | 'all') | undefined` * If set, the component will only re-render if any of the listed properties change. * If set to `['data', 'error']` for example, the component will only re-render when the `data` or `error` properties change. * If set to `'all'`, the component will opt-out of smart tracking and re-render whenever a query is updated. * If set to a function, the function will be executed to compute the list of properties. * By default, access to properties will be tracked, and the component will only re-render when one of the tracked properties change. ### placeholderData `{{TData}} | ((previousValue: {{TData}} | undefined; previousQuery: Query | undefined) => {{TData}}) | undefined` * If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `pending` state. * `placeholderData` is **not persisted** to the cache * If you provide a function for `placeholderData`, as a first argument you will receive previously watched query data if available, and the second argument will be the complete previousQuery instance. ### queryClient `QueryClient | undefined` Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used. ### refetchInterval `number | false | ((data: {{TData}} | undefined, query: Query) => number | false | undefined) | undefined` * If set to a number, all queries will continuously refetch at this frequency in milliseconds * If set to a function, the function will be executed with the latest data and query to compute a frequency ### refetchIntervalInBackground `boolean | undefined` If set to `true`, queries that are set to continuously refetch with a `refetchInterval` will continue to refetch while their tab/window is in the background ### refetchOnMount `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` * Defaults to `true` * If set to `true`, the query will refetch on mount if the data is stale. * If set to `false`, the query will not refetch on mount. * If set to `'always'`, the query will always refetch on mount. * If set to a function, the function will be executed with the query to compute the value ### refetchOnReconnect `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` * Defaults to `true` * If set to `true`, the query will refetch on reconnect if the data is stale. * If set to `false`, the query will not refetch on reconnect. * If set to `'always'`, the query will always refetch on reconnect. * If set to a function, the function will be executed with the query to compute the value ``` -------------------------------- ### Get item from storage Source: https://wagmi.sh/react/api/createStorage Retrieve an item from the storage object using its key. A default value can be provided. ```typescript import { createStorage } from '{{packageName}}' const storage = createStorage({ storage: localStorage }) const recentConnectorId = storage.getItem('recentConnectorId') ``` -------------------------------- ### Import useDisconnect Source: https://wagmi.sh/react/api/hooks/useDisconnect Import the hook from the wagmi package. ```ts import { useDisconnect } from 'wagmi' ``` -------------------------------- ### Configure baseAccount Source: https://wagmi.sh/react/api/connectors/baseAccount Initialize the Wagmi config with the baseAccount connector. ```ts import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' import { baseAccount } from '{{connectorsPackageName}}' // [!code hl] export const config = createConfig({ chains: [mainnet, sepolia], connectors: [baseAccount()], // [!code hl] transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Implement useReconnect in React Source: https://wagmi.sh/react/api/hooks/useReconnect Example of using the useReconnect hook within a React component to trigger a reconnection attempt. ```tsx import { useReconnect } from 'wagmi' import { mainnet } from 'wagmi/chains' import { useEffect } from 'react' function App() { const reconnect = useReconnect() useEffect(() => { reconnect.mutate({ connectors: reconnect.connectors }) }, []) } ``` -------------------------------- ### Switch Chain in React Component Source: https://wagmi.sh/react/api/hooks/useSwitchChain Use the useSwitchChain hook within a React component to render buttons that switch the connected wallet's chain. This example also uses useChains to fetch available chains. ```tsx import { useChains, useSwitchChain } from 'wagmi' function App() { const switchChain = useSwitchChain() const chains = useChains() return (
{chains.map((chain) => ( ))}
) } ``` -------------------------------- ### Implement Wallet Options Component Source: https://wagmi.sh/react/guides/connect-wallet Lists available connectors and provides a button to trigger the connection process for each. ```tsx import * as React from 'react' import { Connector, useConnect, useConnectors } from 'wagmi' export function WalletOptions() { const { connect } = useConnect() const connectors = useConnectors() return connectors.map((connector) => ( connect({ connector })} /> )) } function WalletOption({ connector, onClick, }: { connector: Connector onClick: () => void }) { const [ready, setReady] = React.useState(false) React.useEffect(() => { ;(async () => { const provider = await connector.getProvider() setReady(!!provider) })() }, [connector]) return ( ) } ``` -------------------------------- ### Configure WalletConnect with Metadata Source: https://wagmi.sh/react/api/connectors/walletConnect Provide app metadata such as name, description, and URL for the WalletConnect connection request. ```typescript import { walletConnect } from '{{connectorsPackageName}}' const connector = walletConnect({ projectId: '3fcc6bba6f1de962d911bb5b5c3dba68', metadata: { // [!code focus] name: 'Example', // [!code focus] description: 'Example website', // [!code focus] url: 'https://example.com', // [!code focus] }, // [!code focus] }) ``` -------------------------------- ### Read Token Balance with useReadContract Source: https://wagmi.sh/react/guides/read-from-contract Use `useReadContract` to fetch data from a contract's view function. Ensure the contract configuration and function details are correctly provided. This example reads the token balance for a specific address. ```tsx import { useReadContract } from 'wagmi' import { wagmiContractConfig } from './contracts' function ReadContract() { const { data: balance } = useReadContract({ ...wagmiContractConfig, functionName: 'balanceOf', args: ['0x03A71968491d55603FFe1b11A9e23eF013f75bCF'], }) return (
Balance: {balance?.toString()}
) } ``` -------------------------------- ### Import Chains Source: https://wagmi.sh/react/api/chains Import Chain objects from the 'wagmi/chains' entrypoint, which proxies all chains from 'viem/chains'. ```APIDOC ## Import Chains ### Description Import Chain objects from the `'wagmi/chains'` entrypoint. This entrypoint proxies all chains from `'viem/chains'`. ### Code Example ```ts import { mainnet } from 'wagmi/chains' ``` ``` -------------------------------- ### Integrate Mint NFT into App Entrypoint Source: https://wagmi.sh/react/guides/write-to-contract Wraps the application with WagmiProvider and QueryClientProvider, and includes the MintNft component. ```tsx import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { WagmiProvider } from 'wagmi' import { config } from './config' import { MintNft } from './mint-nft' // [!code ++] const queryClient = new QueryClient() function App() { return ( // [!code ++] ) } ``` -------------------------------- ### Specify Fee Type for useEstimateFeesPerGas Source: https://wagmi.sh/react/api/hooks/useEstimateFeesPerGas Example of how to specify the fee type ('legacy' or 'eip1559') for the useEstimateFeesPerGas hook. Defaults to 'eip1559'. ```ts import { useEstimateFeesPerGas } from 'wagmi' function App() { const result = useEstimateFeesPerGas({ type: 'legacy', // [!code focus] }) } ``` -------------------------------- ### Import useBalance Source: https://wagmi.sh/react/api/hooks/useBalance Import the hook from the wagmi package. ```ts import { useBalance } from 'wagmi' ``` -------------------------------- ### Get ENS Text Record Source: https://wagmi.sh/react/api/hooks/useEnsText Fetches an ENS text record for a given name. Ensure `wagmi` is set up with a `WagmiProvider`. ```typescript import { useEnsText } from 'wagmi' import { normalize } from 'viem/ens' function App() { const result = useEnsText({ name: normalize('wevm.eth'), // [!code focus] key: 'com.twitter', }) } ``` -------------------------------- ### Using Custom Configuration with `useVerifyTypedData` Source: https://wagmi.sh/react/api/hooks/useVerifyTypedData Demonstrates how to use a custom `config` object with the `useVerifyTypedData` hook, bypassing the nearest `WagmiProvider`. ```APIDOC ## POST /api/verifyTypedData (Example) ### Description This example shows how to use a custom configuration object with the `useVerifyTypedData` hook. ### Method POST (Implied by hook usage) ### Endpoint N/A (Hook usage) ### Parameters #### Request Body - **config** (`Config | undefined`) - Required - The configuration object to use instead of retrieving from the nearest `WagmiProvider`. - **domain** (`object`) - Required - The domain information for the typed data. - **types** (`object`) - Required - The type definitions for the typed data. - **message** (`object`) - Required - The message content for the typed data. - **primaryType** (`string`) - Required - The primary type of the message. - **address** (`string`) - Required - The address associated with the signature. - **signature** (`string`) - Required - The signature of the message. ### Request Example ```json { "config": { "chains": [ { "id": 1, "name": "Ethereum Mainnet" }, { "id": 11155111, "name": "Sepolia" } ], "transports": { "1": "http://localhost:8545", "11155111": "http://localhost:8546" } }, "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" } ] }, "message": { "from": { "name": "Cow", "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826" }, "to": { "name": "Bob", "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB" }, "contents": "Hello, Bob!" }, "primaryType": "Mail", "address": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266", "signature": "0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c" } ``` ### Response #### Success Response (200) - **result** (`object`) - The result of the verification. #### Response Example ```json { "result": true } ``` ``` -------------------------------- ### Pagination and Control Methods Source: https://wagmi.sh/react/api/hooks/useBlockNumber Methods for managing infinite queries and manual refetching. ```APIDOC ## Pagination and Control ### Methods - **fetchNextPage** (options?: FetchNextPageOptions) => Promise - Fetches the next page of results. - **fetchPreviousPage** (options?: FetchPreviousPageOptions) => Promise - Fetches the previous page of results. - **refetch** (options: { cancelRefetch?: boolean; throwOnError?: boolean }) => Promise - Manually triggers a query refetch. ### Boolean Flags - **hasNextPage** (boolean) - True if a next page is available. - **hasPreviousPage** (boolean) - True if a previous page is available. - **isFetchingNextPage** (boolean) - True while fetching the next page. - **isFetchingPreviousPage** (boolean) - True while fetching the previous page. ``` -------------------------------- ### Import useWatchPendingTransactions Source: https://wagmi.sh/react/api/hooks/useWatchPendingTransactions Import the hook from the wagmi package. ```ts import { useWatchPendingTransactions } from 'wagmi' ``` -------------------------------- ### Import UseEnsTextReturnType Source: https://wagmi.sh/react/api/hooks/useEnsText Imports the return type for the UseEnsText hook from the wagmi library. This is a common setup for using wagmi hooks. ```typescript import { type UseEnsTextReturnType } from 'wagmi' ``` -------------------------------- ### Waiting for Call Status by ID Source: https://wagmi.sh/react/api/hooks/useWaitForCallsStatus Fetch the status of a call bundle using its unique identifier. This example demonstrates an asynchronous usage. ```typescript import { useWaitForCallsStatus } from '@wagmi/core' import { config } from './config' const status = await useWaitForCallsStatus({ id: '0x1234567890abcdef', // [!code focus] }) ``` ```typescript import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Configuration Options Source: https://wagmi.sh/react/api/createConfig Overview of the primary configuration properties used to initialize the Wagmi Config object. ```APIDOC ## Configuration Properties ### batch - **Type**: `{ multicall?: boolean | { batchSize?: number; wait?: number } } | { [id: number]: { multicall?: boolean | { batchSize?: number; wait?: number } } }` - **Description**: Batch settings for multicall. Defaults to `{ multicall: true }`. ### cacheTime - **Type**: `number | { [id: number]: number }` - **Description**: Frequency in milliseconds for polling enabled features. Defaults to `pollingInterval` or `4000`. ### pollingInterval - **Type**: `number | { [id: number]: number }` - **Description**: Frequency in milliseconds for polling enabled features. Defaults to `4000`. ### transports - **Type**: `Record` - **Description**: Mapping of chain IDs to Transports used for internal Viem client creation. ``` -------------------------------- ### Configure Connect with RPC Method Source: https://wagmi.sh/react/api/connectors/metaMask Use this parameter to execute a specific RPC method immediately after connecting. ```ts import { metaMask } from '{{connectorsPackageName}}' const connector = metaMask({ connectWith: { // [!code focus] method: 'eth_requestAccounts', // [!code focus] params: [], // [!code focus] } }) ``` -------------------------------- ### Wallet Connection Options Source: https://wagmi.sh/react/guides/connect-wallet Renders a list of available wallet connectors using `useConnectors` and allows users to connect by clicking on a wallet option. It checks if the wallet provider is ready before enabling the button. ```tsx import * as React from 'react' import { Connector, useConnect, useConnectors } from 'wagmi' export function WalletOptions() { const { connect } = useConnect() const connectors = useConnectors() return connectors.map((connector) => ( connect({ connector })} /> )) } function WalletOption({ connector, onClick, }: { connector: Connector onClick: () => void }) { const [ready, setReady] = React.useState(false) React.useEffect(() => { ;(async () => { const provider = await connector.getProvider() setReady(!!provider) })() }, [connector]) return ( ) } ``` -------------------------------- ### Import Parameters Source: https://wagmi.sh/react/api/hooks/useWatchBlocks Import the parameter type definition for useWatchBlocks. ```ts import { type UseWatchBlocksParameters } from 'wagmi' ``` -------------------------------- ### Import coinbaseWallet Source: https://wagmi.sh/react/api/connectors/coinbaseWallet Import the connector from the connectors package. ```ts import { coinbaseWallet } from '{{connectorsPackageName}}' ``` -------------------------------- ### Import useChains Source: https://wagmi.sh/react/api/hooks/useChains Import the hook from the wagmi package. ```ts import { useChains } from 'wagmi' ``` -------------------------------- ### Basic useCall Usage Source: https://wagmi.sh/react/api/hooks/useCall Demonstrates a basic usage of the `useCall` hook with account, data, and to parameters. ```tsx import { useCall } from 'wagmi' function App() { const result = useCall({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) } ``` ```typescript import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Specify Block Tag for useStorageAt Source: https://wagmi.sh/react/api/hooks/useStorageAt Use the blockTag parameter to specify a block identifier like 'safe' for the useStorageAt hook. This example focuses on the blockTag parameter. ```typescript import { useStorageAt } from 'wagmi' function App() { const result = useStorageAt({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', blockTag: 'safe', // [!code focus] slot: '0x0', }) } ``` ```typescript import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Specify Block Number for useStorageAt Source: https://wagmi.sh/react/api/hooks/useStorageAt Query storage at a specific block number using the blockNumber parameter in the useStorageAt hook. This example highlights the blockNumber parameter. ```typescript import { useStorageAt } from 'wagmi' function App() { const result = useStorageAt({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', blockNumber: 16280770n, // [!code focus] slot: '0x0', }) } ``` ```typescript import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Use useSimulateContract with scopeKey Source: https://wagmi.sh/react/api/hooks/useSimulateContract Demonstrates how to use the `useSimulateContract` hook with a `scopeKey` to scope the cache to a specific context. Hooks with identical context will share the same cache. ```tsx import { useSimulateContract } from 'wagmi' import { abi } from './abi' import { config } from './config' function App() { const result = useSimulateContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], scopeKey: 'foo', // [!code focus] }) } ``` -------------------------------- ### UseClient with custom config Source: https://wagmi.sh/react/api/hooks/useClient Provide a specific configuration object instead of using the nearest WagmiProvider. ```tsx import { useClient } from 'wagmi' import { config } from './config' // [!code focus] function App() { const client = useClient({ config, // [!code focus] }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Send Multiple Calls with useSendCalls Source: https://wagmi.sh/react/api/hooks/useSendCalls Use the useSendCalls hook to send a batch of calls to the network. This example demonstrates sending two transactions with different parameters. ```tsx import { useSendCalls } from 'wagmi' import { parseEther } from 'viem' function App() { const sendCalls = useSendCalls() return ( ) } ``` -------------------------------- ### Import connectors from 'wagmi/connectors' Source: https://wagmi.sh/react/guides/migrate-from-v1-to-v2 Individual connector entrypoints have been removed. Import all connectors from the unified `'wagmi/connectors'` entrypoint. ```typescript import { InjectedConnector } from 'wagmi/connectors/injected' // [!code --] import { CoinbaseWalletConnector } from 'wagmi/connectors/coinbaseWallet' // [!code --] import { coinbaseWallet, injected } from 'wagmi/connectors' // [!code ++] ``` -------------------------------- ### Fetch ENS Name at a Specific Block Tag Source: https://wagmi.sh/react/api/hooks/useEnsName Get the ENS name for an address using a block tag like 'latest'. Ensure wagmi is configured. ```typescript import { useEnsName } from 'wagmi' function App() { const result = useEnsName({ address: '0xd2135CfB216b74109775236E36d4b433F1DF507B', blockTag: 'latest', // [!code focus] }) } ``` ```typescript import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### useSignTypedData Hook Usage Source: https://wagmi.sh/react/api/hooks/useSignTypedData Example of how to use the useSignTypedData hook to sign typed data. This includes defining the types, primary type, and message, then calling the mutate function. ```APIDOC ## POST /signTypedData ### Description Signs typed data using the provided wallet. ### Method POST ### Endpoint /signTypedData ### Parameters #### Request Body - **types** (object) - Required - The types used in the typed data. - **primaryType** (string) - Required - The primary type of the typed data. - **message** (object) - Required - The message to be signed. ### Request Example ```json { "types": { "Person": [ { "name": "name", "type": "string" }, { "name": "wallet", "type": "address" } ], "Mail": [ { "name": "from", "type": "Person" }, { "name": "to", "type": "Person" }, { "name": "contents", "type": "string" } ] }, "primaryType": "Mail", "message": { "from": { "name": "Cow", "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826" }, "to": { "name": "Bob", "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB" }, "contents": "Hello, Bob!" } } ``` ### Response #### Success Response (200) - **signature** (string) - The signature of the typed data. #### Response Example ```json { "signature": "0x..." } ``` ``` -------------------------------- ### Handle Transaction Replacements Source: https://wagmi.sh/react/api/hooks/useWaitForTransactionReceipt Use the `onReplaced` callback to be notified when a transaction is replaced, for example, due to a higher gas price. It provides details about the replaced and replacing transactions. ```typescript import { useWaitForTransactionReceipt } from 'wagmi' function App() { const result = useWaitForTransactionReceipt({ hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', onReplaced: replacement => console.log(replacement), // [!code focus] }) } ``` -------------------------------- ### useBlock Hook Parameters Source: https://wagmi.sh/react/api/hooks/useBlock Configuration options for the useBlock hook. ```APIDOC ## useBlock Hook Parameters ### Description Configuration options for the `useBlock` hook. ### Parameters #### Request Body - **includeTransactions** (boolean) - Optional - Whether or not to include transactions as objects. - **scopeKey** (string | undefined) - Optional - Scopes the cache to a given context. Hooks that have identical context will share the same cache. - **watch** (boolean | UseWatchBlockParameters | undefined) - Optional - Enables/disables listening for block changes. Can pass a subset of [`UseWatchBlocksParameters`](/react/api/hooks/useWatchBlocks) directly to [`useBlock`](/react/api/hooks/useBlock). ### Request Example ```json { "includeTransactions": true, "scopeKey": "foo", "watch": true } ``` ### Response #### Success Response (200) - **block** (object) - The fetched block information. #### Response Example ```json { "block": { "hash": "0x...", "number": 1234567, "timestamp": 1678886400 } } ``` ``` -------------------------------- ### Specify Storage Slot for useStorageAt Source: https://wagmi.sh/react/api/hooks/useStorageAt Specify the storage slot (as a hex encoded value) to retrieve data from using the useStorageAt hook. This example focuses on the slot parameter. ```typescript import { useStorageAt } from 'wagmi' function App() { const result = useStorageAt({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', slot: '0x0', // [!code focus] }) } ``` ```typescript import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Import useWatchAsset Source: https://wagmi.sh/react/api/hooks/useWatchAsset Import the hook from the wagmi package. ```ts import { useWatchAsset } from 'wagmi' ``` -------------------------------- ### Configure GasPrice Parameter Source: https://wagmi.sh/react/api/hooks/useEstimateGas Sets the price in wei per gas for legacy transactions. ```ts // {"path":"/vercel/path0/site/react/api/hooks/useEstimateGas.md","from":4107,"to":4417} import { useEstimateGas } from 'wagmi' import { parseEther, parseGwei } from 'viem' import { config } from './config' function App() { const result = useEstimateGas({ gasPrice: parseGwei('20'), // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Client Viem Actions with Wagmi Source: https://wagmi.sh/react/guides/viem Uses `usePublicClient` and `useWalletClient` to access Viem client methods directly. This approach may lead to larger bundle sizes compared to tree-shakable actions. ```tsx // 1. Import modules. import { useMutation, useQuery } from '@tanstack/react-query' import { http, createConfig, useClient, useConnectorClient } from 'wagmi' import { base, mainnet, optimism, zora } from 'wagmi/chains' // 2. Set up a Wagmi Config export const config = createConfig({ chains: [base, mainnet, optimism, zora], transports: { [base.id]: http(), [mainnet.id]: http(), [optimism.id]: http(), [zora.id]: http(), }, }) function Example() { // 3. Extract a Viem Client for the current active chain. // [!code hl] const publicClient = useClient({ config }) // [!code hl] // 4. Create a "custom" Query Hook that utilizes the Client. // [!code hl] const { data: logs } = useQuery({ // [!code hl] queryKey: ['logs', publicClient.uid], // [!code hl] queryFn: () => publicClient.getLogs(/* ... */) // [!code hl] }) // [!code hl] // 5. Extract a Viem Client for the current active chain & account. // [!code hl] const { data: walletClient } = useConnectorClient({ config }) // [!code hl] // 6. Create a "custom" Mutation Hook that utilizes the Client. // [!code hl] const { mutate } = useMutation({ mutationFn: (asset) => walletClient.watchAsset(asset) // [!code hl] }) // [!code hl] return (
{/* ... */}
) } ``` -------------------------------- ### Basic Usage of useSignMessage Hook Source: https://wagmi.sh/react/api/hooks/useSignMessage Use the useSignMessage hook to get a mutate function for signing messages. Attach the mutate function to an onClick event handler on a button. ```tsx import { useSignMessage } from 'wagmi' function App() { const signMessage = useSignMessage() return ( ) } ``` -------------------------------- ### Get Current Chain ID with useChainId Source: https://wagmi.sh/react/api/hooks/useChainId Use the useChainId hook within a React component to access the current chain ID. Ensure Wagmi is set up in your application. ```tsx import { useChainId } from 'wagmi' function App() { const chainId = useChainId() } ``` -------------------------------- ### Configuring Storage with createConfig Source: https://wagmi.sh/react/api/createConfig Provide custom `Storage` for persisting Wagmi's state between sessions using `createStorage`. Defaults to `window.localStorage` if available. ```ts-vue import { createConfig, createStorage, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' const config = createConfig({ chains: [mainnet, sepolia], storage: createStorage({ storage: window.localStorage }), transports: { [mainnet.id]: http('https://mainnet.example.com'), [sepolia.id]: http('https://sepolia.example.com'), }, }) ``` -------------------------------- ### Import cookieToInitialState Source: https://wagmi.sh/react/api/utilities/cookieToInitialState Import the cookieToInitialState utility from the wagmi package. ```typescript import { cookieToInitialState } from '{{packageName}}' ``` -------------------------------- ### Wrap App in Context Provider Source: https://wagmi.sh/react/guides/connect-wallet Integrate Wagmi and React Query providers into the application root to enable reactive state and caching. ```tsx // 1. Import modules import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { WagmiProvider } from 'wagmi' import { config } from './config' // 2. Set up a React Query client. const queryClient = new QueryClient() function App() { // 3. Wrap app with Wagmi and React Query context. return ( {/** ... */} ) } ``` ```tsx import { http, createConfig } from 'wagmi' import { base, mainnet, optimism } from 'wagmi/chains' import { injected, metaMask, safe, walletConnect } from 'wagmi/connectors' const projectId = '' export const config = createConfig({ chains: [mainnet, base], connectors: [ injected(), walletConnect({ projectId }), metaMask(), safe(), ], transports: { [mainnet.id]: http(), [base.id]: http(), }, }) ``` -------------------------------- ### Sign Typed Data with useSignTypedData Source: https://wagmi.sh/react/api/hooks/useSignTypedData Use the useSignTypedData hook to sign a structured message. This example defines the 'Person' and 'Mail' types according to EIP-712 and signs a 'Mail' message. ```tsx import { useSignTypedData } from 'wagmi' function App() { const signTypedData = useSignTypedData() return ( ) } ``` -------------------------------- ### Import UseBlobBaseFeeParameters Source: https://wagmi.sh/react/api/hooks/useBlobBaseFee Import the parameter type definition for the hook. ```ts import { type UseBlobBaseFeeParameters } from 'wagmi' ``` -------------------------------- ### Specify Chain ID for useStorageAt Source: https://wagmi.sh/react/api/hooks/useStorageAt Specify the chain ID to query storage on a particular network using the chainId parameter in the useStorageAt hook. This example highlights the chainId parameter. ```typescript import { useStorageAt } from 'wagmi' import { mainnet } from '@wagmi/core/chains' function App() { const result = useStorageAt({ chainId: mainnet.id, // [!code focus] address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', slot: '0x0', }) } ``` ```typescript import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Import CoinbaseWalletParameters Source: https://wagmi.sh/react/api/connectors/coinbaseWallet Import the type definition for connector parameters. ```ts import { type CoinbaseWalletParameters } from '{{connectorsPackageName}}' ``` -------------------------------- ### getProof Action Source: https://wagmi.sh/react/api/hooks/useProof Reference to the getProof action. ```APIDOC ## Action: getProof ### Description Provides a link to the `getProof` action documentation. ### Endpoint [/core/api/actions/getProof](/core/api/actions/getProof) ``` -------------------------------- ### Mutation Callbacks and Options Source: https://wagmi.sh/react/api/hooks/useSignTypedData Details on callback functions and configuration options for mutations. ```APIDOC ## Mutation Options ### onMutate `((variables: {{TVariables}}) => Promise | context | void) | undefined` * This function will fire before the mutation function is fired and is passed the same variables the mutation function would receive. * Useful to perform optimistic updates to a resource in hopes that the mutation succeeds. * The value returned from this function will be passed to both the `onError` and `onSettled` functions in the event of a mutation failure and can be useful for rolling back optimistic updates. ### onSuccess `((data: {{TData}}, variables: {{TVariables}}, context?: context | undefined) => Promise | unknown) | undefined` This function will fire when the mutation is successful and will be passed the mutation's result. ### onSettled `((data: {{TData}}, error: {{TError}}, variables: {{TVariables}}, context?: context | undefined) => Promise | unknown) | undefined` This function will fire when the mutation is either successfully fetched or encounters an error and be passed either the data or error. ### queryClient `QueryClient` Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used. ### retry `boolean | number | ((failureCount: number, error: {{TError}}) => boolean) | undefined` * Defaults to `0`. * If `false`, failed mutations will not retry. * If `true`, failed mutations will retry infinitely. * If set to an `number`, e.g. `3`, failed mutations will retry until the failed mutations count meets that number. ### retryDelay `number | ((retryAttempt: number, error: {{TError}}) => number) | undefined` * This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds. * A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff. * A function like `attempt => attempt * 1000` applies linear backoff. ``` -------------------------------- ### Configure Connect and Sign Source: https://wagmi.sh/react/api/connectors/metaMask Use this parameter to automatically prompt the user to sign a message upon connection. ```ts import { metaMask } from '{{connectorsPackageName}}' const connector = metaMask({ connectAndSign: 'Sign this message to connect', // [!code focus] }) ``` -------------------------------- ### Import useTransactionReceipt Source: https://wagmi.sh/react/api/hooks/useTransactionReceipt Import the hook from the wagmi package. ```ts import { useTransactionReceipt } from 'wagmi' ``` -------------------------------- ### Import useClient Source: https://wagmi.sh/react/api/hooks/useClient Import the useClient hook from the wagmi package. ```ts import { useClient } from 'wagmi' ``` -------------------------------- ### Action: readContracts Source: https://wagmi.sh/react/api/hooks/useReadContracts Link to the documentation for the `readContracts` action. ```APIDOC ## Action: readContracts ### Description Reference to the `readContracts` API action documentation. ### Link [/core/api/actions/readContracts](/core/api/actions/readContracts) ``` -------------------------------- ### Import useConnection Source: https://wagmi.sh/react/api/hooks/useConnection Import the hook from the wagmi package. ```ts import { useConnection } from 'wagmi' ``` -------------------------------- ### Conditional data refresh every N blocks Source: https://wagmi.sh/react/guides/migrate-from-v1-to-v2 Demonstrates how to manually refresh data based on block numbers. This example refreshes the balance data every 5 blocks by checking the `blockNumber` and conditionally invalidating queries. ```typescript const { data: blockNumber } = useBlockNumber({ watch: true }) const { data: balance, queryKey } = useBalance({ address: '0x4557B18E779944BFE9d78A672452331C186a9f48', }) useEffect(() => { if (blockNumber && blockNumber % 5n === 0n) // [!code focus] queryClient.invalidateQueries({ queryKey }) // [!code focus] }, [blockNumber, queryClient]) ``` -------------------------------- ### Configure Wagmi with WalletConnect Source: https://wagmi.sh/react/api/connectors/walletConnect Set up Wagmi's createConfig with the WalletConnect connector, specifying chains, transports, and the WalletConnect project ID. ```typescript import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' import { walletConnect } from '{{connectorsPackageName}}' export const config = createConfig({ chains: [mainnet, sepolia], connectors: [ walletConnect({ projectId: '3fcc6bba6f1de962d911bb5b5c3dba68', }), ], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Query Configuration Options Source: https://wagmi.sh/react/api/hooks/useCapabilities A comprehensive list of configuration properties for managing query lifecycle and behavior. ```APIDOC ## Query Configuration Options ### Parameters - **enabled** (boolean | undefined) - Optional - Set to false to disable the query from automatically running. - **gcTime** (number | Infinity | undefined) - Optional - Time in milliseconds that unused cache data remains in memory. Defaults to 5 minutes. - **initialData** ({{TData}} | (() => {{TData}}) | undefined) - Optional - Initial data for the query cache. - **initialDataUpdatedAt** (number | (() => number | undefined) | undefined) - Optional - Timestamp of when initialData was last updated. - **initialPageParam** ({{TPageParam}}) - Optional - Initial page parameter for infinite queries. - **getPreviousPageParam** (function) - Optional - Function to determine the previous cursor for infinite queries. - **getNextPageParam** (function) - Optional - Function to determine the next cursor for infinite queries. - **meta** (Record | undefined) - Optional - Additional information stored on the query cache entry. - **networkMode** ('online' | 'always' | 'offlineFirst' | undefined) - Optional - Defines how the query handles network connectivity. Defaults to 'online'. - **notifyOnChangeProps** (string[] | 'all' | (() => string[] | 'all') | undefined) - Optional - Controls component re-renders based on property changes. - **placeholderData** ({{TData}} | ((previousValue: {{TData}} | undefined; previousQuery: Query | undefined) => {{TData}}) | undefined) - Optional - Data shown while the query is in the pending state. - **queryClient** (QueryClient | undefined) - Optional - Custom QueryClient instance. - **refetchInterval** (number | false | ((data: {{TData}} | undefined, query: Query) => number | false | undefined) | undefined) - Optional - Frequency in milliseconds for continuous refetching. - **refetchIntervalInBackground** (boolean | undefined) - Optional - If true, refetching continues when the tab is in the background. - **refetchOnMount** (boolean | 'always' | ((query: Query) => boolean | 'always') | undefined) - Optional - Controls refetching behavior when the component mounts. Defaults to true. ``` -------------------------------- ### Type-Safe Query Hook Usage with Merged Config Source: https://wagmi.sh/react/typescript Once declaration merging is set up, query hooks like `useBlockNumber` can infer types based on your global config, eliminating the need to pass the config explicitly. This example shows a type-safe call to `useBlockNumber`. ```typescript import { type Config } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' declare module 'wagmi' { interface Register { config: Config } } // ---cut--- import { useBlockNumber } from 'wagmi' useBlockNumber({ chainId: 123 }) ``` -------------------------------- ### Create Storage with localStorage Source: https://wagmi.sh/react/api/createStorage Create a storage object using the browser's `localStorage`. This is the default behavior if no storage is provided. ```typescript import { createStorage } from '{{packageName}}' const storage = createStorage({ storage: localStorage }) ``` -------------------------------- ### Define Custom Client Creation Source: https://wagmi.sh/react/api/createConfig Provides a function to create a custom Viem client. Ensure parameters.chain is passed to createClient to maintain sync. ```ts-vue import { createClient, http } from 'viem' // [!code focus] import { createConfig } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' const config = createConfig({ chains: [mainnet, sepolia], client({ chain }) { // [!code focus] return createClient({ chain, transport: http('https://...') }) // [!code focus] }, // [!code focus] }) ``` -------------------------------- ### WalletConnect Connector Parameters Source: https://wagmi.sh/react/api/connectors/walletConnect Detailed explanation of the parameters available for configuring the WalletConnect connector. ```APIDOC ## WalletConnect Connector Parameters Check out the [WalletConnect docs](https://github.com/WalletConnect/walletconnect-monorepo/tree/v2.0/providers/ethereum-provider) for more info. A few options are omitted that Wagmi manages internally. ### `customStoragePrefix` `string | undefined` Custom storage prefix for persisting provider state. ```ts import { walletConnect } from '{{connectorsPackageName}}' const connector = walletConnect({ customStoragePrefix: 'wagmi', // [!code focus] projectId: '3fcc6bba6f1de962d911bb5b5c3dba68', }) ``` ### `disableProviderPing` `boolean | undefined` ```ts import { walletConnect } from '{{connectorsPackageName}}' const connector = walletConnect({ disableProviderPing: false, // [!code focus] projectId: '3fcc6bba6f1de962d911bb5b5c3dba68', }) ``` ### `isNewChainsStale` `boolean | undefined` * If a new chain is added to a previously existing configured connector `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 (e.g. the user has not approved or rejected the chain). * Defaults to `true`. ::: details More info 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 (e.g. 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. ::: ```ts import { walletConnect } from '{{connectorsPackageName}}' const connector = walletConnect({ isNewChainsStale: true, // [!code focus] projectId: '3fcc6bba6f1de962d911bb5b5c3dba68', }) ``` ### `metadata` `CoreTypes.Metadata | undefined` Metadata related to the app requesting the connection. ```ts import { walletConnect } from '{{connectorsPackageName}}' const connector = walletConnect({ projectId: '3fcc6bba6f1de962d911bb5b5c3dba68', metadata: { // [!code focus] name: 'Example', // [!code focus] description: 'Example website', // [!code focus] url: 'https://example.com', // [!code focus] }, // [!code focus] }) ``` ``` -------------------------------- ### Query Options Source: https://wagmi.sh/react/api/hooks/useConnectorClient Configuration options for setting up and managing queries. ```APIDOC ## Query Options ### Description Configuration options for setting up and managing queries, including data initialization, pagination, and refetching behaviors. ### Parameters #### initialData `{{TData}} | (() => {{TData}}) | undefined` * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been created or cached yet) * If set to a function, the function will be called **once** during the shared/root query initialization, and be expected to synchronously return the initialData * Initial data is considered stale by default unless a `staleTime` has been set. * `initialData` **is persisted** to the cache #### initialDataUpdatedAt `number | ((() => number | undefined)) | undefined` If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. #### initialPageParam `{{TPageParam}}` The initial page parameter to be passed to the query function. #### getPreviousPageParam This function can be set to automatically get the previous cursor for infinite queries. The result will also be used to determine the value of `hasPreviousPage`. `(firstPage: {{TData}}, allPages: {{TData}}[], firstPageParam: {{TPageParam}}, allPageParams: {{TPageParam}}[]) => {{TPageParam}} | undefined | null` #### getNextPageParam This function can be set to automatically get the previous cursor for infinite queries. The result will also be used to determine the value of `hasPreviousPage`. `(lastPage: {{TData}}, allPages: {{TData}}[], lastPageParam: {{TPageParam}}, allPageParams: {{TPageParam}}[]) => {{TPageParam}} | undefined | null` #### meta `Record | undefined` If set, stores additional information on the query cache entry that can be used as needed. It will be accessible wherever the `query` is available, and is also part of the `QueryFunctionContext` provided to the `queryFn`. #### networkMode `'online' | 'always' | 'offlineFirst' | undefined` * Defaults to `'online'` * see [Network Mode](https://tanstack.com/query/v5/docs/react/guides/network-mode) for more information. #### notifyOnChangeProps `string[] | 'all' | (() => string[] | 'all') | undefined` * If set, the component will only re-render if any of the listed properties change. * If set to `['data', 'error']` for example, the component will only re-render when the `data` or `error` properties change. * If set to `'all'`, the component will opt-out of smart tracking and re-render whenever a query is updated. * If set to a function, the function will be executed to compute the list of properties. * By default, access to properties will be tracked, and the component will only re-render when one of the tracked properties change. #### placeholderData `{{TData}} | ((previousValue: {{TData}} | undefined; previousQuery: Query | undefined) => {{TData}}) | undefined` * If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `pending` state. * `placeholderData` is **not persisted** to the cache * If you provide a function for `placeholderData`, as a first argument you will receive previously watched query data if available, and the second argument will be the complete previousQuery instance. #### queryClient `QueryClient | undefined` Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used. #### refetchInterval `number | false | ((data: {{TData}} | undefined, query: Query) => number | false | undefined) | undefined` * If set to a number, all queries will continuously refetch at this frequency in milliseconds * If set to a function, the function will be executed with the latest data and query to compute a frequency #### refetchIntervalInBackground `boolean | undefined` If set to `true`, queries that are set to continuously refetch with a `refetchInterval` will continue to refetch while their tab/window is in the background #### refetchOnMount `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` * Defaults to `true` * If set to `true`, the query will refetch on mount if the data is stale. * If set to `false`, the query will not refetch on mount. * If set to `'always'`, the query will always refetch on mount. * If set to a function, the function will be executed with the query to compute the value #### refetchOnReconnect `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` * Defaults to `true` * If set to `true`, the query will refetch on reconnect if the data is stale. * If set to `false`, the query will not refetch on reconnect. * If set to `'always'`, the query will always refetch on reconnect. * If set to a function, the function will be executed with the query to compute the value ``` -------------------------------- ### Import useSignTransaction Source: https://wagmi.sh/react/api/hooks/useSignTransaction Import the hook from the wagmi package. ```ts import { useSignTransaction } from 'wagmi' ``` -------------------------------- ### Use useConnectorClient with a Provided Config Source: https://wagmi.sh/react/api/hooks/useConnectorClient Specify a custom wagmi configuration to use when obtaining the Viem Client with useConnectorClient. ```tsx import { useConnectorClient } from 'wagmi' import { config } from './config' function App() { const result = useConnectorClient({ config, }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Using `scopeKey` for Cache Scoping Source: https://wagmi.sh/react/api/hooks/useVerifyTypedData Explains how to use the `scopeKey` option to scope the cache for hooks, allowing hooks with identical contexts to share the same cache. ```APIDOC ## POST /api/verifyTypedData (with scopeKey) ### Description This example demonstrates using the `scopeKey` option to isolate or share the cache for the `useVerifyTypedData` hook. ### Method POST (Implied by hook usage) ### Endpoint N/A (Hook usage) ### Parameters #### Request Body - **scopeKey** (`string | undefined`) - Optional - Scopes the cache to a given context. Hooks with identical context will share the same cache. - **domain** (`object`) - Required - The domain information for the typed data. - **types** (`object`) - Required - The type definitions for the typed data. - **message** (`object`) - Required - The message content for the typed data. - **primaryType** (`string`) - Required - The primary type of the message. - **address** (`string`) - Required - The address associated with the signature. - **signature** (`string`) - Required - The signature of the message. ### Request Example ```json { "scopeKey": "foo", "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" } ] }, "message": { "from": { "name": "Cow", "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826" }, "to": { "name": "Bob", "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB" }, "contents": "Hello, Bob!" }, "primaryType": "Mail", "address": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266", "signature": "0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c" } ``` ### Response #### Success Response (200) - **result** (`object`) - The result of the verification. #### Response Example ```json { "result": true } ``` ``` -------------------------------- ### Configure wagmi with Porto Connector Source: https://wagmi.sh/react/api/connectors/porto Set up wagmi's configuration by adding the Porto connector to the list of available connectors. This allows your application to interact with Porto wallets. ```typescript import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' import { porto } from '{{connectorsPackageName}}' // [!code hl] export const config = createConfig({ chains: [mainnet, sepolia], connectors: [porto()], // [!code hl] transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Query Configuration Options Source: https://wagmi.sh/react/api/hooks/useBlock A collection of configuration properties for customizing query behavior. ```APIDOC ## Query Configuration Options ### Description Configuration properties for managing query lifecycle, retries, and refetching behavior. ### Parameters - **getNextPageParam** (function) - Optional - Function to determine the previous cursor for infinite queries. - **meta** (Record) - Optional - Additional information stored on the query cache entry. - **networkMode** ('online' | 'always' | 'offlineFirst') - Optional - Defines how the query handles network connectivity. Defaults to 'online'. - **notifyOnChangeProps** (string[] | 'all' | function) - Optional - Controls component re-rendering based on property changes. - **placeholderData** (TData | function) - Optional - Data used while the query is in the pending state. - **queryClient** (QueryClient) - Optional - Custom QueryClient instance. - **refetchInterval** (number | false | function) - Optional - Frequency in milliseconds for continuous refetching. - **refetchIntervalInBackground** (boolean) - Optional - Whether to refetch in the background. - **refetchOnMount** (boolean | 'always' | function) - Optional - Refetch behavior when the component mounts. Defaults to true. - **refetchOnReconnect** (boolean | 'always' | function) - Optional - Refetch behavior on network reconnect. Defaults to true. - **refetchOnWindowFocus** (boolean | 'always' | function) - Optional - Refetch behavior on window focus. Defaults to true. - **retry** (boolean | number | function) - Optional - Retry logic for failed queries. Defaults to 3. - **retryDelay** (number | function) - Optional - Delay before the next retry attempt in milliseconds. - **retryOnMount** (boolean) - Optional - Whether to retry on mount if the query has an error. Defaults to true. ``` -------------------------------- ### Import usePublicClient Source: https://wagmi.sh/react/api/hooks/usePublicClient Import the hook from the wagmi package. ```ts import { usePublicClient } from 'wagmi' ``` -------------------------------- ### Type for createConfig Parameters Source: https://wagmi.sh/react/api/createConfig Import the `CreateConfigParameters` type for defining the configuration object. ```ts-vue import { type CreateConfigParameters } from '{{packageName}}' ``` -------------------------------- ### useFeeHistory with Custom Config Source: https://wagmi.sh/react/api/hooks/useFeeHistory Demonstrates how to use the `config` option with the `useFeeHistory` hook to provide a custom Wagmi configuration. ```APIDOC ## useFeeHistory with Custom Config ### Description This example shows how to pass a custom `config` object to the `useFeeHistory` hook, allowing for a specific configuration to be used instead of the one provided by the nearest `WagmiProvider`. ### Method `useFeeHistory` ### Endpoint N/A (Hook) ### Parameters #### Request Body - **config** (`Config | undefined`) - Required/Optional - The Wagmi configuration to use. - **blockCount** (`number`) - Required - The number of blocks to fetch fee history for. - **rewardPercentiles** (`number[]`) - Required - An array of percentile values (0-100) to calculate reward percentages. ### Request Example ```tsx import { useFeeHistory } from 'wagmi' import { config } from './config' function App() { const result = useFeeHistory({ blockCount: 4, rewardPercentiles: [25, 75], config: config }) } ``` ### Response #### Success Response (200) - **data** (`FeeHistory | undefined`) - The fee history data. - **error** (`TError | undefined`) - An error object if the query failed. - **isLoading** (`boolean`) - Indicates if the query is currently loading. #### Response Example ```json { "data": { "baseFeePerGas": "1000000000", "gasUsedRatio": [ 1, 1 ], "latestBaseFeePerGas": "1000000000", "latestGasUsed": 10000000, "latestMaxPriorityFeePerGas": "1000000000", "latestMaxFeePerGas": "1000000000", "reward": [ [ "1000000000", "1000000000" ], [ "1000000000", "1000000000" ], [ "1000000000", "1000000000" ], [ "1000000000", "1000000000" ] ], "rewardBase": [ "1000000000", "1000000000", "1000000000", "1000000000" ] }, "error": null, "isLoading": false } ``` ``` -------------------------------- ### Define and Register Config Source: https://wagmi.sh/react/api/hooks/useConfig Create a configuration object and register it for use with the Wagmi hooks. ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' declare module 'wagmi' { interface Register { config: typeof config } } export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Import createConfig Source: https://wagmi.sh/react/api/createConfig Import the createConfig function from the wagmi package. ```ts-vue import { createConfig } from '{{packageName}}' ``` -------------------------------- ### Pagination Configuration Source: https://wagmi.sh/react/api/hooks/useEnsAvatar Options for configuring pagination behavior in queries. ```APIDOC ## initialPageParam `{{TPageParam}}` The initial page parameter to be passed to the query function. ## getPreviousPageParam This function can be set to automatically get the previous cursor for infinite queries. The result will also be used to determine the value of `hasPreviousPage`. `(firstPage: {{TData}}, allPages: {{TData}}[], firstPageParam: {{TPageParam}}, allPageParams: {{TPageParam}}[]) => {{TPageParam}} | undefined | null` ## getNextPageParam This function can be set to automatically get the previous cursor for infinite queries. The result will also be used to determine the value of `hasPreviousPage`. `(lastPage: {{TData}}, allPages: {{TData}}[], lastPageParam: {{TPageParam}}, allPageParams: {{TPageParam}}[]) => {{TPageParam}} | undefined | null` ``` -------------------------------- ### Mutation Configuration and Properties Source: https://wagmi.sh/react/api/hooks/useWatchAsset Details on configuring mutation behavior and the properties available on the mutation object. ```APIDOC ## Mutation Configuration ### queryClient - **queryClient** (QueryClient) - Optional - Use a custom QueryClient instance. ### retry - **retry** (boolean | number | function) - Optional - Defaults to 0. Configures retry behavior for failed mutations. ### retryDelay - **retryDelay** (number | function) - Optional - Defines the delay in milliseconds before the next retry attempt. ## Mutation Properties ### mutate - **mutate** (function) - The function to trigger the mutation with variables and optional callbacks (onSuccess, onError, onSettled). ### mutateAsync - **mutateAsync** (function) - Similar to mutate but returns a Promise that can be awaited. ### status - **status** ('idle' | 'pending' | 'error' | 'success') - The current state of the mutation. ### data - **data** (TData | undefined) - The last successfully resolved data. ### error - **error** (TError | null) - The error object if the mutation failed. ### failureCount - **failureCount** (number) - The number of times the mutation has failed. ### reset - **reset** (function) - Resets the mutation internal state to its initial state. ``` -------------------------------- ### Import useTransactionConfirmations Source: https://wagmi.sh/react/api/hooks/useTransactionConfirmations Import the hook from the wagmi package. ```ts import { useTransactionConfirmations } from 'wagmi' ``` -------------------------------- ### Query Client and Context Source: https://wagmi.sh/react/api/hooks/useEstimateFeesPerGas Options for providing a custom QueryClient or managing context. ```APIDOC ## queryClient ### Description Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used. ### Type `QueryClient | undefined` ``` -------------------------------- ### Configure Connector Source: https://wagmi.sh/react/api/hooks/useWalletClient Specify a connector instance to retrieve the client for. ```ts import { useConnections, useWalletClient } from 'wagmi' function App() { const connections = useConnections(config) const result = useWalletClient({ connector: connections[0]?.connector, // [!code focus] }) } ``` -------------------------------- ### Import useBlockNumber Source: https://wagmi.sh/react/api/hooks/useBlockNumber Import the hook from the wagmi package. ```ts import { useBlockNumber } from 'wagmi' ``` -------------------------------- ### Configure Safe Connector with Shim Disconnect Source: https://wagmi.sh/react/api/connectors/safe Initialize the Safe connector with shimDisconnect enabled to simulate disconnect behavior using storage. ```typescript import { safe } from '{{connectorsPackageName}}' const connector = safe({ shimDisconnect: true, }) ``` -------------------------------- ### Import useEstimateGas Source: https://wagmi.sh/react/api/hooks/useEstimateGas Import the hook from the wagmi package. ```ts import { useEstimateGas } from 'wagmi' ``` -------------------------------- ### Safe Connector Configuration Source: https://wagmi.sh/react/api/connectors/safe Configuration options for initializing the Safe connector. ```APIDOC ## Safe Connector Configuration ### Description The Safe connector allows integration with the Safe Apps SDK. It is initialized using the `safe()` function. ### Parameters - **allowedDomains** (RegExp[] | undefined) - Optional - A list of regular expressions to allow specific domains for the Safe App. - **debug** (boolean | undefined) - Optional - Enables debug logging for the connector. - **shimDisconnect** (boolean | undefined) - Optional - Simulates disconnect behavior by tracking connection status in storage. Defaults to false. ### Usage Example ```ts import { safe } from '{{connectorsPackageName}}' const connector = safe({ allowedDomains: [/app.safe.global$/], debug: true, shimDisconnect: true }) ``` ``` -------------------------------- ### Action: switchConnection Source: https://wagmi.sh/react/api/hooks/useSwitchConnection Reference to the `switchConnection` action. ```APIDOC ## Action * [`switchConnection`](/core/api/actions/switchConnection) ``` -------------------------------- ### Import useEnsAvatar Source: https://wagmi.sh/react/api/hooks/useEnsAvatar Import the hook from the wagmi package. ```ts import { useEnsAvatar } from 'wagmi' ``` -------------------------------- ### Use Infinite Read Contracts Hook Source: https://wagmi.sh/react/api/hooks/useInfiniteReadContracts Demonstrates the basic usage of `useInfiniteReadContracts` to fetch contract data with pagination. Ensure the `abi` is correctly imported and typed for maximum safety. ```tsx import { useInfiniteReadContracts } from 'wagmi' import { abi } from './abi' function App() { const result = useInfiniteReadContracts({ cacheKey: 'mlootAttributes', contracts(pageParam) { const args = [pageParam] as const return [ // ... { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi, // [!code hl] functionName: 'getChest', args }, // ... ] } query: { initialPageParam: 0, getNextPageParam: (_lastPage, _allPages, lastPageParam) => { return lastPageParam + 1 } } }) } ``` -------------------------------- ### Usage of useConnections with Config Source: https://wagmi.sh/react/api/hooks/useConnections Shows how to use the useConnections hook with a specific configuration object. Ensure the config is imported and passed to the hook. ```tsx import { useConnections } from 'wagmi' import { config } from './config' // [!code focus] function App() { const connections = useConnections({ config, // [!code focus] }) } ``` ```typescript import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### createConfig Source: https://wagmi.sh/react/api/createConfig Initializes a new Config object with specified chains, transports, and optional configurations. ```APIDOC ## createConfig ### Description Creates a new Config object required for Wagmi applications. It manages chains, transports, connectors, and state persistence. ### Parameters #### Request Body - **chains** (readonly [Chain, ...Chain[]]) - Required - Chains used by the Config. - **transports** (Record) - Optional - Transports used for each chain. - **client** (Function) - Optional - A function that returns a Viem Client for fine-grained control. - **connectors** (CreateConnectorFn[]) - Optional - Connectors used by the Config. - **multiInjectedProviderDiscovery** (boolean) - Optional - Enables EIP-6963 discovery. Defaults to true. - **ssr** (boolean) - Optional - Flag for server-side rendering environments. Defaults to false. - **storage** (Storage) - Optional - Storage used to persist Config state. - **syncConnectedChain** (boolean) - Optional - Syncs chainId with current connection. Defaults to true. ### Request Example { "chains": [mainnet, sepolia], "transports": { "1": http('https://mainnet.example.com'), "11155111": http('https://sepolia.example.com') } } ``` -------------------------------- ### Configure Account Source: https://wagmi.sh/react/api/hooks/useWalletClient Specify an account to use with the client. ```ts import { useWalletClient } from 'wagmi' function App() { const result = useWalletClient({ account: '0xd2135CfB216b74109775236E36d4b433F1DF507B', // [!code focus] }) } ``` -------------------------------- ### Configure Args Parameter Source: https://wagmi.sh/react/api/hooks/useWatchContractEvent Filter events by specific arguments inferred from the ABI and event name. ```tsx import { useWatchContractEvent } from 'wagmi' import { abi } from './abi' function App() { useWatchContractEvent({ address: '0x6b175474e89094c44da98b954eedeac495271d0f', abi, args: { // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B' // [!code focus] } // [!code focus] eventName: 'Transfer', onLogs(logs) { console.log('New logs!', logs) }, }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Configure gasPrice parameter Source: https://wagmi.sh/react/api/hooks/usePrepareTransactionRequest Sets the price in wei per gas for Legacy Transactions. ```tsx import { usePrepareTransactionRequest } from 'wagmi' import { parseEther, parseGwei } from 'viem' function App() { const result = usePrepareTransactionRequest({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', gasPrice: parseGwei('20'), // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Import useSimulateContract Source: https://wagmi.sh/react/api/hooks/useSimulateContract Import the hook from the wagmi package. ```ts import { useSimulateContract } from 'wagmi' ``` -------------------------------- ### Basic Usage of useFeeHistory Hook Source: https://wagmi.sh/react/api/hooks/useFeeHistory Demonstrates the basic usage of the useFeeHistory hook with blockCount and rewardPercentiles. ```tsx import { useFeeHistory } from 'wagmi' function App() { const result = useFeeHistory({ blockCount: 4, rewardPercentiles: [25, 75] }) } ``` ```typescript import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Watch with custom config Source: https://wagmi.sh/react/api/hooks/useWatchBlocks Provide a specific Wagmi configuration instance. ```ts import { useWatchBlocks } from 'wagmi' import { config } from './config' function App() { useWatchBlocks({ config, // [!code focus] onBlock(block) { console.log('New block', block.number) }, }) } ``` ```ts import { createConfig, http } from '@wagmi/core' import { mainnet, sepolia } from '@wagmi/core/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Import MetaMask Connector Source: https://wagmi.sh/react/api/connectors/metaMask Import the metaMask connector from the connectors package. ```ts import { metaMask } from '{{connectorsPackageName}}' ``` -------------------------------- ### Configure WalletConnect storageOptions Source: https://wagmi.sh/react/api/connectors/walletConnect Provides configuration for key-value storage used by the connector. ```ts-vue import { walletConnect } from '{{connectorsPackageName}}' const connector = walletConnect({ projectId: '3fcc6bba6f1de962d911bb5b5c3dba68', storageOptions: {}, // [!code focus] }) ``` -------------------------------- ### Configure mock connector Source: https://wagmi.sh/react/api/connectors/mock Integrate the mock connector into the Wagmi configuration. ```ts-vue import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' import { mock } from '{{connectorsPackageName}}' export const config = createConfig({ chains: [mainnet, sepolia], connectors: [ mock({ accounts: [ '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', '0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC', ], }), ], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Query Configuration Options Source: https://wagmi.sh/react/api/hooks/useWalletClient A collection of configuration properties for managing query state, caching, and refetching behavior. ```APIDOC ## Query Configuration Options ### Description Configuration properties used to define the behavior of queries, including initial data, refetching intervals, and network modes. ### Parameters - **initialData** (TData | () => TData) - Optional - Initial data for the query cache. - **initialDataUpdatedAt** (number | () => number) - Optional - Timestamp of when initialData was last updated. - **initialPageParam** (TPageParam) - Optional - Initial page parameter for infinite queries. - **getPreviousPageParam** (Function) - Optional - Function to determine the previous cursor for infinite queries. - **getNextPageParam** (Function) - Optional - Function to determine the next cursor for infinite queries. - **meta** (Record) - Optional - Additional information stored on the query cache entry. - **networkMode** ('online' | 'always' | 'offlineFirst') - Optional - Defines how the query handles network status. - **notifyOnChangeProps** (string[] | 'all' | Function) - Optional - Controls component re-rendering based on property changes. - **placeholderData** (TData | Function) - Optional - Data used while the query is in the pending state. - **queryClient** (QueryClient) - Optional - Custom QueryClient instance. - **refetchInterval** (number | false | Function) - Optional - Frequency in milliseconds for continuous refetching. - **refetchIntervalInBackground** (boolean) - Optional - Whether to refetch in the background. - **refetchOnMount** (boolean | 'always' | Function) - Optional - Behavior for refetching when the component mounts. - **refetchOnReconnect** (boolean | 'always' | Function) - Optional - Behavior for refetching when the network reconnects. ``` -------------------------------- ### Import createStorage Source: https://wagmi.sh/react/api/createStorage Import the `createStorage` function from the wagmi package. ```typescript import { createStorage } from '{{packageName}}' ``` -------------------------------- ### Deploy a Contract Source: https://wagmi.sh/react/api/hooks/useDeployContract Basic usage of the hook to deploy a contract without constructor arguments. ```tsx import { useDeployContract } from 'wagmi' import { parseEther } from 'viem' import { wagmiAbi } from './abi' function App() { const deployContract = useDeployContract() return ( ) } ``` ```ts export const wagmiAbi = [ ... { inputs: [], stateMutability: "nonpayable", type: "constructor", }, ... ] as const ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Import Porto Connector Source: https://wagmi.sh/react/api/connectors/porto Import the Porto connector from the wagmi connectors package. This is the first step to integrating Porto wallet functionality. ```typescript import { porto } from '{{connectorsPackageName}}' ``` -------------------------------- ### Configure shimDisconnect Source: https://wagmi.sh/react/api/connectors/injected Simulate disconnect behavior by tracking connection status in storage. ```ts-vue import { injected } from '{{connectorsPackageName}}' const connector = injected({ shimDisconnect: false, // [!code focus] }) ``` -------------------------------- ### Query Configuration Options Source: https://wagmi.sh/react/api/hooks/useBytecode A comprehensive list of configuration options for customizing query behavior in Wagmi React hooks. ```APIDOC ## Query Configuration Options ### Description These options allow fine-grained control over how queries behave, including data fetching, caching, and error handling. ### Parameters - **placeholderData** (TData | function) - Optional - Data used while the query is in the pending state. - **queryClient** (QueryClient) - Optional - Custom QueryClient instance. - **refetchInterval** (number | false | function) - Optional - Frequency in milliseconds to continuously refetch. - **refetchIntervalInBackground** (boolean) - Optional - Whether to refetch while the tab is in the background. - **refetchOnMount** (boolean | 'always' | function) - Optional - Whether to refetch on mount if data is stale. Defaults to true. - **refetchOnReconnect** (boolean | 'always' | function) - Optional - Whether to refetch on reconnect if data is stale. Defaults to true. - **refetchOnWindowFocus** (boolean | 'always' | function) - Optional - Whether to refetch on window focus if data is stale. Defaults to true. - **retry** (boolean | number | function) - Optional - Retry logic for failed queries. Defaults to 3. - **retryDelay** (number | function) - Optional - Delay in milliseconds before retrying. - **retryOnMount** (boolean) - Optional - Whether to retry on mount if the query has an error. Defaults to true. - **select** (function) - Optional - Transform or select a part of the query data. - **staleTime** (number | Infinity) - Optional - Time in milliseconds until data is considered stale. Defaults to 0. - **structuralSharing** (boolean | function) - Optional - Whether to enable structural sharing. Defaults to true. ``` -------------------------------- ### Deploy with Constructor Arguments Source: https://wagmi.sh/react/api/hooks/useDeployContract Deploy a contract that requires constructor arguments by passing them in the mutate function. ```tsx import { useDeployContract } from 'wagmi' import { parseEther } from 'viem' import { wagmiAbi } from './abi' function App() { const deployContract = useDeployContract() return ( ) } ``` ```ts export const wagmiAbi = [ ... { inputs: [{ name: "x", type: "uint32" }], stateMutability: "nonpayable", type: "constructor", }, ... ] as const; ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### useFeeHistory with Scope Key Source: https://wagmi.sh/react/api/hooks/useFeeHistory Illustrates how to use the `scopeKey` option with the `useFeeHistory` hook to isolate cache instances. ```APIDOC ## useFeeHistory with Scope Key ### Description This example demonstrates using the `scopeKey` option with the `useFeeHistory` hook. This allows you to scope the cache to a specific context, enabling hooks with identical contexts to share the same cache. ### Method `useFeeHistory` ### Endpoint N/A (Hook) ### Parameters #### Request Body - **scopeKey** (`string | undefined`) - Required/Optional - A string to scope the cache. Hooks with the same `scopeKey` will share a cache. - **blockCount** (`number`) - Required - The number of blocks to fetch fee history for. - **rewardPercentiles** (`number[]`) - Required - An array of percentile values (0-100) to calculate reward percentages. ### Request Example ```tsx import { useFeeHistory } from 'wagmi' function App() { const result = useFeeHistory({ blockCount: 4, rewardPercentiles: [25, 75], scopeKey: 'foo' }) } ``` ### Response #### Success Response (200) - **data** (`FeeHistory | undefined`) - The fee history data. - **error** (`TError | undefined`) - An error object if the query failed. - **isLoading** (`boolean`) - Indicates if the query is currently loading. #### Response Example ```json { "data": { "baseFeePerGas": "1000000000", "gasUsedRatio": [ 1, 1 ], "latestBaseFeePerGas": "1000000000", "latestGasUsed": 10000000, "latestMaxPriorityFeePerGas": "1000000000", "latestMaxFeePerGas": "1000000000", "reward": [ [ "1000000000", "1000000000" ], [ "1000000000", "1000000000" ], [ "1000000000", "1000000000" ], [ "1000000000", "1000000000" ] ], "rewardBase": [ "1000000000", "1000000000", "1000000000", "1000000000" ] }, "error": null, "isLoading": false } ``` ``` -------------------------------- ### Import useInfiniteReadContracts Hook Source: https://wagmi.sh/react/api/hooks/useInfiniteReadContracts Import the `useInfiniteReadContracts` hook from the wagmi library. ```typescript import { useInfiniteReadContracts } from 'wagmi' ``` -------------------------------- ### Configure Devtools with BigInt Serialization Source: https://wagmi.sh/react/guides/tanstack-query Use the hashFn from @wagmi/core/query to ensure BigInt values are correctly serialized in the Devtools. ```tsx import { QueryClient, QueryClientProvider, } from "@tanstack/react-query"; import { ReactQueryDevtools } from "@tanstack/react-query-devtools"; // [!code hl] import { hashFn } from "@wagmi/core/query"; // [!code hl] const queryClient = new QueryClient({ defaultOptions: { // [!code hl] queries: { // [!code hl] queryKeyHashFn: hashFn, // [!code hl] }, // [!code hl] }, // [!code hl] }); ``` -------------------------------- ### Import Wagmi Connectors Source: https://wagmi.sh/react/api/connectors Use this import statement to access available wallet connectors within your project. ```ts import { injected } from 'wagmi/connectors' ``` -------------------------------- ### Mutation Configuration and Methods Source: https://wagmi.sh/react/api/hooks/useSendCalls Details on the configuration options for mutation hooks and the methods available to trigger mutations. ```APIDOC ## Mutation Configuration ### Parameters - **networkMode** (string) - Optional - Defines network behavior: 'online', 'always', 'offlineFirst'. Defaults to 'online'. - **onError** (function) - Optional - Callback fired on mutation error. - **onMutate** (function) - Optional - Callback fired before mutation; useful for optimistic updates. - **onSuccess** (function) - Optional - Callback fired on successful mutation. - **onSettled** (function) - Optional - Callback fired when mutation completes (success or error). - **queryClient** (QueryClient) - Optional - Custom QueryClient instance. - **retry** (boolean | number | function) - Optional - Retry logic for failed mutations. Defaults to 0. - **retryDelay** (number | function) - Optional - Delay between retry attempts in milliseconds. ## Mutation Methods ### mutate `(variables: TVariables, { onSuccess, onSettled, onError }) => void` Triggers the mutation with provided variables and optional callbacks. ### mutateAsync `(variables: TVariables, { onSuccess, onSettled, onError }) => Promise` Similar to `mutate` but returns a promise that can be awaited. ### reset `() => void` Resets the mutation internal state to its initial state. ``` -------------------------------- ### Handle onConnect event Source: https://wagmi.sh/react/api/hooks/useConnectionEffect Define a callback to execute when a connection is established. ```tsx import { useConnectionEffect } from 'wagmi' function App() { useConnectionEffect({ onConnect(data) { // [!code focus] console.log('Connected!', data) // [!code focus] }, // [!code focus] }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### WalletConnect Connector Configuration Source: https://wagmi.sh/react/api/connectors/walletConnect Configure the WalletConnect connector with essential options like projectId, qrModalOptions, relayUrl, storageOptions, and showQrModal. ```APIDOC ## WalletConnect Connector Configuration ### Description Configure the WalletConnect connector with essential options like `projectId`, `qrModalOptions`, `relayUrl`, `storageOptions`, and `showQrModal`. ### Method N/A (Configuration object) ### Endpoint N/A (Configuration object) ### Parameters #### Request Body - **projectId** (string) - Required - WalletConnect Cloud project identifier. - **qrModalOptions** (QrModalOptions | undefined) - Optional - Options for rendering QR modal. - **relayUrl** (string | undefined) - Optional - WalletConnect relay URL to use. Defaults to `'wss://relay.walletconnect.com'`. - **storageOptions** (KeyValueStorageOptions | undefined) - Optional - Storage options for the connector. - **showQrModal** (boolean | undefined) - Optional - Whether to show the QR code modal upon calling `connector.connect()`. Defaults to `true`. ### Request Example ```json { "projectId": "3fcc6bba6f1de962d911bb5b5c3dba68", "qrModalOptions": { "themeMode": "dark" }, "relayUrl": "wss://relay.walletconnect.org", "storageOptions": {}, "showQrModal": true } ``` ### Response N/A (Configuration object) ### Notes If `showQrModal` is disabled, you can listen for a `'message'` event with payload `{ type: 'display_uri'; data: string }` to render your own QR code. ``` -------------------------------- ### Basic Usage of useShowCallsStatus Source: https://wagmi.sh/react/api/hooks/useShowCallsStatus Demonstrates how to use the useShowCallsStatus hook to trigger the display of call status in the wallet. Requires an ID for the call batch. ```tsx import { useShowCallsStatus } from 'wagmi' import { parseEther } from 'viem' function App() { const showCallsStatus = useShowCallsStatus() return ( ) } ``` -------------------------------- ### Import useDeployContract Source: https://wagmi.sh/react/api/hooks/useDeployContract Import the hook from the wagmi package. ```ts import { useDeployContract } from 'wagmi' ``` -------------------------------- ### Create Storage with IndexedDB Source: https://wagmi.sh/react/api/createStorage Create a storage object using IndexedDB via the `idb-keyval` library for asynchronous storage. ```typescript import { createStorage } from '{{packageName}}' // Using IndexedDB via https://github.com/jakearchibald/idb-keyval import { del, get, set } from 'idb-keyval' const storage = createStorage({ storage: { async getItem(name) { return get(name) }, async setItem(name, value) { await set(name, value) }, async removeItem(name) { await del(name) }, }, }) ``` -------------------------------- ### Import useGasPrice Hook Source: https://wagmi.sh/react/api/hooks/useGasPrice Import the useGasPrice hook from the wagmi library. ```typescript import { useGasPrice } from 'wagmi' ``` -------------------------------- ### Import useConnectorClient Source: https://wagmi.sh/react/api/hooks/useConnectorClient Import the useConnectorClient hook from the wagmi library. ```typescript import { useConnectorClient } from 'wagmi' ``` -------------------------------- ### Use Connector with useCapabilities Source: https://wagmi.sh/react/api/hooks/useCapabilities Fetches capabilities using a specific connector obtained from useConnections. Ensure wagmi config is set up. ```tsx import { useCapabilities, useConnections } from 'wagmi' import { config } from './config' // [!code focus] function App() { const connections = useConnections() const result = useCapabilities({ connector: connections[0]?.connector, // [!code focus] }) } ``` ```typescript import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Verify Typed Data with Signature Source: https://wagmi.sh/react/api/hooks/useVerifyTypedData Demonstrates using the signature parameter to verify typed data. ```tsx import { domain, types } from './data' import { useVerifyTypedData } from 'wagmi' function App() { const result = useVerifyTypedData({ domain, types, message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, primaryType: 'Mail', address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', // [!code focus] }) } ``` ```ts // All properties on a domain are optional export const domain = { name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', } as const // The named list of all type definitions export const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], } as const ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### useProof Hook Parameters Source: https://wagmi.sh/react/api/hooks/useProof This section details the parameters available for the `useProof` hook in Wagmi. ```APIDOC ## chainId `config['chains'][number]['id'] | undefined` The ID of chain to get the proof for. ### Request Example ```tsx import { useProof } from 'wagmi' import { optimism } from 'wagmi/chains' function App() { const result = useProof({ chainId: optimism.id, // [!code focus] address: '0x4200000000000000000000000000000000000016', storageKeys: [ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }) } ``` ## config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ### Request Example ```tsx import { useProof } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useProof({ config, // [!code focus] address: '0x4200000000000000000000000000000000000016', storageKeys: [ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }) } ``` ## scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ### Request Example ```tsx import { useProof } from 'wagmi' import { config } from './config' function App() { const result = useProof({ scopeKey: 'foo' // [!code focus] address: '0x4200000000000000000000000000000000000016', storageKeys: [ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }) } ``` ``` -------------------------------- ### Create Storage with custom key prefix Source: https://wagmi.sh/react/api/createStorage Create a storage object with a custom `key` prefix to avoid naming collisions with other applications. ```typescript import { createStorage } from '{{packageName}}' const storage = createStorage({ key: 'my-app', storage: localStorage, }) ``` -------------------------------- ### Import UseBlockParameters Source: https://wagmi.sh/react/api/hooks/useBlock Import the type definition for hook parameters. ```ts import { type UseBlockParameters } from 'wagmi' ``` -------------------------------- ### cookieToInitialState Utility Source: https://wagmi.sh/react/api/utilities/cookieToInitialState Converts a cookie string into the initial state required for WagmiProvider during server-side rendering. ```APIDOC ## cookieToInitialState ### Description Helper function to convert a cookie string into initial state for WagmiProvider. ### Parameters - **config** (Config) - Required - The Wagmi configuration object. - **cookie** (string | null | undefined) - Required - The cookie string to parse. ### Return Type - **State** - The initial state object derived from the cookie. ### Usage Example ```ts import { cookieToInitialState } from '{{packageName}}' import config from './config' function handler(req: Request) { const initialState = cookieToInitialState(config, req.headers.cookie) } ``` ``` -------------------------------- ### Import CreateStorageParameters type Source: https://wagmi.sh/react/api/createStorage Import the `CreateStorageParameters` type for type safety when configuring storage. ```typescript import { type CreateStorageParameters } from '{{packageName}}' ``` -------------------------------- ### Use Simulate Contract with Wagmi Source: https://wagmi.sh/react/guides/migrate-from-v1-to-v2 Replaces `usePrepareContractWrite` with `useSimulateContract` and composes it with `useWriteContract` for contract interactions. ```tsx import { usePrepareContractWrite, useWriteContract } from 'wagmi' // [!code --] import { useSimulateContract, useWriteContract } from 'wagmi' // [!code ++] const { config } = usePrepareContractWrite({ address: '0x', abi: [{ type: 'function', name: 'transferFrom', stateMutability: 'nonpayable', inputs: [ { name: 'sender', type: 'address' }, { name: 'recipient', type: 'address' }, { name: 'amount', type: 'uint256' }, ], outputs: [{ type: 'bool' }], }], functionName: 'transferFrom', args: ['0x', '0x', 123n], }) // [!code --] const { data } = useSimulateContract({ address: '0x', abi: [{ type: 'function', name: 'transferFrom', stateMutability: 'nonpayable', inputs: [ { name: 'sender', type: 'address' }, { name: 'recipient', type: 'address' }, { name: 'amount', type: 'uint256' }, ], outputs: [{ type: 'bool' }], }], functionName: 'transferFrom', args: ['0x', '0x', 123n], }) // [!code ++] const { write } = useWriteContract(config) // [!code --] const { writeContract } = useWriteContract() // [!code ++] ``` -------------------------------- ### Configure WalletConnect with Custom Storage Prefix Source: https://wagmi.sh/react/api/connectors/walletConnect Use the `customStoragePrefix` option to specify a unique prefix for persisting WalletConnect provider state. ```typescript import { walletConnect } from '{{connectorsPackageName}}' const connector = walletConnect({ customStoragePrefix: 'wagmi', // [!code focus] projectId: '3fcc6bba6f1de962d911bb5b5c3dba68', }) ``` -------------------------------- ### useInfiniteReadContracts Hook Source: https://wagmi.sh/react/api/hooks/useInfiniteReadContracts This hook is used to fetch data from multiple smart contracts with support for infinite scrolling or pagination. It takes a `contracts` function that returns an array of contract configurations and a `query` object for pagination. ```APIDOC ## useInfiniteReadContracts Hook ### Description Fetches data from multiple smart contracts with support for infinite scrolling or pagination. It takes a `contracts` function that returns an array of contract configurations and a `query` object for pagination. ### Method `useInfiniteReadContracts` ### Parameters #### Request Body - **cacheKey** (string) - Required - A unique key for caching the contract data. - **contracts** ((pageParam: TPageParam) => Contract[]) - Required - A function that receives a page parameter and returns an array of contract configurations. - **address** (Address | undefined) - The contract's address. - **abi** (Abi | undefined) - The contract's ABI. - **functionName** (string | undefined) - The name of the function to call on the contract. Inferred from `abi`. - **args** (readonly unknown[] | undefined) - Arguments to pass when calling the contract. Inferred from `abi` and `functionName`. - **query** (object) - Required - Configuration for the query, including pagination. - **initialPageParam** (any) - The initial parameter for the first page. - **getNextPageParam** ((lastPage: any, allPages: any[], lastPageParam: any) => any | undefined) - A function to determine the next page parameter. ``` -------------------------------- ### Import UseWatchPendingTransactionsParameters Source: https://wagmi.sh/react/api/hooks/useWatchPendingTransactions Import the parameter type definition for the hook. ```ts import { type UseWatchPendingTransactionsParameters } from 'wagmi' ``` -------------------------------- ### Import WalletConnect Connector Source: https://wagmi.sh/react/api/connectors/walletConnect Import the walletConnect connector from the wagmi connectors package. ```typescript import { walletConnect } from '{{connectorsPackageName}}' ``` -------------------------------- ### Create Mint NFT Component Source: https://wagmi.sh/react/guides/write-to-contract Sets up a basic React component with a form for minting an NFT, including an input for the token ID and a submit button. ```tsx import * as React from 'react' export function MintNFT() { return (
) } ``` -------------------------------- ### Import useSwitchChain Hook Source: https://wagmi.sh/react/api/hooks/useSwitchChain Import the useSwitchChain hook from the wagmi library. ```typescript import { useSwitchChain } from 'wagmi' ``` -------------------------------- ### Import UseProofReturnType Source: https://wagmi.sh/react/api/hooks/useProof Import the return type definition for the useProof hook. ```ts import { type UseProofReturnType } from 'wagmi' ``` -------------------------------- ### Import useFeeHistory Hook Source: https://wagmi.sh/react/api/hooks/useFeeHistory Import the useFeeHistory hook from the wagmi library. ```typescript import { useFeeHistory } from 'wagmi' ``` -------------------------------- ### Available Chains Source: https://wagmi.sh/react/api/chains Lists the available Chain definitions. For the latest definitions, refer to the Viem repository. ```APIDOC ## Available Chains ### Description Chain definitions are provided as of a specific `viem` version. For the most up-to-date list, consult the [Viem repository](https://github.com/wevm/viem/blob/main/src/chains/index.ts). ### Note Chain definitions are versioned with `viem`. Ensure your `viem` version is compatible or check the Viem documentation for the latest available chains. ``` -------------------------------- ### Import useTransaction Source: https://wagmi.sh/react/api/hooks/useTransaction Import the hook from the wagmi package. ```ts import { useTransaction } from 'wagmi' ``` -------------------------------- ### Import UseBlockNumberParameters Source: https://wagmi.sh/react/api/hooks/useBlockNumber Import the parameter type definition for the hook. ```ts import { type UseBlockNumberParameters } from 'wagmi' ``` -------------------------------- ### Import mock connector Source: https://wagmi.sh/react/api/connectors/mock Import the mock connector from the connectors package. ```ts-vue import { mock } from '{{connectorsPackageName}}' ``` -------------------------------- ### Display Available Connectors with useConnect Source: https://wagmi.sh/react/api/hooks/useConnect Use `useConnect` to access available connectors and render buttons for users to initiate connections. This snippet demonstrates mapping over `connect.connectors` to display connector names and trigger the connection mutation. ```tsx import { useConnect } from 'wagmi' function App() { const connect = useConnect() return (
{connect.connectors.map((connector) => ( ))}
) } ``` -------------------------------- ### Mutation Configuration and Methods Source: https://wagmi.sh/react/api/hooks/useSignMessage Details on configuring retry behavior and utilizing mutation methods to sign messages. ```APIDOC ## Mutation Configuration ### retry - **retry** (boolean | number | function) - Optional - Defines retry behavior for failed mutations. Defaults to 0. ### retryDelay - **retryDelay** (number | function) - Optional - Function to determine the delay in milliseconds before the next retry attempt. ## Mutation Methods ### mutate - **mutate** (function) - Triggers the mutation with variables and optional callbacks (onSuccess, onError, onSettled). ### mutateAsync - **mutateAsync** (function) - Similar to mutate but returns a Promise that can be awaited. ### reset - **reset** (function) - Resets the mutation internal state to its initial state. ``` -------------------------------- ### Import WalletConnect Parameters Type Source: https://wagmi.sh/react/api/connectors/walletConnect Import the WalletConnectParameters type for type safety when configuring the connector. ```typescript import { type WalletConnectParameters } from '{{connectorsPackageName}}' ``` -------------------------------- ### Query Options Source: https://wagmi.sh/react/api/hooks/useEnsAddress Configuration options for queries. ```APIDOC ## Query Options This section details various options that can be configured for queries. ### initialDataUpdatedAt `number | (() => number | undefined) | undefined` If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. ### initialPageParam `{{TPageParam}}` The initial page parameter to be passed to the query function. ### getPreviousPageParam This function can be set to automatically get the previous cursor for infinite queries. The result will also be used to determine the value of `hasPreviousPage`. `(firstPage: {{TData}}, allPages: {{TData}}[], firstPageParam: {{TPageParam}}, allPageParams: {{TPageParam}}[]) => {{TPageParam}} | undefined | null` ### getNextPageParam This function can be set to automatically get the previous cursor for infinite queries. The result will also be used to determine the value of `hasPreviousPage`. `(lastPage: {{TData}}, allPages: {{TData}}[], lastPageParam: {{TPageParam}}, allPageParams: {{TPageParam}}[]) => {{TPageParam}} | undefined | null` ### meta `Record | undefined` If set, stores additional information on the query cache entry that can be used as needed. It will be accessible wherever the `query` is available, and is also part of the `QueryFunctionContext` provided to the `queryFn`. ### networkMode `'online' | 'always' | 'offlineFirst' | undefined` * Defaults to `'online'` * See [Network Mode](https://tanstack.com/query/v5/docs/react/guides/network-mode) for more information. ### notifyOnChangeProps `string[] | 'all' | (() => string[] | 'all') | undefined` * If set, the component will only re-render if any of the listed properties change. * If set to `['data', 'error']` for example, the component will only re-render when the `data` or `error` properties change. * If set to `'all'`, the component will opt-out of smart tracking and re-render whenever a query is updated. * If set to a function, the function will be executed to compute the list of properties. * By default, access to properties will be tracked, and the component will only re-render when one of the tracked properties change. ### placeholderData `{{TData}} | ((previousValue: {{TData}} | undefined; previousQuery: Query | undefined) => {{TData}}) | undefined` * If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `pending` state. * `placeholderData` is **not persisted** to the cache * If you provide a function for `placeholderData`, as a first argument you will receive previously watched query data if available, and the second argument will be the complete previousQuery instance. ### queryClient `QueryClient | undefined` Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used. ### refetchInterval `number | false | ((data: {{TData}} | undefined, query: Query) => number | false | undefined) | undefined` * If set to a number, all queries will continuously refetch at this frequency in milliseconds * If set to a function, the function will be executed with the latest data and query to compute a frequency ### refetchIntervalInBackground `boolean | undefined` If set to `true`, queries that are set to continuously refetch with a `refetchInterval` will continue to refetch while their tab/window is in the background ### refetchOnMount `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` * Defaults to `true` * If set to `true`, the query will refetch on mount if the data is stale. * If set to `false`, the query will not refetch on mount. * If set to `'always'`, the query will always refetch on mount. * If set to a function, the function will be executed with the query to compute the value ### refetchOnReconnect `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` * Defaults to `true` * If set to `true`, the query will refetch on reconnect if the data is stale. * If set to `false`, the query will not refetch on reconnect. * If set to `'always'`, the query will always refetch on reconnect. * If set to a function, the function will be executed with the query to compute the value ### refetchOnWindowFocus `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` * Defaults to `true` * If set to `true`, the query will refetch on window focus if the data is stale. * If set to `false`, the query will not refetch on window focus. * If set to `'always'`, the query will always refetch on window focus. * If set to a function, the function will be executed with the query to compute the value ### retry `boolean | number | ((failureCount: number, error: {{TError}}) => boolean) | undefined` * If `false`, failed queries will not retry by default. * If `true`, failed queries will retry infinitely. * If set to a `number`, e.g. `3`, failed queries will retry until the failed query count meets that number. * Defaults to `3` on the client and `0` on the server ``` -------------------------------- ### Composing with useWriteContract Source: https://wagmi.sh/react/api/hooks/useSimulateContract Combine simulation with write operations to reduce wallet validation requirements. ```tsx import { useSimulateContract, useWriteContract } from 'wagmi' import { abi } from './abi' function App() { const { data } = useSimulateContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], }) const { writeContract } = useWriteContract() return ( ) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Import UseSwitchConnectionParameters Source: https://wagmi.sh/react/api/hooks/useSwitchConnection Import the type definition for the hook parameters. ```ts import { type UseSwitchConnectionParameters } from 'wagmi' ``` -------------------------------- ### Import useEnsText Source: https://wagmi.sh/react/api/hooks/useEnsText Import the hook from the wagmi package. ```ts import { useEnsText } from 'wagmi' ``` -------------------------------- ### Configure accessList parameter Source: https://wagmi.sh/react/api/hooks/useSimulateContract Include an access list in the simulation parameters. ```tsx import { useSimulateContract } from 'wagmi' import { abi } from './abi' import { config } from './config' function App() { const result = useSimulateContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], accessList: [{ // [!code focus] address: '0x1', // [!code focus] storageKeys: ['0x1'], // [!code focus] }], // [!code focus] }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Infinite Query Configuration Source: https://wagmi.sh/react/api/hooks/useEstimateFeesPerGas Options specific to configuring infinite queries, including pagination parameters. ```APIDOC ## initialPageParam ### Description The initial page parameter to be passed to the query function. ### Type `{{TPageParam}}` ``` ```APIDOC ## getPreviousPageParam ### Description This function can be set to automatically get the previous cursor for infinite queries. The result will also be used to determine the value of `hasPreviousPage`. ### Type `(firstPage: {{TData}}, allPages: {{TData}}[], firstPageParam: {{TPageParam}}, allPageParams: {{TPageParam}}[]) => {{TPageParam}} | undefined | null` ``` ```APIDOC ## getNextPageParam ### Description This function can be set to automatically get the previous cursor for infinite queries. The result will also be used to determine the value of `hasPreviousPage`. ### Type `(lastPage: {{TData}}, allPages: {{TData}}[], lastPageParam: {{TPageParam}}, allPageParams: {{TPageParam}}[]) => {{TPageParam}} | undefined | null` ``` -------------------------------- ### Link globally linked Wagmi package Source: https://wagmi.sh/react/installation Link the globally linked Wagmi package to your project. ```bash pnpm link --global {{packageName}} ``` -------------------------------- ### Import useWaitForTransactionReceipt Hook Source: https://wagmi.sh/react/api/hooks/useWaitForTransactionReceipt Import the useWaitForTransactionReceipt hook from the wagmi library. ```typescript import { useWaitForTransactionReceipt } from 'wagmi' ``` -------------------------------- ### Refetching and Network Configuration Source: https://wagmi.sh/react/api/hooks/useEstimateFeesPerGas Options controlling when and how queries are refetched, and network behavior. ```APIDOC ## networkMode ### Description Controls the network mode for queries. See [Network Mode](https://tanstack.com/query/v5/docs/react/guides/network-mode) for more information. ### Type `'online' | 'always' | 'offlineFirst' | undefined` ### Defaults `'online'` ``` ```APIDOC ## notifyOnChangeProps ### Description If set, the component will only re-render if any of the listed properties change. If set to `['data', 'error']` for example, the component will only re-render when the `data` or `error` properties change. If set to `'all'`, the component will opt-out of smart tracking and re-render whenever a query is updated. If set to a function, the function will be executed to compute the list of properties. By default, access to properties will be tracked, and the component will only re-render when one of the tracked properties change. ### Type `string[] | 'all' | (() => string[] | 'all') | undefined` ``` ```APIDOC ## refetchInterval ### Description If set to a number, all queries will continuously refetch at this frequency in milliseconds. If set to a function, the function will be executed with the latest data and query to compute a frequency. ### Type `number | false | ((data: {{TData}} | undefined, query: Query) => number | false | undefined) | undefined` ``` ```APIDOC ## refetchIntervalInBackground ### Description If set to `true`, queries that are set to continuously refetch with a `refetchInterval` will continue to refetch while their tab/window is in the background. ### Type `boolean | undefined` ``` ```APIDOC ## refetchOnMount ### Description Controls whether a query refetches on mount. Defaults to `true`. If set to `true`, the query will refetch on mount if the data is stale. If set to `false`, the query will not refetch on mount. If set to `'always'`, the query will always refetch on mount. If set to a function, the function will be executed with the query to compute the value. ### Type `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` ### Defaults `true` ``` -------------------------------- ### useChains Hook Source: https://wagmi.sh/react/api/hooks/useChains Retrieves the list of chains configured in the wagmi project. ```APIDOC ## useChains ### Description Retrieves the list of chains from the wagmi configuration. ### Parameters #### Request Body - **config** (Config | undefined) - Optional - The configuration object to use instead of retrieving from the nearest WagmiProvider. ### Response - **Return Type** (readonly [Chain, ...Chain[]]) - The list of chains defined in the configuration. ``` -------------------------------- ### Import UseBytecodeParameters Source: https://wagmi.sh/react/api/hooks/useBytecode Import the type definition for the hook parameters. ```ts import { type UseBytecodeParameters } from 'wagmi' ``` -------------------------------- ### Basic Usage of useWatchContractEvent Source: https://wagmi.sh/react/api/hooks/useWatchContractEvent Demonstrates the basic implementation of the hook to watch for 'Transfer' events. ```tsx import { useWatchContractEvent } from 'wagmi' import { abi } from './abi' function App() { useWatchContractEvent({ address: '0x6b175474e89094c44da98b954eedeac495271d0f', abi, eventName: 'Transfer', onLogs(logs) { console.log('New logs!', logs) }, }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### useSimulateContract - args parameter Source: https://wagmi.sh/react/api/hooks/useSimulateContract Arguments to pass when calling the contract. These are inferred from the ABI and function name. ```APIDOC ## POST /simulateContract ### Description Simulates a contract interaction using the provided parameters. ### Method POST ### Endpoint /simulateContract ### Parameters #### Request Body - **account** (Account | undefined) - The account to use when calling the contract (msg.sender). Throws if account is not found on connector. - **address** (Address | undefined) - The contract's address. - **functionName** (string) - The name of the function to call on the contract. - **args** (unknown[]) - Arguments to pass when calling the contract. Inferred from `abi` and `functionName`. - **abi** (Abi | undefined) - The contract's ABI. - **blockNumber** (bigint | undefined) - Block number to call contract at. - **blockTag** ('latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined) - Block tag to call contract at. ### Request Example ```json { "args": [ "0xd2135CfB216b74109775236E36d4b433F1DF507B", "0xA0Cf798816D4b9b9866b5330EEa46a18382f251e", 123n ] } ``` ### Response #### Success Response (200) - **result** (SimulateContractResult) - The result of the contract simulation. #### Response Example ```json { "result": { "data": "0x...", "request": { "from": "0xd2135CfB216b74109775236E36d4b433F1DF507B", "to": "0x6b175474e89094c44da98b954eedeac495271d0f", "value": 0n, "data": "0x..." } } } ``` ``` -------------------------------- ### Convert Connector Client to Ethers Signer Source: https://wagmi.sh/react/guides/ethers Reference implementations for converting a Viem connector client to an Ethers.js signer. ```typescript import { providers } from 'ethers' import { useMemo } from 'react' import type { Account, Chain, Client, Transport } from 'viem' import { Config, useConnectorClient } from 'wagmi' export function clientToSigner(client: Client) { const { account, chain, transport } = client const network = { chainId: chain.id, name: chain.name, ensAddress: chain.contracts?.ensRegistry?.address, } const provider = new providers.Web3Provider(transport, network) const signer = provider.getSigner(account.address) return signer } /** Hook to convert a Viem Client to an ethers.js Signer. */ export function useEthersSigner({ chainId }: { chainId?: number } = {}) { const { data: client } = useConnectorClient({ chainId }) return useMemo(() => (client ? clientToSigner(client) : undefined), [client]) } ``` ```typescript import { BrowserProvider, JsonRpcSigner } from 'ethers' import { useMemo } from 'react' import type { Account, Chain, Client, Transport } from 'viem' import { type Config, useConnectorClient } from 'wagmi' export function clientToSigner(client: Client) { const { account, chain, transport } = client const network = { chainId: chain.id, name: chain.name, ensAddress: chain.contracts?.ensRegistry?.address, } const provider = new BrowserProvider(transport, network) const signer = new JsonRpcSigner(provider, account.address) return signer } /** Hook to convert a viem Wallet Client to an ethers.js Signer. */ export function useEthersSigner({ chainId }: { chainId?: number } = {}) { const { data: client } = useConnectorClient({ chainId }) return useMemo(() => (client ? clientToSigner(client) : undefined), [client]) } ``` -------------------------------- ### Use useConnectorClient with a Specific Account Source: https://wagmi.sh/react/api/hooks/useConnectorClient Obtain a Viem Client for a specific account by passing the account address to the useConnectorClient hook. ```tsx import { useConnectorClient } from 'wagmi' function App() { const result = useConnectorClient({ account: '0xd2135CfB216b74109775236E36d4b433F1DF507B', }) } ``` -------------------------------- ### Basic Usage Source: https://wagmi.sh/react/api/hooks/useWatchBlocks Monitor new blocks and log their numbers. ```tsx import { useWatchBlocks } from 'wagmi' function App() { useWatchBlocks({ onBlock(block) { console.log('New block', block.number) }, }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### refetchOnMount Source: https://wagmi.sh/react/api/hooks/useEnsResolver Configures refetching behavior when a component mounts. ```APIDOC ## refetchOnMount ### Description If set to `true`, the query will refetch on mount if the data is stale. If set to `false`, the query will not refetch on mount. If set to `'always'`, the query will always refetch on mount. If set to a function, the function will be executed with the query to compute the value. ### Type `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` ### Default `true` ``` -------------------------------- ### Import UseBalanceParameters Source: https://wagmi.sh/react/api/hooks/useBalance Import the parameter type definition for the hook. ```ts import { type UseBalanceParameters } from 'wagmi' ``` -------------------------------- ### config Configuration Source: https://wagmi.sh/react/api/hooks/useWatchContractEvent Allows specifying a custom Wagmi configuration object instead of relying on the nearest WagmiProvider. ```APIDOC ## config ### Description [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ### Type `Config | undefined` ### Request Example ```tsx import { useWatchContractEvent } from 'wagmi' import { abi } from './abi' import { config } from './config' function App() { useWatchContractEvent({ address: '0x6b175474e89094c44da98b954eedeac495271d0f', abi, config, // [!code focus] eventName: 'Transfer', onLogs(logs) { console.log('New logs!', logs) }, }) } ``` ``` -------------------------------- ### TanStack Query Parameters Source: https://wagmi.sh/react/api/hooks/useBlockTransactionCount These are parameters compatible with TanStack Query. Refer to the [TanStack Query documentation](https://tanstack.com/query/v5/docs/react/reference/useQuery) for more details. Note that some parameters like `queryFn` and `queryKey` are used internally by Wagmi and cannot be overridden. ```APIDOC ### query TanStack Query parameters. See the [TanStack Query query docs](https://tanstack.com/query/v5/docs/react/reference/useQuery) for more info. ::: info Wagmi does not support passing all TanStack Query parameters TanStack Query parameters, like `queryFn` and `queryKey`, are used internally to make Wagmi work and you cannot override them. Check out the [source](https://github.com/wevm/wagmi/blob/main/packages/react/src/types/properties.ts#L27) to see what parameters are not supported. All parameters listed below are supported. ::: #### enabled `boolean | undefined` * Set this to `false` to disable this query from automatically running. * Can be used for [Dependent Queries](https://tanstack.com/query/v5/docs/react/guides/dependent-queries). #### gcTime `number | Infinity | undefined` * Defaults to `5 * 60 * 1000` (5 minutes) or `Infinity` during SSR * The time in milliseconds that unused/inactive cache data remains in memory. When a query's cache becomes unused or inactive, that cache data will be garbage collected after this duration. When different garbage collection times are specified, the longest one will be used. * If set to `Infinity`, will disable garbage collection #### initialData `{{TData}} | (() => {{TData}}) | undefined` * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been created or cached yet) * If set to a function, the function will be called **once** during the shared/root query initialization, and be expected to synchronously return the initialData * Initial data is considered stale by default unless a `staleTime` has been set. * `initialData` **is persisted** to the cache #### initialDataUpdatedAt `number | (() => number | undefined)) | undefined` If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. #### initialPageParam `{{TPageParam}}` The initial page parameter to be passed to the query function. #### getPreviousPageParam This function can be set to automatically get the previous cursor for infinite queries. The result will also be used to determine the value of `hasPreviousPage`. `(firstPage: {{TData}}, allPages: {{TData}}[], firstPageParam: {{TPageParam}}, allPageParams: {{TPageParam}}[]) => {{TPageParam}} | undefined | null` #### getNextPageParam This function can be set to automatically get the previous cursor for infinite queries. The result will also be used to determine the value of `hasPreviousPage`. `(lastPage: {{TData}}, allPages: {{TData}}[], lastPageParam: {{TPageParam}}, allPageParams: {{TPageParam}}[]) => {{TPageParam}} | undefined | null` #### meta `Record | undefined` If set, stores additional information on the query cache entry that can be used as needed. It will be accessible wherever the `query` is available, and is also part of the `QueryFunctionContext` provided to the `queryFn`. #### networkMode `online' | 'always' | 'offlineFirst' | undefined` * Defaults to `'online'` * see [Network Mode](https://tanstack.com/query/v5/docs/react/guides/network-mode) for more information. #### notifyOnChangeProps `string[] | 'all' | (() => string[] | 'all') | undefined` * If set, the component will only re-render if any of the listed properties change. * If set to `['data', 'error']` for example, the component will only re-render when the `data` or `error` properties change. * If set to `'all'`, the component will opt-out of smart tracking and re-render whenever a query is updated. * If set to a function, the function will be executed to compute the list of properties. * By default, access to properties will be tracked, and the component will only re-render when one of the tracked properties change. ``` -------------------------------- ### Import baseAccount Source: https://wagmi.sh/react/api/connectors/baseAccount Import the baseAccount connector from the connectors package. ```ts import { baseAccount } from '{{connectorsPackageName}}' ``` -------------------------------- ### Configure Safe Connector with Allowed Domains Source: https://wagmi.sh/react/api/connectors/safe Initialize the Safe connector, restricting connections to specified domains using a RegExp array. ```typescript import { safe } from '{{connectorsPackageName}}' const connector = safe({ allowedDomains: [/app.safe.global$/], }) ``` -------------------------------- ### Import useEstimateMaxPriorityFeePerGas Source: https://wagmi.sh/react/api/hooks/useEstimateMaxPriorityFeePerGas Import the hook from the wagmi package. ```ts import { useEstimateMaxPriorityFeePerGas } from 'wagmi' ``` -------------------------------- ### useReadContract - config Source: https://wagmi.sh/react/api/hooks/useReadContract Config to use instead of retrieving from the nearest WagmiProvider. ```APIDOC ## useReadContract config ### Description [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ### Parameters #### Request Body - **config** (Config) - Optional - Config to use instead of retrieving from the nearest WagmiProvider. ### Request Example ```json { "config": { "chains": [ { "id": 1, "name": "Ethereum", "type": "mainnet" } ], "transports": { "1": { "url": "http://localhost:8545" } } } } ``` ### Response #### Success Response (200) - **result** (unknown) - The result of the contract call. #### Response Example ```json { "result": "0x..." } ``` ``` -------------------------------- ### Configure custom config for useBlobBaseFee Source: https://wagmi.sh/react/api/hooks/useBlobBaseFee Provide a custom Wagmi config instance instead of using the default provider context. ```tsx import { useBlobBaseFee } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useBlobBaseFee({ config, // [!code focus] }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Import ABIs from viem instead of wagmi Source: https://wagmi.sh/react/guides/migrate-from-v1-to-v2 ABI exports have been removed from the main `wagmi` package. Import ABIs directly from the `viem` package. ```typescript import { erc20ABI } from 'wagmi' // [!code --] import { erc20Abi } from 'viem' // [!code ++] ``` -------------------------------- ### Query Configuration Options Source: https://wagmi.sh/react/api/hooks/useFeeHistory Configuration options for customizing query behavior. ```APIDOC ## notifyOnChangeProps ### Description If set, the component will only re-render if any of the listed properties change. If set to `['data', 'error']` for example, the component will only re-render when the `data` or `error` properties change. If set to `'all'`, the component will opt-out of smart tracking and re-render whenever a query is updated. If set to a function, the function will be executed to compute the list of properties. By default, access to properties will be tracked, and the component will only re-render when one of the tracked properties change. ### Type `string[] | 'all' | (() => string[] | 'all') | undefined` ## placeholderData ### Description If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `pending` state. `placeholderData` is **not persisted** to the cache. If you provide a function for `placeholderData`, as a first argument you will receive previously watched query data if available, and the second argument will be the complete previousQuery instance. ### Type `{{TData}} | ((previousValue: {{TData}} | undefined; previousQuery: Query | undefined) => {{TData}}) | undefined` ## queryClient ### Description Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used. ### Type `QueryClient | undefined` ## refetchInterval ### Description If set to a number, all queries will continuously refetch at this frequency in milliseconds. If set to a function, the function will be executed with the latest data and query to compute a frequency. ### Type `number | false | ((data: {{TData}} | undefined, query: Query) => number | false | undefined) | undefined` ## refetchIntervalInBackground ### Description If set to `true`, queries that are set to continuously refetch with a `refetchInterval` will continue to refetch while their tab/window is in the background. ### Type `boolean | undefined` ## refetchOnMount ### Description Defaults to `true`. If set to `true`, the query will refetch on mount if the data is stale. If set to `false`, the query will not refetch on mount. If set to `'always'`, the query will always refetch on mount. If set to a function, the function will be executed with the query to compute the value. ### Type `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` ## refetchOnReconnect ### Description Defaults to `true`. If set to `true`, the query will refetch on reconnect if the data is stale. If set to `false`, the query will not refetch on reconnect. If set to `'always'`, the query will always refetch on reconnect. If set to a function, the function will be executed with the query to compute the value. ### Type `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` ## refetchOnWindowFocus ### Description Defaults to `true`. If set to `true`, the query will refetch on window focus if the data is stale. If set to `false`, the query will not refetch on window focus. If set to `'always'`, the query will always refetch on window focus. If set to a function, the function will be executed with the query to compute the value. ### Type `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` ## retry ### Description If `false`, failed queries will not retry by default. If `true`, failed queries will retry infinitely. If set to a `number`, e.g. `3`, failed queries will retry until the failed query count meets that number. Defaults to `3` on the client and `0` on the server. ### Type `boolean | number | ((failureCount: number, error: {{TError}}) => boolean) | undefined` ## retryDelay ### Description This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds. A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff. A function like `attempt => attempt * 1000` applies linear backoff. ### Type `number | ((retryAttempt: number, error: {{TError}}) => number) | undefined` ## retryOnMount ### Description If set to `false`, the query will not be retried on mount if it contains an error. Defaults to `true`. ### Type `boolean | undefined` ## select ### Description This option can be used to transform or select a part of the data returned by the query function. It affects the returned `data` value, but does not affect what gets stored in the query cache. ### Type `((data: {{TData}}) => unknown) | undefined` ## staleTime ### Description Defaults to `0`. The time in milliseconds after data is considered stale. This value only applies to the hook it is defined on. If set to `Infinity`, the data will never be considered stale. ### Type `number | Infinity | undefined` ``` -------------------------------- ### Action Reference Source: https://wagmi.sh/react/api/hooks/useSwitchChain Reference to the switchChain action. ```APIDOC ## Action * [`switchChain`](/core/api/actions/switchChain) ``` -------------------------------- ### Basic Usage of useCapabilities Hook Source: https://wagmi.sh/react/api/hooks/useCapabilities Demonstrates the basic usage of the useCapabilities hook in a React component. ```tsx import { useCapabilities } from 'wagmi' function App() { const result = useCapabilities() } ``` -------------------------------- ### Hook Configuration and Return Properties Source: https://wagmi.sh/react/api/hooks/useEnsName Overview of the structuralSharing configuration and the various state properties returned by Wagmi hooks. ```APIDOC ## Configuration: structuralSharing ### Description Controls how data is shared between query results to improve performance. ### Parameters - **structuralSharing** (boolean | function) - Optional - Defaults to true. If false, disables structural sharing. If a function, allows custom merging of old and new data. ## Return Properties ### Data and Status - **data** (TData) - The last successfully resolved data. - **dataUpdatedAt** (number) - Timestamp of the last successful data update. - **status** (string) - The current status of the query (e.g., success, error). - **isPending / isSuccess / isError** (boolean) - Derived status flags. - **fetchStatus** ('fetching' | 'idle' | 'paused') - The current fetch status. ### Error Handling - **error** (null | TError) - The error object if the query failed. - **errorUpdatedAt** (number) - Timestamp of the last error update. - **errorUpdateCount** (number) - Sum of all errors. - **failureCount** (number) - Number of times the query has failed. - **failureReason** (null | TError) - The reason for the query retry failure. ### Pagination - **fetchNextPage** (function) - Fetches the next page of results. - **fetchPreviousPage** (function) - Fetches the previous page of results. - **hasNextPage / hasPreviousPage** (boolean) - Indicates if more pages are available. - **isFetchingNextPage / isFetchingPreviousPage** (boolean) - Indicates if a page fetch is in progress. ### Refetching - **refetch** (function) - Manually triggers a query refetch. ### Utility Flags - **isFetched** (boolean) - True if the query has been fetched. - **isFetchedAfterMount** (boolean) - True if fetched after component mount. - **isStale** (boolean) - True if data is invalidated or older than staleTime. ``` -------------------------------- ### Basic Usage of useClient Source: https://wagmi.sh/react/api/hooks/useClient Retrieve the client instance within a React component. ```tsx import { useClient } from 'wagmi' function App() { const client = useClient() } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Configure emitOnBegin for useWatchBlocks Source: https://wagmi.sh/react/api/hooks/useWatchBlocks Sets whether to emit the block to the callback when the subscription opens. ```ts // {"path":"/vercel/path0/site/react/api/hooks/useWatchBlocks.md","from":2440,"to":2636} import { useWatchBlocks } from 'wagmi' function App() { useWatchBlocks({ emitOnBegin: true, // [!code focus] onBlock(block) { console.log('New block', block.number) }, }) } ``` ```ts import { createConfig, http } from '@wagmi/core' import { mainnet, sepolia } from '@wagmi/core/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### useBlock Hook Options Source: https://wagmi.sh/react/api/hooks/useBlock Configuration options for the useBlock hook to customize data fetching and caching behavior. ```APIDOC ## useBlock Hook Options ### select `((data: {{TData}}) => unknown) | undefined` This option can be used to transform or select a part of the data returned by the query function. It affects the returned `data` value, but does not affect what gets stored in the query cache. ### staleTime `number | Infinity | undefined` * Defaults to `0` * The time in milliseconds after data is considered stale. This value only applies to the hook it is defined on. * If set to `Infinity`, the data will never be considered stale ### structuralSharing `boolean | (((oldData: {{TData}} | undefined, newData: {{TData}}) => {{TData}})) | undefined` * Defaults to `true` * If set to `false`, structural sharing between query results will be disabled. * If set to a function, the old and new data values will be passed through this function, which should combine them into resolved data for the query. This way, you can retain references from the old data to improve performance even when that data contains non-serializable values. ``` -------------------------------- ### Use Verify Message Hook with Scope Key Source: https://wagmi.sh/react/api/hooks/useVerifyMessage Demonstrates how to use the `useVerifyMessage` hook with a `scopeKey` to scope the cache to a specific context. Hooks with identical context will share the same cache. ```tsx import { useVerifyMessage } from 'wagmi' import { config } from './config' function App() { const result = useVerifyMessage({ scopeKey: 'foo' // [!code focus] address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message: 'hello world', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) } ``` -------------------------------- ### Basic Usage of useConnections Hook Source: https://wagmi.sh/react/api/hooks/useConnections Demonstrates the basic usage of the useConnections hook in a React component. No specific parameters are required for basic functionality. ```tsx import { useConnections } from 'wagmi' function App() { const connections = useConnections() } ``` -------------------------------- ### Basic Usage Source: https://wagmi.sh/react/api/hooks/usePublicClient Retrieve the PublicClient instance within a component. ```tsx import { usePublicClient } from 'wagmi' function App() { const client = usePublicClient() } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### useEstimateGas Parameters Source: https://wagmi.sh/react/api/hooks/useEstimateGas This section details the parameters available for the useEstimateGas hook. ```APIDOC ## useEstimateGas Hook Parameters ### nonce `number` Unique number identifying this transaction. ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ### to `Address | undefined` The transaction recipient or contract address. ### type `'legacy' | 'eip1559' | 'eip2930' | undefined` Optional transaction request type to narrow parameters. ### value `bigint | undefined` Value in wei sent with this transaction. ### query TanStack Query parameters. See the [TanStack Query query docs](https://tanstack.com/query/v5/docs/react/reference/useQuery) for more info. ::: info Wagmi does not support passing all TanStack Query parameters TanStack Query parameters, like `queryFn` and `queryKey`, are used internally to make Wagmi work and you cannot override them. Check out the [source](https://github.com/wevm/wagmi/blob/main/packages/react/src/types/properties.ts#L27) to see what parameters are not supported. All parameters listed below are supported. ::: #### enabled `boolean | undefined` * Set this to `false` to disable this query from automatically running. * Can be used for [Dependent Queries](https://tanstack.com/query/v5/docs/react/guides/dependent-queries). ``` -------------------------------- ### Fetch with custom config Source: https://wagmi.sh/react/api/hooks/useBlock Provide a custom Wagmi configuration instead of using the provider context. ```tsx import { useBlock } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useBlock({ config, // [!code focus] }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Query Hook Configuration Options Source: https://wagmi.sh/react/api/hooks/useEnsName A comprehensive list of configuration options for customizing query behavior in React Query hooks. ```APIDOC ## Query Hook Configuration Options ### Description Configuration options used to customize the behavior of React Query hooks, including data fetching, caching, and re-rendering logic. ### Parameters - **notifyOnChangeProps** (string[] | 'all' | function) - Optional - Defines which properties trigger a component re-render. - **placeholderData** (TData | function) - Optional - Provides initial data while the query is in a pending state. - **queryClient** (QueryClient) - Optional - Specifies a custom QueryClient instance. - **refetchInterval** (number | false | function) - Optional - Frequency in milliseconds for continuous refetching. - **refetchIntervalInBackground** (boolean) - Optional - Enables refetching while the window is in the background. - **refetchOnMount** (boolean | 'always' | function) - Optional - Determines if the query refetches on mount. - **refetchOnReconnect** (boolean | 'always' | function) - Optional - Determines if the query refetches on network reconnect. - **refetchOnWindowFocus** (boolean | 'always' | function) - Optional - Determines if the query refetches on window focus. - **retry** (boolean | number | function) - Optional - Configures retry behavior for failed queries. - **retryDelay** (number | function) - Optional - Sets the delay between retry attempts. - **retryOnMount** (boolean) - Optional - Determines if the query retries on mount if it contains an error. - **select** (function) - Optional - Transforms or selects a subset of the returned data. - **staleTime** (number | Infinity) - Optional - Time in milliseconds before data is considered stale. ``` -------------------------------- ### Import useConnectionEffect Source: https://wagmi.sh/react/api/hooks/useConnectionEffect Import the hook from the wagmi package. ```ts import { useConnectionEffect } from 'wagmi' ``` -------------------------------- ### Import useVerifyMessage Source: https://wagmi.sh/react/api/hooks/useVerifyMessage Import the hook from the wagmi package. ```ts import { useVerifyMessage } from 'wagmi' ``` -------------------------------- ### Use Contract Events with Custom Config Source: https://wagmi.sh/react/api/hooks/useContractEvents Uses a provided `Config` object instead of the one from the nearest `WagmiProvider`. Ensure the config is correctly set up. ```tsx import { useContractEvents } from 'wagmi' import { abi } from './abi' import { config } from './config' function App() { const result = useContractEvents({ abi, config, }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Import baseAccountParameters Source: https://wagmi.sh/react/api/connectors/baseAccount Import the type definition for baseAccount parameters. ```ts import { type baseAccountParameters } from '{{connectorsPackageName}}' ``` -------------------------------- ### injected() Source: https://wagmi.sh/react/api/connectors/injected Initializes the injected connector for EIP-1193 Ethereum providers. ```APIDOC ## injected() ### Description Creates a connector instance for EIP-1193 Ethereum providers, enabling interaction with browser-injected wallets. ### Parameters #### Request Body - **shimDisconnect** (boolean) - Optional - Simulates disconnect behavior for providers that do not support it programmatically. Defaults to true. - **target** (TargetId | object | function) - Optional - Specifies the EIP-1193 provider to target. - **unstable_shimAsyncInject** (boolean | number) - Optional - Watches for async provider injection via the 'ethereum#initialized' event. If true, defaults to 1000ms, or accepts a custom millisecond value. ### Request Example ```ts import { injected } from '@wagmi/connectors' const connector = injected({ shimDisconnect: true, unstable_shimAsyncInject: 2000 }) ``` ``` -------------------------------- ### Import useCapabilities Hook Source: https://wagmi.sh/react/api/hooks/useCapabilities Import the useCapabilities hook from the wagmi library. ```typescript import { useCapabilities } from 'wagmi' ``` -------------------------------- ### Wagmi Configuration Source: https://wagmi.sh/react/guides/send-transaction Sets up the Wagmi configuration with specified chains, connectors, and transports. Ensure you replace '' with your actual Project ID for WalletConnect to function. ```ts import { http, createConfig } from 'wagmi' import { base, mainnet, optimism } from 'wagmi/chains' import { injected, metaMask, safe, walletConnect } from 'wagmi/connectors' const projectId = '' export const config = createConfig({ chains: [mainnet, base], connectors: [ injected(), walletConnect({ projectId }), metaMask(), safe(), ], transports: { [mainnet.id]: http(), [base.id]: http(), }, }) ``` -------------------------------- ### Import UseConfigReturnType Source: https://wagmi.sh/react/api/hooks/useConfig Import the return type for the useConfig hook. ```ts import { type UseConfigReturnType } from 'wagmi' ``` -------------------------------- ### usePrepareTransactionRequest Hook Source: https://wagmi.sh/react/api/hooks/usePrepareTransactionRequest The usePrepareTransactionRequest hook prepares a transaction request by populating required fields such as nonce, gas limit, and fee values. ```APIDOC ## usePrepareTransactionRequest ### Description Hook for preparing a transaction request for signing by populating a nonce, gas limit, fee values, and a transaction type. ### Parameters - **account** (Account | Address | undefined) - Optional - The Account to send the transaction from. - **to** (`0x${string}` | undefined) - Optional - The transaction recipient or contract address. - **accessList** (AccessList | undefined) - Optional - The access list. - **chainId** (config['chains'][number]['id'] | undefined) - Optional - Chain ID to prepare the transaction request for. ### Request Example ```tsx import { usePrepareTransactionRequest } from 'wagmi' import { parseEther } from 'viem' function App() { const result = usePrepareTransactionRequest({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), }) } ``` ``` -------------------------------- ### Import hook Source: https://wagmi.sh/react/api/hooks/usePrepareTransactionRequest Import the hook from the wagmi package. ```ts import { usePrepareTransactionRequest } from 'wagmi' ``` -------------------------------- ### Wagmi Hook Configuration Options Source: https://wagmi.sh/react/api/hooks/useBlockNumber Detailed explanations of configuration options for Wagmi React hooks. ```APIDOC ## Placeholder Data ### Description If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `pending` state. `placeholderData` is **not persisted** to the cache. If you provide a function for `placeholderData`, as a first argument you will receive previously watched query data if available, and the second argument will be the complete previousQuery instance. ### Type `{{TData}} | ((previousValue: {{TData}} | undefined; previousQuery: Query | undefined) => {{TData}}) | undefined` ## Query Client ### Description Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used. ### Type `QueryClient | undefined` ## Refetch Interval ### Description If set to a number, all queries will continuously refetch at this frequency in milliseconds. If set to a function, the function will be executed with the latest data and query to compute a frequency. ### Type `number | false | ((data: {{TData}} | undefined, query: Query) => number | false | undefined) | undefined` ## Refetch Interval In Background ### Description If set to `true`, queries that are set to continuously refetch with a `refetchInterval` will continue to refetch while their tab/window is in the background. ### Type `boolean | undefined` ## Refetch On Mount ### Description Defaults to `true`. If set to `true`, the query will refetch on mount if the data is stale. If set to `false`, the query will not refetch on mount. If set to `'always'`, the query will always refetch on mount. If set to a function, the function will be executed with the query to compute the value. ### Type `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` ## Refetch On Reconnect ### Description Defaults to `true`. If set to `true`, the query will refetch on reconnect if the data is stale. If set to `false`, the query will not refetch on reconnect. If set to `'always'`, the query will always refetch on reconnect. If set to a function, the function will be executed with the query to compute the value. ### Type `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` ## Refetch On Window Focus ### Description Defaults to `true`. If set to `true`, the query will refetch on window focus if the data is stale. If set to `false`, the query will not refetch on window focus. If set to `'always'`, the query will always refetch on window focus. If set to a function, the function will be executed with the query to compute the value. ### Type `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` ## Retry ### Description If `false`, failed queries will not retry by default. If `true`, failed queries will retry infinitely. If set to a `number`, e.g. `3`, failed queries will retry until the failed query count meets that number. Defaults to `3` on the client and `0` on the server. ### Type `boolean | number | ((failureCount: number, error: {{TError}}) => boolean) | undefined` ## Retry Delay ### Description This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds. A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff. A function like `attempt => attempt * 1000` applies linear backoff. ### Type `number | ((retryAttempt: number, error: {{TError}}) => number) | undefined` ## Retry On Mount ### Description If set to `false`, the query will not be retried on mount if it contains an error. Defaults to `true`. ### Type `boolean | undefined` ## Select ### Description This option can be used to transform or select a part of the data returned by the query function. It affects the returned `data` value, but does not affect what gets stored in the query cache. ### Type `((data: {{TData}}) => unknown) | undefined` ## Stale Time ### Description Defaults to `0`. The time in milliseconds after data is considered stale. This value only applies to the hook it is defined on. If set to `Infinity`, the data will never be considered stale. ### Type `number | Infinity | undefined` ## Structural Sharing ### Description Defaults to `true`. If set to `false`, structural sharing between query results will be disabled. If set to a function, the old and new data values will be passed through this function, which should combine them into resolved data for the query. This way, you can retain references from the old data to improve performance even when that data contains non-serializable values. ### Type `boolean | (((oldData: {{TData}} | undefined, newData: {{TData}}) => {{TData}})) | undefined` ``` -------------------------------- ### Import UseWatchAssetParameters Source: https://wagmi.sh/react/api/hooks/useWatchAsset Import the parameter type definition for the hook. ```ts import { type UseWatchAssetParameters } from 'wagmi' ``` -------------------------------- ### refetch Method Source: https://wagmi.sh/react/api/hooks/useCapabilities Manual trigger for query refetching. ```APIDOC ## refetch ### Description A function to manually trigger a query refetch. ### Parameters - **options** (object) - Optional - **cancelRefetch** (boolean) - Optional - If true, cancels running requests before starting a new one. Defaults to true. - **throwOnError** (boolean) - Optional - If true, throws an error on failure; if false, logs the error. ``` -------------------------------- ### Import UseInfiniteReadContractsParameters Type Source: https://wagmi.sh/react/api/hooks/useInfiniteReadContracts Import the `UseInfiniteReadContractsParameters` type for defining hook parameters. ```typescript import { type UseInfiniteReadContractsParameters } from 'wagmi' ``` -------------------------------- ### Import MetaMask Parameters Type Source: https://wagmi.sh/react/api/connectors/metaMask Import the type definition for MetaMask connector parameters. ```ts import { type MetaMaskParameters } from '{{connectorsPackageName}}' ``` -------------------------------- ### Configure args for useReadContracts Source: https://wagmi.sh/react/api/hooks/useReadContracts Pass arguments to the contract function call. These are inferred from the provided ABI and function name. ```tsx import { useReadContracts } from 'wagmi' function App() { const result = useReadContracts({ contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, functionName: 'getChest', args: [69], // [!code hl] }, // ... ], }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Configure Dapp Metadata Source: https://wagmi.sh/react/api/connectors/metaMask Provide metadata to customize the UX on MetaMask confirmation screens. ```ts import { metaMask } from '{{connectorsPackageName}}' const connector = metaMask({ dapp: { // [!code focus] name: 'My Wagmi App', // [!code focus] url: 'https://example.com', // [!code focus] iconUrl: 'https://example.com/favicon.ico', // [!code focus] } }) ``` -------------------------------- ### Configure unstable_shimAsyncInject Source: https://wagmi.sh/react/api/connectors/injected Watch for async provider injection via the ethereum#initialized event. ```ts-vue import { injected } from '{{connectorsPackageName}}' const connector = injected({ unstable_shimAsyncInject: 2_000, // [!code focus] }) ``` -------------------------------- ### Import useCallsStatus Source: https://wagmi.sh/react/api/hooks/useCallsStatus Import the hook from the wagmi package. ```ts import { useCallsStatus } from 'wagmi' ``` -------------------------------- ### Configure custom config for useProof Source: https://wagmi.sh/react/api/hooks/useProof Overrides the default WagmiProvider configuration with a custom Config instance. ```tsx import { useProof } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useProof({ config, // [!code focus] address: '0x4200000000000000000000000000000000000016', storageKeys: [ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### TanStack Query Configuration Parameters Source: https://wagmi.sh/react/api/hooks/useTransactionReceipt Configuration options for customizing query behavior in Wagmi hooks. ```APIDOC ## TanStack Query Configuration Parameters ### Description These parameters allow you to configure the behavior of queries within Wagmi hooks. Note that some TanStack Query parameters are reserved for internal use and cannot be overridden. ### Parameters - **enabled** (boolean | undefined) - Optional - Set to false to disable the query from automatically running. - **gcTime** (number | Infinity | undefined) - Optional - Time in milliseconds that unused/inactive cache data remains in memory. - **initialData** ({{TData}} | (() => {{TData}}) | undefined) - Optional - Initial data for the query cache. - **initialDataUpdatedAt** (number | (() => number | undefined) | undefined) - Optional - Timestamp of when initialData was last updated. - **initialPageParam** ({{TPageParam}}) - Optional - Initial page parameter for infinite queries. - **getPreviousPageParam** (function) - Optional - Function to get the previous cursor for infinite queries. - **getNextPageParam** (function) - Optional - Function to get the next cursor for infinite queries. - **meta** (Record | undefined) - Optional - Additional information stored on the query cache entry. - **networkMode** ('online' | 'always' | 'offlineFirst' | undefined) - Optional - Defines how the query handles network connectivity. - **notifyOnChangeProps** (string[] | 'all' | (() => string[] | 'all') | undefined) - Optional - Controls component re-renders based on property changes. - **placeholderData** ({{TData}} | ((previousValue: {{TData}} | undefined; previousQuery: Query | undefined) => {{TData}}) | undefined) - Optional - Data used while the query is in the pending state. - **queryClient** (QueryClient | undefined) - Optional - Custom QueryClient instance. - **refetchInterval** (number | false | ((data: {{TData}} | undefined, query: Query) => number | false | undefined) | undefined) - Optional - Frequency in milliseconds for continuous refetching. - **refetchIntervalInBackground** (boolean | undefined) - Optional - If true, refetching continues when the tab/window is in the background. ``` -------------------------------- ### Using useWaitForCallsStatus with Custom Config Source: https://wagmi.sh/react/api/hooks/useWaitForCallsStatus Provide a custom wagmi configuration to `useWaitForCallsStatus` if you are not using the default one. ```tsx import { useWaitForCallsStatus } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useWaitForCallsStatus({ config, // [!code focus] id: '0x...', }) } ``` ```typescript import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Import useWatchContractEvent Source: https://wagmi.sh/react/api/hooks/useWatchContractEvent Import the hook from the wagmi package. ```ts import { useWatchContractEvent } from 'wagmi' ``` -------------------------------- ### Configure config parameter Source: https://wagmi.sh/react/api/hooks/useWatchPendingTransactions Provide a custom Wagmi config instance instead of using the default provider. ```tsx import { useWatchPendingTransactions } from 'wagmi' import { config } from './config' function App() { useWatchPendingTransactions({ config // [!code focus] onTransactions(transactions) { console.log('New transactions!', transactions) }, }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Import UseTransactionReceiptParameters Source: https://wagmi.sh/react/api/hooks/useTransactionReceipt Import the type definition for the hook parameters. ```ts import { type UseTransactionReceiptParameters } from 'wagmi' ``` -------------------------------- ### Estimate Gas with AccessList Source: https://wagmi.sh/react/api/hooks/useEstimateGas Provide an access list to the estimation hook. ```ts import { useEstimateGas } from 'wagmi' import { parseEther } from 'viem' import { config } from './config' function App() { const result = useEstimateGas({ accessList: [{ // [!code focus] address: '0x1', // [!code focus] storageKeys: ['0x1'], // [!code focus] }], // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Import UseWatchAssetReturnType Source: https://wagmi.sh/react/api/hooks/useWatchAsset Import the return type for the useWatchAsset hook. ```ts import { type UseWatchAssetReturnType } from 'wagmi' ``` -------------------------------- ### Refetch On Mount Source: https://wagmi.sh/react/api/hooks/useReadContracts Controls whether queries refetch when a component mounts. ```APIDOC ## refetchOnMount ### Description Controls whether queries refetch on mount. Defaults to `true`. If set to `true`, the query will refetch on mount if the data is stale. If set to `false`, the query will not refetch on mount. If set to `'always'`, the query will always refetch on mount. If set to a function, the function will be executed with the query to compute the value. ### Type `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` ### Default `true` ``` -------------------------------- ### Configure custom config Source: https://wagmi.sh/react/api/hooks/useBlockNumber Provide a specific Wagmi configuration instance instead of using the nearest provider. ```tsx import { useBlockNumber } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useBlockNumber({ config, // [!code focus] }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Integrate Wallet Components in app.tsx Source: https://wagmi.sh/react/guides/connect-wallet Wraps the application with WagmiProvider and QueryClientProvider, and conditionally renders the connection or wallet options based on the connection state. ```tsx import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { WagmiProvider, useConnection } from 'wagmi' import { config } from './config' import { Connection } from './connection' // [!code ++] import { WalletOptions } from './wallet-options' // [!code ++] const queryClient = new QueryClient() function ConnectWallet() { // [!code ++] const { isConnected } = useConnection() // [!code ++] if (isConnected) return // [!code ++] return // [!code ++] } // [!code ++] function App() { return ( // [!code ++] ) } ``` -------------------------------- ### Import useShowCallsStatus Hook Source: https://wagmi.sh/react/api/hooks/useShowCallsStatus Import the useShowCallsStatus hook from the wagmi library. ```typescript import { useShowCallsStatus } from 'wagmi' ``` -------------------------------- ### Import useEnsAddress Source: https://wagmi.sh/react/api/hooks/useEnsAddress Import the hook from the wagmi package. ```ts import { useEnsAddress } from 'wagmi' ``` -------------------------------- ### Mutation Configuration Options Source: https://wagmi.sh/react/api/hooks/useShowCallsStatus Configuration parameters available for mutation hooks. ```APIDOC ## Mutation Configuration Options ### Parameters - **onSettled** (function) - Optional - Callback fired when the mutation is either successfully fetched or encounters an error. - **queryClient** (QueryClient) - Optional - Custom QueryClient instance. - **retry** (boolean | number | function) - Optional - Defines retry behavior for failed mutations. Defaults to 0. - **retryDelay** (number | function) - Optional - Defines the delay in milliseconds before the next retry attempt. ``` -------------------------------- ### Basic useConnect Usage Source: https://wagmi.sh/react/api/hooks/useConnect Use the useConnect hook to connect to a wallet using the injected connector. This is a common pattern for initiating wallet connections in a React application. ```tsx import { useConnect } from 'wagmi' import { injected } from 'wagmi/connectors' function App() { const connect = useConnect() return ( ) } ``` -------------------------------- ### Query Options Configuration Source: https://wagmi.sh/react/api/hooks/useVerifyMessage Configuration options for customizing query behavior in Wagmi React hooks. ```APIDOC ## Query Options ### Description Configuration options for customizing query behavior in Wagmi React hooks. ### Parameters #### Query Options - **placeholderData** ({{TData}} | ((previousValue: {{TData}} | undefined; previousQuery: Query | undefined) => {{TData}}) | undefined) - Optional - If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `pending` state. `placeholderData` is **not persisted** to the cache. If you provide a function for `placeholderData`, as a first argument you will receive previously watched query data if available, and the second argument will be the complete previousQuery instance. - **queryClient** (QueryClient | undefined) - Optional - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used. - **refetchInterval** (number | false | ((data: {{TData}} | undefined, query: Query) => number | false | undefined)) - Optional - If set to a number, all queries will continuously refetch at this frequency in milliseconds. If set to a function, the function will be executed with the latest data and query to compute a frequency. - **refetchIntervalInBackground** (boolean | undefined) - Optional - If set to `true`, queries that are set to continuously refetch with a `refetchInterval` will continue to refetch while their tab/window is in the background. - **refetchOnMount** (boolean | 'always' | ((query: Query) => boolean | 'always')) - Optional - Defaults to `true`. If set to `true`, the query will refetch on mount if the data is stale. If set to `false`, the query will not refetch on mount. If set to `'always'`, the query will always refetch on mount. If set to a function, the function will be executed with the query to compute the value. - **refetchOnReconnect** (boolean | 'always' | ((query: Query) => boolean | 'always')) - Optional - Defaults to `true`. If set to `true`, the query will refetch on reconnect if the data is stale. If set to `false`, the query will not refetch on reconnect. If set to `'always'`, the query will always refetch on reconnect. If set to a function, the function will be executed with the query to compute the value. - **refetchOnWindowFocus** (boolean | 'always' | ((query: Query) => boolean | 'always')) - Optional - Defaults to `true`. If set to `true`, the query will refetch on window focus if the data is stale. If set to `false`, the query will not refetch on window focus. If set to `'always'`, the query will always refetch on window focus. If set to a function, the function will be executed with the query to compute the value. - **retry** (boolean | number | ((failureCount: number, error: {{TError}}) => boolean)) - Optional - If `false`, failed queries will not retry by default. If `true`, failed queries will retry infinitely. If set to a `number`, e.g. `3`, failed queries will retry until the failed query count meets that number. Defaults to `3` on the client and `0` on the server. - **retryDelay** (number | ((retryAttempt: number, error: {{TError}}) => number)) - Optional - This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds. A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff. A function like `attempt => attempt * 1000` applies linear backoff. - **retryOnMount** (boolean | undefined) - Optional - If set to `false`, the query will not be retried on mount if it contains an error. Defaults to `true`. - **select** ((data: {{TData}}) => unknown) | undefined - Optional - This option can be used to transform or select a part of the data returned by the query function. It affects the returned `data` value, but does not affect what gets stored in the query cache. - **staleTime** (number | Infinity | undefined) - Optional - Defaults to `0`. The time in milliseconds after data is considered stale. This value only applies to the hook it is defined on. If set to `Infinity`, the data will never be considered stale. - **structuralSharing** (boolean | (((oldData: {{TData}} | undefined, newData: {{TData}}) => {{TData}}))) | undefined - Optional - Defaults to `true`. If set to `false`, structural sharing between query results will be disabled. If set to a function, the old and new data values will be passed through this function, which should combine them into resolved data for the query. This way, you can retain references from the old data to improve performance even when that data contains non-serializable values. ``` -------------------------------- ### Configure WalletConnect with isNewChainsStale Source: https://wagmi.sh/react/api/connectors/walletConnect Control how new chains are handled when added to an existing WalletConnect configuration. Defaults to true. ```typescript import { walletConnect } from '{{connectorsPackageName}}' const connector = walletConnect({ isNewChainsStale: true, // [!code focus] projectId: '3fcc6bba6f1de962d911bb5b5c3dba68', }) ``` -------------------------------- ### Import WagmiProvider Source: https://wagmi.sh/react/api/WagmiProvider Import the WagmiProvider component from the 'wagmi' library. ```typescript import { WagmiProvider } from 'wagmi' ``` -------------------------------- ### Configure scopeKey and Wagmi Client Source: https://wagmi.sh/react/api/hooks/useBalance Use scopeKey to share cache between hooks with identical context, and initialize the Wagmi config. ```tsx // {"path":"/vercel/path0/site/react/api/hooks/useBalance.md","from":2992,"to":3179} import { useBalance } from 'wagmi' function App() { const result = useBalance({ address: '0x4557B18E779944BFE9d78A672452331C186a9f48', scopeKey: 'foo', // [!code focus] }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Specify Contract Arguments Source: https://wagmi.sh/react/api/hooks/useInfiniteReadContracts Demonstrates how to pass arguments to the contract function. The `args` should match the expected parameters of the specified `functionName` and be derived from the `pageParam` for pagination. ```tsx import { useInfiniteReadContracts } from 'wagmi' import { abi } from './abi' function App() { const result = useInfiniteReadContracts({ cacheKey: 'mlootAttributes', contracts(pageParam) { return [ // ... { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi, functionName: 'getChest', args: [pageParam] // [!code hl] }, // ... ] } query: { initialPageParam: 0, getNextPageParam: (_lastPage, _allPages, lastPageParam) => { return lastPageParam + 1 } } }) } ``` -------------------------------- ### Provide Config for useSimulateContract Source: https://wagmi.sh/react/api/hooks/useSimulateContract Pass a `config` object to `useSimulateContract` to override the default configuration. The `config` object should be imported from a separate configuration file. ```tsx import { useSimulateContract } from 'wagmi' import { abi } from './abi' import { config } from './config' // [!code focus] function App() { const result = useSimulateContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], config, // [!code focus] }) } ``` -------------------------------- ### Infinite Query Methods Source: https://wagmi.sh/react/api/hooks/useWaitForTransactionReceipt Methods for managing paginated data fetching. ```APIDOC ## fetchNextPage ### Description Allows you to fetch the next "page" of results. ### Parameters - **options** (FetchNextPageOptions) - Optional - Configuration for the fetch operation. ## fetchPreviousPage ### Description Allows you to fetch the previous "page" of results. ### Parameters - **options** (FetchPreviousPageOptions) - Optional - Configuration for the fetch operation. ``` -------------------------------- ### useBlock Hook API Source: https://wagmi.sh/react/api/hooks/useBlock This section details the parameters available for the useBlock hook. ```APIDOC ## useBlock Hook Hook for fetching information about a block at a block number, hash or tag. ### Parameters #### blockHash `` `0x${string}` `` Information at a given block hash. #### blockNumber `bigint` Information at a given block number. #### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'` Information at a given block tag. Defaults to `'latest'`. #### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. #### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ``` -------------------------------- ### Mutation Status and Variables Source: https://wagmi.sh/react/api/hooks/useSendCalls Explains the possible states of a mutation and the data associated with it. ```APIDOC ## Mutation States and Variables ### status `'idle' | 'pending' | 'error' | 'success'` * `'idle'` initial status prior to the mutation function executing. * `'pending'` if the mutation is currently executing. * `'error'` if the last mutation attempt resulted in an error. * `'success'` if the last mutation attempt was successful. ### submittedAt `number` * The timestamp for when the mutation was submitted. * Defaults to `0`. ### variables `{{TVariables}} | undefined` * The variables object passed to [`mutate`](#mutate). * Defaults to `undefined`. ``` -------------------------------- ### Query Options Source: https://wagmi.sh/react/api/hooks/useGasPrice Configuration options for customizing query behavior. ```APIDOC ## Query Options This section details various options that can be configured for queries. ### initialDataUpdatedAt `number | (() => number | undefined) | undefined` If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. ### initialPageParam `{{TPageParam}}` The initial page parameter to be passed to the query function. ### getPreviousPageParam `((firstPage: {{TData}}, allPages: {{TData}}[], firstPageParam: {{TPageParam}}, allPageParams: {{TPageParam}}[]) => {{TPageParam}} | undefined | null)` This function can be set to automatically get the previous cursor for infinite queries. The result will also be used to determine the value of `hasPreviousPage`. ### getNextPageParam `(lastPage: {{TData}}, allPages: {{TData}}[], lastPageParam: {{TPageParam}}, allPageParams: {{TPageParam}}[]) => {{TPageParam}} | undefined | null` This function can be set to automatically get the previous cursor for infinite queries. The result will also be used to determine the value of `hasPreviousPage`. ### meta `Record | undefined` If set, stores additional information on the query cache entry that can be used as needed. It will be accessible wherever the `query` is available, and is also part of the `QueryFunctionContext` provided to the `queryFn`. ### networkMode `'online' | 'always' | 'offlineFirst' | undefined` * Defaults to `'online'` * See [Network Mode](https://tanstack.com/query/v5/docs/react/guides/network-mode) for more information. ### notifyOnChangeProps `string[] | 'all' | (() => string[] | 'all') | undefined` * If set, the component will only re-render if any of the listed properties change. * If set to `['data', 'error']` for example, the component will only re-render when the `data` or `error` properties change. * If set to `'all'`, the component will opt-out of smart tracking and re-render whenever a query is updated. * If set to a function, the function will be executed to compute the list of properties. * By default, access to properties will be tracked, and the component will only re-render when one of the tracked properties change. ### placeholderData `{{TData}} | ((previousValue: {{TData}} | undefined; previousQuery: Query | undefined) => {{TData}}) | undefined` * If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `pending` state. * `placeholderData` is **not persisted** to the cache. * If you provide a function for `placeholderData`, as a first argument you will receive previously watched query data if available, and the second argument will be the complete previousQuery instance. ### queryClient `QueryClient | undefined` Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used. ### refetchInterval `number | false | ((data: {{TData}} | undefined, query: Query) => number | false | undefined) | undefined` * If set to a number, all queries will continuously refetch at this frequency in milliseconds. * If set to a function, the function will be executed with the latest data and query to compute a frequency. ### refetchIntervalInBackground `boolean | undefined` If set to `true`, queries that are set to continuously refetch with a `refetchInterval` will continue to refetch while their tab/window is in the background. ### refetchOnMount `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` * Defaults to `true`. * If set to `true`, the query will refetch on mount if the data is stale. * If set to `false`, the query will not refetch on mount. * If set to `'always'`, the query will always refetch on mount. * If set to a function, the function will be executed with the query to compute the value. ### refetchOnReconnect `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` * Defaults to `true`. * If set to `true`, the query will refetch on reconnect if the data is stale. * If set to `false`, the query will not refetch on reconnect. * If set to `'always'`, the query will always refetch on reconnect. * If set to a function, the function will be executed with the query to compute the value. ### refetchOnWindowFocus `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` * Defaults to `true`. * If set to `true`, the query will refetch on window focus if the data is stale. * If set to `false`, the query will not refetch on window focus. * If set to `'always'`, the query will always refetch on window focus. * If set to a function, the function will be executed with the query to compute the value. ### retry `boolean | number | ((failureCount: number, error: {{TError}}) => boolean) | undefined` * If `false`, failed queries will not retry by default. * If `true`, failed queries will retry infinitely. * If set to a `number`, e.g. `3`, failed queries will retry until the failed query count meets that number. * Defaults to `3` on the client and `0` on the server. ``` -------------------------------- ### Type Inference and Imports Source: https://wagmi.sh/react/api/hooks/useSimulateContract Information on type inference and necessary imports for Wagmi. ```APIDOC ## Type Inference With [`abi`](#abi) setup correctly, TypeScript will infer the correct types for [`functionName`](#functionname), [`args`](#args), and [`value`](#value). See the Wagmi [TypeScript docs](/react/typescript) for more information. ## TanStack Query Imports ```ts-vue import { type {{typeName}}Data, type {{typeName}}Options, type {{typeName}}QueryFnData, type {{typeName}}QueryKey, {{actionName}}QueryKey, {{actionName}}QueryOptions, } from '{{packageName}}/query' ``` ``` -------------------------------- ### Configure gasPrice for useCall Source: https://wagmi.sh/react/api/hooks/useCall Sets the price per gas for legacy transactions. ```tsx // {"path":"/vercel/path0/site/react/api/hooks/useCall.md","from":3341,"to":3642} import { useCall } from 'wagmi' function App() { const result = useCall({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', gasPrice: parseGwei('20'), // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Import UseClientParameters Source: https://wagmi.sh/react/api/hooks/useClient Import the type definition for useClient parameters. ```ts import { type UseClientParameters } from 'wagmi' ``` -------------------------------- ### Import TanStack Query Types Source: https://wagmi.sh/react/api/hooks/useConnect Import necessary types for mutations when using TanStack Query with Wagmi. Ensure the package name is correctly specified. ```ts-vue import { type {{typeName}}Data, type {{typeName}}Variables, type {{typeName}}Mutate, type {{typeName}}MutateAsync, {{actionName}}MutationOptions, } from '{{packageName}}/query' ``` -------------------------------- ### Import useEnsAvatar with custom config Source: https://wagmi.sh/react/api/hooks/useEnsAvatar Import and use the `useEnsAvatar` hook with a custom `config` object. Ensure the `config` is properly created using `createConfig`. ```tsx import { useEnsAvatar } from 'wagmi' import { normalize } from 'viem/ens' import { config } from './config' // [!code focus] function App() { const result = useEnsAvatar({ config, // [!code focus] name: normalize('wevm.eth'), }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Set appName Source: https://wagmi.sh/react/api/connectors/baseAccount Configure the application name for the connector. ```ts import { baseAccount } from '{{connectorsPackageName}}' const connector = baseAccount({ appName: 'My Wagmi App', // [!code focus] }) ``` -------------------------------- ### Query Options Source: https://wagmi.sh/react/api/hooks/useGasPrice Configuration options for customizing query behavior in wagmi React hooks. ```APIDOC ## Query Options ### retryDelay `number | ((retryAttempt: number, error: {{TError}}) => number) | undefined` * This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds. * A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff. * A function like `attempt => attempt * 1000` applies linear backoff. ### retryOnMount `boolean | undefined` If set to `false`, the query will not be retried on mount if it contains an error. Defaults to `true`. ### select `((data: {{TData}}) => unknown) | undefined` This option can be used to transform or select a part of the data returned by the query function. It affects the returned `data` value, but does not affect what gets stored in the query cache. ### staleTime `number | Infinity | undefined` * Defaults to `0` * The time in milliseconds after data is considered stale. This value only applies to the hook it is defined on. * If set to `Infinity`, the data will never be considered stale ### structuralSharing `boolean | (((oldData: {{TData}} | undefined, newData: {{TData}}) => {{TData}})) | undefined` * Defaults to `true` * If set to `false`, structural sharing between query results will be disabled. * If set to a function, the old and new data values will be passed through this function, which should combine them into resolved data for the query. This way, you can retain references from the old data to improve performance even when that data contains non-serializable values. ``` -------------------------------- ### Import UseChainsParameters Source: https://wagmi.sh/react/api/hooks/useChains Import the type definition for the hook parameters. ```ts import { type UseChainsParameters } from 'wagmi' ``` -------------------------------- ### Import UseEstimateGasParameters Source: https://wagmi.sh/react/api/hooks/useEstimateGas Import the type definition for the hook parameters. ```ts import { type UseEstimateGasParameters } from 'wagmi' ``` -------------------------------- ### Import UsePrepareTransactionRequestReturnType Source: https://wagmi.sh/react/api/hooks/usePrepareTransactionRequest Import the return type definition for the usePrepareTransactionRequest hook. ```typescript import { type UsePrepareTransactionRequestReturnType } from 'wagmi' ``` -------------------------------- ### UseBytecode with config parameter Source: https://wagmi.sh/react/api/hooks/useBytecode Provide a custom Wagmi config instead of using the nearest provider. ```tsx import { useBytecode } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useBytecode({ config, // [!code focus] address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Configure useWatchAsset Source: https://wagmi.sh/react/api/hooks/useWatchAsset Provide a custom Wagmi configuration to the hook. ```tsx import { useWatchAsset } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useWatchAsset({ config, // [!code focus] }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Import useCall Hook Source: https://wagmi.sh/react/api/hooks/useCall Import the `useCall` hook from the wagmi library. ```typescript import { useCall } from 'wagmi' ``` -------------------------------- ### useClient Hook API Source: https://wagmi.sh/react/api/hooks/useClient The useClient hook retrieves the Viem Client instance. It can optionally accept parameters to specify the chain ID or a custom configuration. ```APIDOC ## useClient ### Description Hook for getting Viem [`Client`](https://viem.sh/docs/clients/custom) instance. ### Method React Hook ### Endpoint N/A (React Hook) ### Parameters #### Query Parameters - **chainId** (number | undefined) - Optional - ID of chain to use when getting Viem Client. - **config** (Config | undefined) - Optional - [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ### Request Example ```tsx import { useClient } from 'wagmi' function App() { const client = useClient() const clientWithChainId = useClient({ chainId: 1 }) const clientWithConfig = useClient({ config: myConfig }) } ``` ### Response #### Success Response (200) - **client** (Client | undefined) - Viem [`Client`](https://viem.sh/docs/clients/custom) instance. #### Response Example ```json { "client": { /* Viem Client Object */ } } ``` ``` -------------------------------- ### Set appLogoUrl parameter Source: https://wagmi.sh/react/api/connectors/coinbaseWallet Define the application logo URL displayed during wallet connection. ```ts import { coinbaseWallet } from '{{connectorsPackageName}}' const connector = coinbaseWallet({ appName: 'My Wagmi App', appLogoUrl: 'https://example.com/myLogoUrl.png', // [!code focus] }) ``` -------------------------------- ### Import useChainId Hook Source: https://wagmi.sh/react/api/hooks/useChainId Import the useChainId hook from the wagmi library. ```typescript import { useChainId } from 'wagmi' ``` -------------------------------- ### Configure useBytecode with scopeKey Source: https://wagmi.sh/react/api/hooks/useBytecode Use `scopeKey` to scope the cache for hooks. Hooks with identical context will share the same cache. ```tsx import { useBytecode } from 'wagmi' import { config } from './config' function App() { const result = useBytecode({ scopeKey: 'foo' // [!code focus] address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Import UseSignTransactionParameters Source: https://wagmi.sh/react/api/hooks/useSignTransaction Import the type definition for hook parameters. ```ts import { type UseSignTransactionParameters } from 'wagmi' ``` -------------------------------- ### Import Parameters Source: https://wagmi.sh/react/api/hooks/useEnsAddress Import the type definition for hook parameters. ```ts import { type UseEnsAddressParameters } from 'wagmi' ``` -------------------------------- ### Import UseBlobBaseFeeReturnType Source: https://wagmi.sh/react/api/hooks/useBlobBaseFee Import the return type definition for the useBlobBaseFee hook. ```typescript import { type UseBlobBaseFeeReturnType } from 'wagmi' ``` -------------------------------- ### Import useBlockTransactionCount Hook Source: https://wagmi.sh/react/api/hooks/useBlockTransactionCount Import the useBlockTransactionCount hook from the wagmi library. ```typescript import { useBlockTransactionCount } from 'wagmi' ``` -------------------------------- ### Import useConnect Hook Source: https://wagmi.sh/react/api/hooks/useConnect Import the useConnect hook from the wagmi library. ```typescript import { useConnect } from 'wagmi' ``` -------------------------------- ### Import parameter types Source: https://wagmi.sh/react/api/hooks/usePrepareTransactionRequest Import the parameter type definition for the hook. ```ts import { type UsePrepareTransactionRequestParameters } from 'wagmi' ``` -------------------------------- ### getStorageAt Action Source: https://wagmi.sh/react/api/hooks/useStorageAt Information about the `getStorageAt` action. ```APIDOC ## Action: getStorageAt ### Description Retrieves storage data at a specified location. ### Endpoint `/core/api/actions/getStorageAt` ``` -------------------------------- ### Set appLogoUrl Source: https://wagmi.sh/react/api/connectors/baseAccount Configure the application logo URL for the connector. ```ts import { baseAccount } from '{{connectorsPackageName}}' const connector = baseAccount({ appName: 'My Wagmi App', appLogoUrl: 'https://example.com/myLogoUrl.png', // [!code focus] }) ``` -------------------------------- ### Import useConnections Hook Source: https://wagmi.sh/react/api/hooks/useConnections Import the useConnections hook from the wagmi library. ```typescript import { useConnections } from 'wagmi' ``` -------------------------------- ### Fetch Capabilities for a Specific Account Source: https://wagmi.sh/react/api/hooks/useCapabilities Fetches capabilities for a specific account address. Ensure the wagmi config is set up correctly. ```typescript import { useCapabilities } from '@wagmi/core' import { config } from './config' const status = await useCapabilities({ account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', }) ``` ```typescript import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Import useSendTransaction Source: https://wagmi.sh/react/api/hooks/useSendTransaction Import the hook from the wagmi package. ```ts import { useSendTransaction } from 'wagmi' ``` -------------------------------- ### useSimulateContract - account parameter Source: https://wagmi.sh/react/api/hooks/useSimulateContract Specifies the account to be used when calling the contract. This account must be found on the connector. ```APIDOC ## POST /simulateContract ### Description Simulates a contract interaction using the provided parameters. ### Method POST ### Endpoint /simulateContract ### Parameters #### Request Body - **account** (Account | undefined) - The account to use when calling the contract (msg.sender). Throws if account is not found on connector. - **address** (Address | undefined) - The contract's address. - **functionName** (string) - The name of the function to call on the contract. - **args** (unknown[]) - Arguments to pass when calling the contract. Inferred from `abi` and `functionName`. - **abi** (Abi | undefined) - The contract's ABI. - **blockNumber** (bigint | undefined) - Block number to call contract at. - **blockTag** ('latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined) - Block tag to call contract at. ### Request Example ```json { "account": "0xd2135CfB216b74109775236E36d4b433F1DF507B", "address": "0x6b175474e89094c44da98b954eedeac495271d0f", "functionName": "transferFrom", "args": [ "0xd2135CfB216b74109775236E36d4b433F1DF507B", "0xA0Cf798816D4b9b9866b5330EEa46a18382f251e", 123n ] } ``` ### Response #### Success Response (200) - **result** (SimulateContractResult) - The result of the contract simulation. #### Response Example ```json { "result": { "data": "0x...", "request": { "from": "0xd2135CfB216b74109775236E36d4b433F1DF507B", "to": "0x6b175474e89094c44da98b954eedeac495271d0f", "value": 0n, "data": "0x..." } } } ``` ``` -------------------------------- ### Use Custom Config with useDisconnect Source: https://wagmi.sh/react/api/hooks/useDisconnect Pass a custom configuration object to the hook instead of relying on the nearest WagmiProvider context. ```tsx import { useDisconnect } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useDisconnect({ config, // [!code focus] }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Initialize Wagmi State from Cookie in Next.js App Router Layout Source: https://wagmi.sh/react/guides/ssr In your `app/layout.tsx` Server Component, extract the cookie from headers and use `cookieToInitialState` to initialize Wagmi's state. This state is then passed to the `WagmiProvider` in `app/providers.tsx`. ```typescript import { type ReactNode } from 'react' import { headers } from 'next/headers' import { cookieToInitialState } from 'wagmi' import { getConfig } from './config' import { Providers } from './providers' export default async function Layout({ children }: { children: ReactNode }) { const initialState = cookieToInitialState( getConfig(), (await headers()).get('cookie') ) return ( {children} ) } ``` -------------------------------- ### Import Parameters Type Source: https://wagmi.sh/react/api/hooks/usePublicClient Import the type definition for hook parameters. ```ts import { type UsePublicClientParameters } from 'wagmi' ``` -------------------------------- ### Query Fetching Methods Source: https://wagmi.sh/react/api/hooks/useVerifyMessage Functions for controlling the fetching of data, including fetching next/previous pages and manual refetching. ```APIDOC ## Query Fetching Methods ### fetchNextPage `(options?: FetchNextPageOptions) => Promise>` This function allows you to fetch the next "page" of results. ### fetchPreviousPage `(options?: FetchPreviousPageOptions) => Promise>` This function allows you to fetch the previous "page" of results. ### refetch `(options: { cancelRefetch?: boolean | undefined; throwOnError?: boolean | undefined }) => Promise>` * A function to manually refetch the query. * `throwOnError` * When set to `true`, an error will be thrown if the query fails. * When set to `false`, an error will be logged if the query fails. * `cancelRefetch` * When set to `true`, a currently running request will be cancelled before a new request is made. * When set to `false`, no refetch will be made if there is already a request running. * Defaults to `true` ``` -------------------------------- ### useReadContract - args Source: https://wagmi.sh/react/api/hooks/useReadContract Arguments to pass when calling the contract. Inferred from `abi` and `functionName`. ```APIDOC ## useReadContract args ### Description Arguments to pass when calling the contract. Inferred from [`abi`](#abi) and [`functionName`](#functionname). ### Parameters #### Request Body - **args** (unknown[]) - Required - Arguments to pass when calling the contract. ### Request Example ```json { "args": [ "0x6b175474e89094c44da98b954eedeac495271d0f" ] } ``` ### Response #### Success Response (200) - **result** (unknown) - The result of the contract call. #### Response Example ```json { "result": "0x..." } ``` ``` -------------------------------- ### Prefetching Queries in Event Handlers Source: https://wagmi.sh/react/guides/tanstack-query Seed the cache by prefetching data during user interactions like hover or focus events. ```tsx import { Link } from 'next/link' import { getBlockQueryOptions } from 'wagmi' function App() { const config = useConfig() const chainId = useChainId() // 1. Set up a function to prefetch the block data. // [!code hl] const prefetch = () => // [!code hl] queryClient.prefetchQuery(getBlockQueryOptions(config, { chainId })) // [!code hl] return ( Block details ) } ``` -------------------------------- ### Use scopeKey with useBlockTransactionCount Hook Source: https://wagmi.sh/react/api/hooks/useBlockTransactionCount Demonstrates how to use the `scopeKey` option to scope the cache for the `useBlockTransactionCount` hook. Hooks with identical context will share the same cache. ```tsx // {"path":"/vercel/path0/site/react/api/hooks/useBlockTransactionCount.md","from":2805,"to":3012} import { useBlockTransactionCount } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useBlockTransactionCount({ scopeKey: 'foo', // [!code focus] }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Import useWatchBlockNumber Hook Source: https://wagmi.sh/react/api/hooks/useWatchBlockNumber Import the useWatchBlockNumber hook from the wagmi library. ```typescript import { useWatchBlockNumber } from 'wagmi' ``` -------------------------------- ### Set appName parameter Source: https://wagmi.sh/react/api/connectors/coinbaseWallet Define the application name displayed during wallet connection. ```ts import { coinbaseWallet } from '{{connectorsPackageName}}' const connector = coinbaseWallet({ appName: 'My Wagmi App', // [!code focus] }) ``` -------------------------------- ### useCapabilities Hook Source: https://wagmi.sh/react/api/hooks/useCapabilities Hook to extract capabilities (grouped by chain ID) that a connected wallet supports. ```APIDOC ## useCapabilities ### Description Hook to extract capabilities (grouped by chain ID) that a connected wallet supports (e.g. paymasters, session keys, etc). ### Parameters - **account** (Account | Address | undefined) - Optional - Fetch capabilities for the provided account. - **config** (Config | undefined) - Optional - Config to use instead of retrieving from the nearest WagmiProvider. - **connector** (Connector | undefined) - Optional - Connector to get call statuses with. - **scopeKey** (string | undefined) - Optional - Scopes the cache to a given context. - **query** (Object) - Optional - TanStack Query parameters for controlling cache and fetch behavior. ### Request Example ```tsx import { useCapabilities } from 'wagmi' function App() { const result = useCapabilities({ account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', scopeKey: 'foo' }) } ``` ``` -------------------------------- ### Configure scopeKey for useProof Source: https://wagmi.sh/react/api/hooks/useProof Scopes the cache to a specific context, allowing hooks with identical keys to share cache data. ```tsx import { useProof } from 'wagmi' import { config } from './config' function App() { const result = useProof({ scopeKey: 'foo' // [!code focus] address: '0x4200000000000000000000000000000000000016', storageKeys: [ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Configure Custom Config Source: https://wagmi.sh/react/api/hooks/useWalletClient Provide a specific Wagmi config instance. ```tsx import { useWalletClient } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useWalletClient({ config, // [!code focus] }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Import SwitchChainNotSupportedError Source: https://wagmi.sh/react/api/errors Import the error for when switching chains is not supported by connectors. ```ts-vue import { SwitchChainNotSupportedError } from '{{packageName}}' ``` -------------------------------- ### useConnect Hook Source: https://wagmi.sh/react/api/hooks/useConnect The `useConnect` hook provides functionality to connect to a wallet and access information about available connectors. ```APIDOC ## useConnect Hook ### Description Provides functionality to connect to a wallet and access information about available connectors. ### Return Type ```ts import { type UseConnectReturnType } from 'wagmi' ``` ### connectors `readonly Connector[]` Globally configured connectors via [`createConfig`](/react/api/createConfig#connectors). Useful for rendering a list of available connectors. ### Example Usage ```tsx import { useConnect } from 'wagmi' function App() { const connect = useConnect() return (
{connect.connectors.map((connector) => ( ))}
) } ``` ### Configuration Example ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` ``` -------------------------------- ### Import useEstimateFeesPerGas Hook Source: https://wagmi.sh/react/api/hooks/useEstimateFeesPerGas Import the useEstimateFeesPerGas hook from the wagmi library. ```typescript import { useEstimateFeesPerGas } from 'wagmi' ``` -------------------------------- ### Network and Re-fetching Configuration Source: https://wagmi.sh/react/api/hooks/useEnsAvatar Options for controlling network behavior and automatic re-fetching. ```APIDOC ## networkMode `'online' | 'always' | 'offlineFirst' | undefined` * Defaults to `'online'` * see [Network Mode](https://tanstack.com/query/v5/docs/react/guides/network-mode) for more information. ## notifyOnChangeProps `string[] | 'all' | (() => string[] | 'all') | undefined` * If set, the component will only re-render if any of the listed properties change. * If set to `['data', 'error']` for example, the component will only re-render when the `data` or `error` properties change. * If set to `'all'`, the component will opt-out of smart tracking and re-render whenever a query is updated. * If set to a function, the function will be executed to compute the list of properties. * By default, access to properties will be tracked, and the component will only re-render when one of the tracked properties change. ## placeholderData `{{TData}} | ((previousValue: {{TData}} | undefined; previousQuery: Query | undefined) => {{TData}}) | undefined` * If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `pending` state. * `placeholderData` is **not persisted** to the cache * If you provide a function for `placeholderData`, as a first argument you will receive previously watched query data if available, and the second argument will be the complete previousQuery instance. ## queryClient `QueryClient | undefined` Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used. ## refetchInterval `number | false | ((data: {{TData}} | undefined, query: Query) => number | false | undefined) | undefined` * If set to a number, all queries will continuously refetch at this frequency in milliseconds * If set to a function, the function will be executed with the latest data and query to compute a frequency ## refetchIntervalInBackground `boolean | undefined` If set to `true`, queries that are set to continuously refetch with a `refetchInterval` will continue to refetch while their tab/window is in the background ## refetchOnMount `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` * Defaults to `true` * If set to `true`, the query will refetch on mount if the data is stale. * If set to `false`, the query will not refetch on mount. * If set to `'always'`, the query will always refetch on mount. * If set to a function, the function will be executed with the query to compute the value ``` -------------------------------- ### Provide custom configuration Source: https://wagmi.sh/react/api/hooks/useReadContract Override the default WagmiProvider configuration by passing a specific config object. ```tsx // {"path":"/vercel/path0/site/react/api/hooks/useReadContract.md","from":5181,"to":5490} import { useReadContract } from 'wagmi' import { abi } from './abi' import { config } from './config' // [!code focus] function App() { const result = useReadContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'totalSupply', config, // [!code focus] }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### usePrepareTransactionRequest Hook Source: https://wagmi.sh/react/api/hooks/usePrepareTransactionRequest The `usePrepareTransactionRequest` hook is used to prepare a transaction request. It accepts various parameters to customize the transaction. ```APIDOC ## POST /api/prepareTransactionRequest ### Description Prepares a transaction request for sending. ### Method POST ### Endpoint /api/prepareTransactionRequest ### Parameters #### Request Body - **account** (string) - Required - The account to send the transaction from. - **to** (string) - Required - The recipient address of the transaction. - **value** (bigint) - Optional - The value in wei to send with the transaction. - **parameters** (("fees" | "gas" | "nonce" | "type")[]) - Optional - Specific parameters to prepare for the transaction. - **config** (Config) - Optional - The wagmi configuration to use. - **scopeKey** (string) - Optional - Scopes the cache to a given context. ### Query Parameters #### enabled - **enabled** (boolean) - Optional - Set to `false` to disable the query from automatically running. #### gcTime - **gcTime** (number | Infinity) - Optional - The time in milliseconds that unused/inactive cache data remains in memory. Defaults to 5 minutes or Infinity during SSR. ``` -------------------------------- ### Configure Wagmi with coinbaseWallet Source: https://wagmi.sh/react/api/connectors/coinbaseWallet Integrate the connector into the Wagmi configuration object. ```ts import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' import { coinbaseWallet } from '{{connectorsPackageName}}' // [!code hl] export const config = createConfig({ chains: [mainnet, sepolia], connectors: [coinbaseWallet()], // [!code hl] transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### queryClient Source: https://wagmi.sh/react/api/hooks/useEnsResolver Allows specifying a custom QueryClient. ```APIDOC ## queryClient ### Description Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used. ### Type `QueryClient | undefined` ``` -------------------------------- ### TanStack Query Type Imports Source: https://wagmi.sh/react/api/hooks/useWaitForCallsStatus Standard pattern for importing TanStack Query types and keys for Wagmi actions. ```APIDOC ## TanStack Query Imports ### Description Use this pattern to import necessary types and query options for Wagmi actions. ### Code Example ```ts import { type {{typeName}}Data, type {{typeName}}Options, type {{typeName}}QueryFnData, type {{typeName}}QueryKey, {{actionName}}QueryKey, {{actionName}}QueryOptions, } from '{{packageName}}/query' ``` ``` -------------------------------- ### TanStack Query Parameters for useBlock Source: https://wagmi.sh/react/api/hooks/useBlock TanStack Query parameters that can be used with the useBlock hook. ```APIDOC ## TanStack Query Parameters for useBlock ### Description TanStack Query parameters that can be used with the `useBlock` hook. See the [TanStack Query query docs](https://tanstack.com/query/v5/docs/react/reference/useQuery) for more info. :::info Wagmi does not support passing all TanStack Query parameters TanStack Query parameters, like `queryFn` and `queryKey`, are used internally to make Wagmi work and you cannot override them. Check out the [source](https://github.com/wevm/wagmi/blob/main/packages/react/src/types/properties.ts#L27) to see what parameters are not supported. All parameters listed below are supported. ::: ### Parameters #### Query Parameters - **enabled** (boolean | undefined) - Optional - Set this to `false` to disable this query from automatically running. Can be used for [Dependent Queries](https://tanstack.com/query/v5/docs/react/guides/dependent-queries). - **gcTime** (number | Infinity | undefined) - Optional - Defaults to `5 * 60 * 1000` (5 minutes) or `Infinity` during SSR. The time in milliseconds that unused/inactive cache data remains in memory. When a query's cache becomes unused or inactive, that cache data will be garbage collected after this duration. When different garbage collection times are specified, the longest one will be used. If set to `Infinity`, will disable garbage collection. - **initialData** (TData | (() => TData) | undefined) - Optional - If set, this value will be used as the initial data for the query cache (as long as the query hasn't been created or cached yet). If set to a function, the function will be called **once** during the shared/root query initialization, and be expected to synchronously return the initialData. Initial data is considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the cache. - **initialDataUpdatedAt** (number | (() => number | undefined)) - Optional - If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. - **initialPageParam** (TPageParam) - The initial page parameter to be passed to the query function. - **getPreviousPageParam** ((firstPage: TData, allPages: TData[], firstPageParam: TPageParam, allPageParams: TPageParam[]) => TPageParam | undefined | null) - This function can be set to automatically get the previous cursor for infinite queries. The result will also be used to determine the value of `hasPreviousPage`. ``` -------------------------------- ### Configure chainId for useProof Source: https://wagmi.sh/react/api/hooks/useProof Specifies the chain ID to retrieve the proof for. ```tsx import { useProof } from 'wagmi' import { optimism } from 'wagmi/chains' function App() { const result = useProof({ chainId: optimism.id, // [!code focus] address: '0x4200000000000000000000000000000000000016', storageKeys: [ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Fetch Next Page in TanStack Query Source: https://wagmi.sh/react/api/hooks/useWaitForTransactionReceipt Use `fetchNextPage` to retrieve the subsequent set of results in an infinite query. Ensure you have defined `getNextPageParam` in your query options. ```typescript fetchNextPage(options?: FetchNextPageOptions) ``` -------------------------------- ### Create Storage with custom serialize function Source: https://wagmi.sh/react/api/createStorage Create a storage object with a custom `serialize` function. Ensure it can handle `bigint` and `Map` values. ```typescript import { createStorage, serialize } from '{{packageName}}' const storage = createStorage({ serialize, storage: localStorage, }) ``` -------------------------------- ### Hook Configuration Parameters Source: https://wagmi.sh/react/api/hooks/useBalance Configuration options for Wagmi hooks including cache scoping and TanStack Query integration. ```APIDOC ## Hook Configuration Parameters ### Description Configure how Wagmi hooks interact with the cache and TanStack Query. ### Parameters #### scopeKey - **scopeKey** (string | undefined) - Optional - Scopes the cache to a given context. Hooks with identical context share the same cache. #### TanStack Query Parameters - **enabled** (boolean | undefined) - Optional - Set to false to disable the query from automatically running. - **gcTime** (number | Infinity | undefined) - Optional - Time in milliseconds that unused/inactive cache data remains in memory. - **initialData** ({{TData}} | (() => {{TData}}) | undefined) - Optional - Initial data for the query cache. - **initialDataUpdatedAt** (number | (() => number | undefined) | undefined) - Optional - Time in milliseconds when initialData was last updated. - **initialPageParam** ({{TPageParam}}) - Optional - Initial page parameter for infinite queries. - **getPreviousPageParam** (function) - Optional - Function to get the previous cursor for infinite queries. - **getNextPageParam** (function) - Optional - Function to get the next cursor for infinite queries. - **meta** (Record | undefined) - Optional - Additional information stored on the query cache entry. - **networkMode** ('online' | 'always' | 'offlineFirst' | undefined) - Optional - Defines how the query handles network connectivity. - **notifyOnChangeProps** (string[] | 'all' | (() => string[] | 'all') | undefined) - Optional - Controls component re-renders based on property changes. ### Request Example ```tsx import { useBalance } from 'wagmi' function App() { const result = useBalance({ address: '0x4557B18E779944BFE9d78A672452331C186a9f48', scopeKey: 'foo', }) } ``` ``` -------------------------------- ### Mutation Options and States Source: https://wagmi.sh/react/api/hooks/useSwitchConnection Details on mutation options like `retry` and `retryDelay`, and the various states and return values of mutation functions. ```APIDOC ## Mutation Options and States ### queryClient `QueryClient` Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used. ### retry `boolean | number | ((failureCount: number, error: {{TError}}) => boolean) | undefined` * Defaults to `0`. * If `false`, failed mutations will not retry. * If `true`, failed mutations will retry infinitely. * If set to an `number`, e.g. `3`, failed mutations will retry until the failed mutations count meets that number. ### retryDelay `number | ((retryAttempt: number, error: {{TError}}) => number) | undefined` * This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds. * A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff. * A function like `attempt => attempt * 1000` applies linear backoff. ### mutate `(variables: {{TVariables}}, { onSuccess, onSettled, onError }) => void` The mutation function you can call with variables to trigger the mutation and optionally hooks on additional callback options. * #### variables `{{TVariables}}` The variables object to pass to the `{{mutate}}` action. * #### onSuccess `(data: {{TData}}, variables: {{TVariables}}, context: TContext) => void` This function will fire when the mutation is successful and will be passed the mutation's result. * #### onError `(error: {{TError}}, variables: {{TVariables}}, context: TContext | undefined) => void` This function will fire if the mutation encounters an error and will be passed the error. * #### onSettled `(data: {{TData}} | undefined, error: {{TError}} | null, variables: {{TVariables}}, context: TContext | undefined) => void` * This function will fire when the mutation is either successfully fetched or encounters an error and be passed either the data or error * If you make multiple requests, `onSuccess` will fire only after the latest call you've made. ### mutateAsync `(variables: {{TVariables}}, { onSuccess, onSettled, onError }) => Promise<{{TData}}>` Similar to [`mutate`](#mutate) but returns a promise which can be awaited. ### data `{{TData}} | undefined` * `{{mutate}}` return type * Defaults to `undefined` * The last successfully resolved data for the mutation. ### error `{{TError}} | null` The error object for the mutation, if an error was encountered. ### failureCount `number` * The failure count for the mutation. * Incremented every time the mutation fails. * Reset to `0` when the mutation succeeds. ### failureReason `{{TError}} | null` * The failure reason for the mutation retry. * Reset to `null` when the mutation succeeds. ### isError / isIdle / isPending / isSuccess `boolean` Boolean variables derived from [`status`](#status). ### isPaused `boolean` * will be `true` if the mutation has been `paused`. * see [Network Mode](https://tanstack.com/query/v5/docs/react/guides/network-mode) for more information. ### reset `() => void` A function to clean the mutation internal state (e.g. it resets the mutation to its initial state). ### status `'idle' | 'pending' | 'error' | 'success'` * `'idle'` initial status prior to the mutation function executing. * `'pending'` if the mutation is currently executing. * `'error'` if the last mutation attempt resulted in an error. * `'success'` if the last mutation attempt was successful. ### submittedAt `number` * The timestamp for when the mutation was submitted. * Defaults to `0`. ``` -------------------------------- ### Import useEnsResolver Hook Source: https://wagmi.sh/react/api/hooks/useEnsResolver Import the useEnsResolver hook from the wagmi library. ```typescript import { useEnsResolver } from 'wagmi' ``` -------------------------------- ### Import TanStack Query Types Source: https://wagmi.sh/react/api/hooks/useBlockNumber Standard import pattern for query-related types and options in a TypeScript environment. ```ts-vue import { type {{typeName}}Data, type {{typeName}}Options, type {{typeName}}QueryFnData, type {{typeName}}QueryKey, {{actionName}}QueryKey, {{actionName}}QueryOptions, } from '{{packageName}}/query' ``` -------------------------------- ### Configure scopeKey for useBlobBaseFee Source: https://wagmi.sh/react/api/hooks/useBlobBaseFee Use a scope key to share cache between hooks with identical context. ```tsx import { useBlobBaseFee } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useBlobBaseFee({ scopeKey: 'foo', // [!code focus] }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Usage with custom config Source: https://wagmi.sh/react/api/hooks/useChains Provide a specific configuration object to the hook instead of using the default context. ```tsx import { useChains } from 'wagmi' import { config } from './config' // [!code focus] function App() { const chains = useChains({ config, // [!code focus] }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### refetch Method Source: https://wagmi.sh/react/api/hooks/useBlobBaseFee Function to manually trigger a refetch of the query. ```APIDOC ## refetch ### Description A function to manually refetch the query. ### Parameters - **options** (object) - Optional configuration object. - **cancelRefetch** (boolean) - Optional. If true, cancels running requests before refetching. Defaults to true. - **throwOnError** (boolean) - Optional. If true, throws an error on failure; if false, logs the error. ``` -------------------------------- ### Configuring SSR with createConfig Source: https://wagmi.sh/react/api/createConfig Set the `ssr` flag to `true` to indicate that the config is being used in a server-side rendering environment. Defaults to `false`. ```ts-vue import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' const config = createConfig({ chains: [mainnet, sepolia], ssr: true, transports: { [mainnet.id]: http('https://mainnet.example.com'), [sepolia.id]: http('https://sepolia.example.com'), }, }) ``` -------------------------------- ### Configure transaction parameters Source: https://wagmi.sh/react/api/hooks/usePrepareTransactionRequest Use the parameters array to specify which transaction fields to prepare. ```tsx import { usePrepareTransactionRequest } from 'wagmi' import { parseEther } from 'viem' function App() { const result = usePrepareTransactionRequest({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', parameters: ['gas', 'nonce'], // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### useWatchBlocks Hook Configuration Source: https://wagmi.sh/react/api/hooks/useWatchBlocks Configuration options for the useWatchBlocks hook. ```APIDOC ## useWatchBlocks Hook Options ### emitOnBegin `boolean` Whether or not to emit the block to the callback when the subscription opens. Defaults to `false`. ### enabled `boolean` Whether or not to watch for blocks. Defaults to `true`. ### includeTransactions `boolean` Whether or not to unwrap transactions as objects (instead of hashes) in blocks. Defaults to `false`. ### onBlock `(block: Block, prevblock: Block | undefined) => void` Callback for when block changes. ### onError `((error: Error) => void) | undefined` Error thrown from getting the block. ### poll `boolean | undefined` * Whether or not to use a polling mechanism to check for new blocks instead of a WebSocket subscription. * Defaults to `false` for WebSocket Clients, and `true` for non-WebSocket Clients. ``` -------------------------------- ### Import useStorageAt Hook Source: https://wagmi.sh/react/api/hooks/useStorageAt Import the useStorageAt hook from the wagmi library. ```typescript import { useStorageAt } from 'wagmi' ``` -------------------------------- ### Import UseConnectionParameters Source: https://wagmi.sh/react/api/hooks/useConnection Import the type definition for hook parameters. ```ts import { type UseConnectionParameters } from 'wagmi' ``` -------------------------------- ### Basic Usage of useBlobBaseFee Source: https://wagmi.sh/react/api/hooks/useBlobBaseFee Basic implementation of the hook within a React component. ```tsx import { useBlobBaseFee } from 'wagmi' function App() { const result = useBlobBaseFee() } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Configure Safe Connector with Debug Enabled Source: https://wagmi.sh/react/api/connectors/safe Initialize the Safe connector with the debug option enabled for enhanced logging. ```typescript import { safe } from '{{connectorsPackageName}}' const connector = safe({ debug: true, }) ``` -------------------------------- ### TanStack Query Parameters Source: https://wagmi.sh/react/api/hooks/useFeeHistory Overview of TanStack Query parameters supported by Wagmi hooks, with explanations for each parameter. ```APIDOC ## TanStack Query Parameters ### Description Wagmi utilizes TanStack Query for its data fetching and caching mechanisms. This section details the TanStack Query parameters that can be passed to Wagmi hooks. Note that certain parameters like `queryFn` and `queryKey` are used internally by Wagmi and cannot be overridden. ### Parameters #### enabled - **Type**: `boolean | undefined` - **Description**: Set to `false` to disable the query from running automatically. Useful for [Dependent Queries](https://tanstack.com/query/v5/docs/react/guides/dependent-queries). #### gcTime - **Type**: `number | Infinity | undefined` - **Description**: Defaults to `5 * 60 * 1000` (5 minutes) or `Infinity` during SSR. Specifies the time in milliseconds that unused cache data remains in memory before garbage collection. The longest duration specified will be used if multiple `gcTime` values are set. Setting to `Infinity` disables garbage collection. #### initialData - **Type**: `{{TData}} | (() => {{TData}}) | undefined` - **Description**: Provides initial data for the query cache if the query hasn't been created or cached yet. If a function is provided, it will be called once during initialization and must synchronously return the initial data. `initialData` is considered stale by default unless `staleTime` is set and is persisted to the cache. #### initialDataUpdatedAt - **Type**: `number | (() => number | undefined) | undefined` - **Description**: Sets the time (in milliseconds) when the `initialData` was last updated. #### initialPageParam - **Type**: `{{TPageParam}}` - **Description**: The initial page parameter for infinite queries. #### getPreviousPageParam - **Type**: `(firstPage: {{TData}}, allPages: {{TData}}[], firstPageParam: {{TPageParam}}, allPageParams: {{TPageParam}}[]) => {{TPageParam}} | undefined | null` - **Description**: A function to retrieve the previous cursor for infinite queries. The result determines the value of `hasPreviousPage`. #### getNextPageParam - **Type**: `(lastPage: {{TData}}, allPages: {{TData}}[], lastPageParam: {{TPageParam}}, allPageParams: {{TPageParam}}[]) => {{TPageParam}} | undefined | null` - **Description**: A function to retrieve the next cursor for infinite queries. The result determines the value of `hasNextPage`. #### meta - **Type**: `Record | undefined` - **Description**: Allows storing additional information on the query cache entry, accessible via the `query` object and `QueryFunctionContext`. #### networkMode - **Type**: `'online' | 'always' | 'offlineFirst' | undefined` - **Description**: Defaults to `'online'`. Controls the network mode for queries. See [Network Mode](https://tanstack.com/query/v5/docs/react/guides/network-mode) for more details. ``` -------------------------------- ### Basic Usage of useGasPrice Source: https://wagmi.sh/react/api/hooks/useGasPrice Use the useGasPrice hook to fetch the current gas price. Ensure wagmi is configured. ```tsx import { useGasPrice } from 'wagmi' function App() { const result = useGasPrice() } ``` ```typescript import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### useSimulateContract - blockTag parameter Source: https://wagmi.sh/react/api/hooks/useSimulateContract Specifies the block tag at which to call the contract. ```APIDOC ## POST /simulateContract ### Description Simulates a contract interaction using the provided parameters. ### Method POST ### Endpoint /simulateContract ### Parameters #### Request Body - **account** (Account | undefined) - The account to use when calling the contract (msg.sender). Throws if account is not found on connector. - **address** (Address | undefined) - The contract's address. - **functionName** (string) - The name of the function to call on the contract. - **args** (unknown[]) - Arguments to pass when calling the contract. Inferred from `abi` and `functionName`. - **abi** (Abi | undefined) - The contract's ABI. - **blockNumber** (bigint | undefined) - Block number to call contract at. - **blockTag** ('latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined) - Block tag to call contract at. ### Request Example ```json { "blockTag": "safe" } ``` ### Response #### Success Response (200) - **result** (SimulateContractResult) - The result of the contract simulation. #### Response Example ```json { "result": { "data": "0x...", "request": { "from": "0xd2135CfB216b74109775236E36d4b433F1DF507B", "to": "0x6b175474e89094c44da98b954eedeac495271d0f", "value": 0n, "data": "0x..." } } } ``` ``` -------------------------------- ### Import Storage type Source: https://wagmi.sh/react/api/createStorage Import the `Storage` type for defining storage interfaces. ```typescript import { type Storage } from '{{packageName}}' ``` -------------------------------- ### WagmiProvider with Initial State Source: https://wagmi.sh/react/api/WagmiProvider Provide an initial state to the WagmiProvider for server-side rendering (SSR). ```tsx import { WagmiProvider } from 'wagmi' import { config } from './config' function App() { return ( {/** ... **/ ) } ``` ```typescript import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### useConnectorClient Hook API Source: https://wagmi.sh/react/api/hooks/useConnectorClient Provides a Viem Client object for the current or provided connector. ```APIDOC ## useConnectorClient ### Description Hook for getting a Viem [`Client`](https://viem.sh/docs/clients/custom) object for the current or provided connector. ### Import ```ts import { useConnectorClient } from 'wagmi' ``` ### Usage ```tsx import { useConnectorClient } from 'wagmi' function App() { const result = useConnectorClient() } ``` ## Parameters ### account `Address | Account | undefined` Account to use with client. Throws if account is not found on [`connector`](#connector). ```tsx import { useConnectorClient } from 'wagmi' function App() { const result = useConnectorClient({ account: '0xd2135CfB216b74109775236E36d4b433F1DF507B', }) } ``` ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use with client. ```tsx import { useConnectorClient } from 'wagmi' import { mainnet } from 'wagmi/chains' function App() { const result = useConnectorClient({ chainId: mainnet.id, }) } ``` ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ```tsx import { useConnectorClient } from 'wagmi' import { config } from './config' function App() { const result = useConnectorClient({ config, }) } ``` ### connector `Connector | undefined` * Connector to get client for. * Defaults to current connector. ```tsx import { useConnections, useConnectorClient } from 'wagmi' function App() { const connections = useConnections(config) const result = useConnectorClient({ connector: connections[0]?.connector, }) } ``` ### query TanStack Query parameters. See the [TanStack Query query docs](https://tanstack.com/query/v5/docs/react/reference/useQuery) for more info. ::: info Wagmi does not support passing all TanStack Query parameters TanStack Query parameters, like `queryFn` and `queryKey`, are used internally to make Wagmi work and you cannot override them. Check out the [source](https://github.com/wevm/wagmi/blob/main/packages/react/src/types/properties.ts#L27) to see what parameters are not supported. All parameters listed below are supported. ::: #### enabled `boolean | undefined` * Set this to `false` to disable this query from automatically running. * Can be used for [Dependent Queries](https://tanstack.com/query/v5/docs/react/guides/dependent-queries). #### gcTime `number | Infinity | undefined` * Defaults to `5 * 60 * 1000` (5 minutes) or `Infinity` during SSR * The time in milliseconds that unused/inactive cache data remains in memory. When a query's cache becomes unused or inactive, that cache data will be garbage collected after this duration. When different garbage collection times are specified, the longest one will be used. * If set to `Infinity`, will disable garbage collection ``` -------------------------------- ### Configure Multiple Wagmi Instances Source: https://wagmi.sh/react/typescript Define multiple Wagmi configurations to be used selectively by hooks. ```ts import { createConfig, http } from 'wagmi' import { mainnet, optimism } from 'wagmi/chains' export const configA = createConfig({ // [!code focus] chains: [mainnet], // [!code focus] transports: { // [!code focus] [mainnet.id]: http(), // [!code focus] }, // [!code focus] }) // [!code focus] export const configB = createConfig({ // [!code focus] chains: [optimism], // [!code focus] transports: { // [!code focus] [optimism.id]: http(), // [!code focus] }, // [!code focus] }) // [!code focus] ``` -------------------------------- ### Import useVerifyTypedData Hook Source: https://wagmi.sh/react/api/hooks/useVerifyTypedData Import the useVerifyTypedData hook from the wagmi library. ```typescript import { useVerifyTypedData } from 'wagmi' ``` -------------------------------- ### Configure MaxFeePerGas Parameter Source: https://wagmi.sh/react/api/hooks/useEstimateGas Sets the total fee per gas in wei for EIP-1559 transactions. ```ts // {"path":"/vercel/path0/site/react/api/hooks/useEstimateGas.md","from":4728,"to":5042} import { useEstimateGas } from 'wagmi' import { parseEther, parseGwei } from 'viem' import { config } from './config' function App() { const result = useEstimateGas({ maxFeePerGas: parseGwei('20'), // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Import UseSwitchConnectionReturnType Source: https://wagmi.sh/react/api/hooks/useSwitchConnection Import the return type definition for the useSwitchConnection hook. ```ts import { type UseSwitchConnectionReturnType } from 'wagmi' ``` -------------------------------- ### refetchOnWindowFocus Source: https://wagmi.sh/react/api/hooks/useEnsResolver Configures refetching behavior when the window gains focus. ```APIDOC ## refetchOnWindowFocus ### Description If set to `true`, the query will refetch on window focus if the data is stale. If set to `false`, the query will not refetch on window focus. If set to `'always'`, the query will always refetch on window focus. If set to a function, the function will be executed with the query to compute the value. ### Type `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` ### Default `true` ``` -------------------------------- ### useSimulateContract - address parameter Source: https://wagmi.sh/react/api/hooks/useSimulateContract The address of the contract to interact with. ```APIDOC ## POST /simulateContract ### Description Simulates a contract interaction using the provided parameters. ### Method POST ### Endpoint /simulateContract ### Parameters #### Request Body - **account** (Account | undefined) - The account to use when calling the contract (msg.sender). Throws if account is not found on connector. - **address** (Address | undefined) - The contract's address. - **functionName** (string) - The name of the function to call on the contract. - **args** (unknown[]) - Arguments to pass when calling the contract. Inferred from `abi` and `functionName`. - **abi** (Abi | undefined) - The contract's ABI. - **blockNumber** (bigint | undefined) - Block number to call contract at. - **blockTag** ('latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined) - Block tag to call contract at. ### Request Example ```json { "address": "0x6b175474e89094c44da98b954eedeac495271d0f" } ``` ### Response #### Success Response (200) - **result** (SimulateContractResult) - The result of the contract simulation. #### Response Example ```json { "result": { "data": "0x...", "request": { "from": "0xd2135CfB216b74109775236E36d4b433F1DF507B", "to": "0x6b175474e89094c44da98b954eedeac495271d0f", "value": 0n, "data": "0x..." } } } ``` ``` -------------------------------- ### Import useWriteContract Hook Source: https://wagmi.sh/react/api/hooks/useWriteContract Import the `useWriteContract` hook from the wagmi library. ```typescript import { useWriteContract } from 'wagmi' ``` -------------------------------- ### Import serialize function Source: https://wagmi.sh/react/api/utilities/serialize Import the serialize function from the wagmi package. This is the first step before using it in your application. ```ts-vue import { serialize } from '{{packageName}}' ``` -------------------------------- ### Set preference parameter Source: https://wagmi.sh/react/api/connectors/coinbaseWallet Configure the wallet type preference for the connection. ```ts import { coinbaseWallet } from '{{connectorsPackageName}}' const connector = coinbaseWallet({ appName: 'My Wagmi App', preference: { // [!code focus] options: 'smartWalletOnly' // [!code focus] }, // [!code focus] }) ``` -------------------------------- ### Define mock accounts Source: https://wagmi.sh/react/api/connectors/mock Specify the list of addresses to be used by the mock connector. ```ts-vue import { mock } from '{{connectorsPackageName}}' const connector = mock({ accounts: [ // [!code focus] '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', // [!code focus] '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', // [!code focus] '0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC', // [!code focus] '0x90F79bf6EB2c4f870365E785982E1f101E93b906', // [!code focus] '0x15d34aaf54267db7d7c367839aaf71a00a2c6a65', // [!code focus] '0x9965507D1a55bcC2695C58ba16FB37d819B0A4dc', // [!code focus] '0x976EA74026E726554dB657fA54763abd0C3a0aa9', // [!code focus] '0x14dC79964da2C08b23698B3D3cc7Ca32193d9955', // [!code focus] '0x23618e81E3f5cdF7f54C3d65f7FBc0aBf5B21E8f', // [!code focus] '0xa0Ee7A142d267C1f36714E4a8F75612F20a79720', // [!code focus] ], // [!code focus] }) ``` -------------------------------- ### Import useReadContracts Hook Source: https://wagmi.sh/react/api/hooks/useReadContracts Import the useReadContracts hook from the wagmi library. ```typescript import { useReadContracts } from 'wagmi' ``` -------------------------------- ### placeholderData Source: https://wagmi.sh/react/api/hooks/useEnsResolver Provides placeholder data for a query observer. ```APIDOC ## placeholderData ### Description If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `pending` state. `placeholderData` is **not persisted** to the cache. If you provide a function for `placeholderData`, as a first argument you will receive previously watched query data if available, and the second argument will be the complete previousQuery instance. ### Type `{{TData}} | ((previousValue: {{TData}} | undefined; previousQuery: Query | undefined) => {{TData}}) | undefined` ``` -------------------------------- ### Mutation Execution and State Source: https://wagmi.sh/react/api/hooks/useSignTypedData Functions and properties for executing mutations and observing their state. ```APIDOC ## Mutation Execution and State ### mutate `(variables: {{TVariables}}, { onSuccess, onSettled, onError }) => void` The mutation function you can call with variables to trigger the mutation and optionally hooks on additional callback options. * #### variables `{{TVariables}}` The variables object to pass to the `{{mutate}}` action. * #### onSuccess `(data: {{TData}}, variables: {{TVariables}}, context: TContext) => void` This function will fire when the mutation is successful and will be passed the mutation's result. * #### onError `(error: {{TError}}, variables: {{TVariables}}, context: TContext | undefined) => void` This function will fire if the mutation encounters an error and will be passed the error. * #### onSettled `(data: {{TData}} | undefined, error: {{TError}} | null, variables: {{TVariables}}, context: TContext | undefined) => void` * This function will fire when the mutation is either successfully fetched or encounters an error and be passed either the data or error * If you make multiple requests, `onSuccess` will fire only after the latest call you've made. ### mutateAsync `(variables: {{TVariables}}, { onSuccess, onSettled, onError }) => Promise<{{TData}}>` Similar to [`mutate`](#mutate) but returns a promise which can be awaited. ### data `{{TData}} | undefined` * `{{mutate}}` return type * Defaults to `undefined` * The last successfully resolved data for the mutation. ### error `{{TError}} | null` The error object for the mutation, if an error was encountered. ### failureCount `number` * The failure count for the mutation. * Incremented every time the mutation fails. * Reset to `0` when the mutation succeeds. ### failureReason `{{TError}} | null` * The failure reason for the mutation retry. * Reset to `null` when the mutation succeeds. ### isError / isIdle / isPending / isSuccess `boolean` Boolean variables derived from [`status`](#status). ### isPaused `boolean` * will be `true` if the mutation has been `paused`. * see [Network Mode](https://tanstack.com/query/v5/docs/react/guides/network-mode) for more information. ### reset `() => void` A function to clean the mutation internal state (e.g. it resets the mutation to its initial state). ### status `'idle' | 'pending' | 'error' | 'success'` * `'idle'` initial status prior to the mutation function executing. * `'pending'` if the mutation is currently executing. * `'error'` if the last mutation attempt resulted in an error. * `'success'` if the last mutation attempt was successful. ### submittedAt `number` * The timestamp for when the mutation was submitted. * Defaults to `0`. ``` -------------------------------- ### useGasPrice Hook API Source: https://wagmi.sh/react/api/hooks/useGasPrice Documentation for the useGasPrice hook, including its parameters and usage. ```APIDOC ## useGasPrice Hook ### Description Hook for fetching the current price of gas (in wei). ### Import ```ts import { useGasPrice } from 'wagmi' ``` ### Usage ```tsx import { useGasPrice } from 'wagmi' function App() { const result = useGasPrice() } ``` ### Parameters #### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ```tsx import { useGasPrice } from 'wagmi' import { mainnet } from 'wagmi/chains' function App() { const result = useGasPrice({ chainId: mainnet.id, }) } ``` #### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ```tsx import { useGasPrice } from 'wagmi' import { config } from './config' function App() { const result = useGasPrice({ config, }) } ``` #### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ```tsx import { useGasPrice } from 'wagmi' import { config } from './config' function App() { const result = useGasPrice({ scopeKey: 'foo', }) } ``` ### query TanStack Query parameters. See the [TanStack Query query docs](https://tanstack.com/query/v5/docs/react/reference/useQuery) for more info. ::: info Wagmi does not support passing all TanStack Query parameters TanStack Query parameters, like `queryFn` and `queryKey`, are used internally to make Wagmi work and you cannot override them. Check out the [source](https://github.com/wevm/wagmi/blob/main/packages/react/src/types/properties.ts#L27) to see what parameters are not supported. All parameters listed below are supported. ::: #### enabled `boolean | undefined` * Set this to `false` to disable this query from automatically running. * Can be used for [Dependent Queries](https://tanstack.com/query/v5/docs/react/guides/dependent-queries). #### gcTime `number | Infinity | undefined` * Defaults to `5 * 60 * 1000` (5 minutes) or `Infinity` during SSR * The time in milliseconds that unused/inactive cache data remains in memory. When a query's cache becomes unused or inactive, that cache data will be garbage collected after this duration. When different garbage collection times are specified, the longest one will be used. * If set to `Infinity`, will disable garbage collection #### initialData `{{TData}} | (() => {{TData}}) | undefined` * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been created or cached yet) * If set to a function, the function will be called **once** during the shared/root query initialization, and be expected to synchronously return the initialData * Initial data is considered stale by default unless a `staleTime` has been set. * `initialData` **is persisted** to the cache ``` -------------------------------- ### Configuring useShowCallsStatus with Custom Config Source: https://wagmi.sh/react/api/hooks/useShowCallsStatus Shows how to use the useShowCallsStatus hook with a specific Wagmi configuration object. Ensure the config is imported correctly. ```tsx import { useShowCallsStatus } from 'wagmi' import { config } from './config' // [!code focus] function App() { const showCallsStatus = useShowCallsStatus({ config, // [!code focus] }) } ``` ```typescript import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Basic Usage Source: https://wagmi.sh/react/api/hooks/useBlock Basic implementation of the useBlock hook within a React component. ```tsx import { useBlock } from 'wagmi' function App() { const result = useBlock() } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Configure Safe Connector in wagmi Source: https://wagmi.sh/react/api/connectors/safe Set up the wagmi configuration with the Safe connector, specifying chains and transports. ```typescript import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' import { safe } from '{{connectorsPackageName}}' export const config = createConfig({ chains: [mainnet, sepolia], connectors: [safe()], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Config Parameter Source: https://wagmi.sh/react/api/hooks/useBalance Provide a custom Wagmi config instance. ```tsx import { useBalance } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useBalance({ address: '0x4557B18E779944BFE9d78A672452331C186a9f48', config, // [!code focus] }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### useEnsText Hook Source: https://wagmi.sh/react/api/hooks/useEnsText This snippet demonstrates the basic usage of the useEnsText hook with a specified ENS name and key. ```APIDOC ## useEnsText Hook ### Description Fetches text records associated with an ENS name. ### Method `useEnsText` ### Parameters #### Request Body - **name** (string | undefined) - Required/Optional - Name to get the text for. `enabled` set to `false` if `name` is `undefined`. - **key** (string | undefined) - Required/Optional - The key for the text record. - **config** (Config | undefined) - Required/Optional - Configuration object to use instead of retrieving from the nearest `WagmiProvider`. - **scopeKey** (string | undefined) - Required/Optional - Scopes the cache to a given context. Hooks that have identical context will share the same cache. - **universalResolverAddress** (Address | undefined) - Required/Optional - Resolver of ENS Universal Resolver Contract. Defaults to current chain's Universal Resolver Contract address. #### Query Parameters (TanStack Query) - **enabled** (boolean | undefined) - Set this to `false` to disable this query from automatically running. - **gcTime** (number | Infinity | undefined) - The time in milliseconds that unused/inactive cache data remains in memory. - **initialData** ({{TData}} | (() => {{TData}}) | undefined) - If set, this value will be used as the initial data for the query cache. ### Request Example ```json { "name": "wevm.eth", "key": "com.twitter", "config": { ... }, "scopeKey": "foo", "universalResolverAddress": "0x74E20Bd2A1fE0cdbe45b9A1d89cb7e0a45b36376" } ``` ### Response #### Success Response (200) - **data** (TData | undefined) - The fetched text record data. - **error** (TError | undefined) - An error object if the query failed. - **isError** (boolean) - Whether the query encountered an error. - **isLoading** (boolean) - Whether the query is currently loading. - **isSuccess** (boolean) - Whether the query has successfully fetched data. #### Response Example ```json { "data": "example_text_record", "error": null, "isError": false, "isLoading": false, "isSuccess": true } ``` ``` -------------------------------- ### TanStack Query Imports Source: https://wagmi.sh/react/api/hooks/useProof Import statements for TanStack Query types and functions. ```APIDOC ## TanStack Query Imports ### Description Import necessary types and functions for TanStack Query. ### Code ```ts-vue import { type {{typeName}}Data, type {{typeName}}Options, type {{typeName}}QueryFnData, type {{typeName}}QueryKey, {{actionName}}QueryKey, {{actionName}}QueryOptions, } from '{{packageName}}/query' ``` ``` -------------------------------- ### Query Options Source: https://wagmi.sh/react/api/hooks/useBlobBaseFee Configuration options available for Wagmi queries, including refetching behavior, retry mechanisms, data selection, and staleness. ```APIDOC ## Query Options ### refetchOnWindowFocus `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` * Defaults to `true` * If set to `true`, the query will refetch on window focus if the data is stale. * If set to `false`, the query will not refetch on window focus. * If set to `'always'`, the query will always refetch on window focus. * If set to a function, the function will be executed with the query to compute the value ### retry `boolean | number | ((failureCount: number, error: {{TError}}) => boolean) | undefined` * If `false`, failed queries will not retry by default. * If `true`, failed queries will retry infinitely. * If set to a `number`, e.g. `3`, failed queries will retry until the failed query count meets that number. * Defaults to `3` on the client and `0` on the server ### retryDelay `number | ((retryAttempt: number, error: {{TError}}) => number) | undefined` * This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds. * A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff. * A function like `attempt => attempt * 1000` applies linear backoff. ### retryOnMount `boolean | undefined` If set to `false`, the query will not be retried on mount if it contains an error. Defaults to `true`. ### select `((data: {{TData}}) => unknown) | undefined` This option can be used to transform or select a part of the data returned by the query function. It affects the returned `data` value, but does not affect what gets stored in the query cache. ### staleTime `number | Infinity | undefined` * Defaults to `0` * The time in milliseconds after data is considered stale. This value only applies to the hook it is defined on. * If set to `Infinity`, the data will never be considered stale ### structuralSharing `boolean | (((oldData: {{TData}} | undefined, newData: {{TData}}) => {{TData}})) | undefined` * Defaults to `true` * If set to `false`, structural sharing between query results will be disabled. * If set to a function, the old and new data values will be passed through this function, which should combine them into resolved data for the query. This way, you can retain references from the old data to improve performance even when that data contains non-serializable values. ``` -------------------------------- ### Import UseConnectionEffectParameters Source: https://wagmi.sh/react/api/hooks/useConnectionEffect Import the parameter type definition for the hook. ```ts import { type UseConnectionEffectParameters } from 'wagmi' ``` -------------------------------- ### Import Mutation Types for TanStack Query Source: https://wagmi.sh/react/api/hooks/useWriteContract Import necessary types for defining mutations with TanStack Query. Ensure your package name and type names are correctly substituted. ```ts-vue import { type {{typeName}}Data, type {{typeName}}Variables, type {{typeName}}Mutate, type {{typeName}}MutateAsync, {{actionName}}MutationOptions, } from '{{packageName}}/query' ``` -------------------------------- ### Importing a Chain Source: https://wagmi.sh/react/api/chains Import specific chain definitions from the wagmi/chains entrypoint. ```ts import { mainnet } from 'wagmi/chains' ``` -------------------------------- ### Import useConnectors Hook Source: https://wagmi.sh/react/api/hooks/useConnectors Import the useConnectors hook from the wagmi library. ```typescript import { useConnectors } from 'wagmi' ``` -------------------------------- ### Usage with config Source: https://wagmi.sh/react/api/hooks/useEstimateMaxPriorityFeePerGas Provide a custom Wagmi config instead of using the one from the nearest WagmiProvider. ```tsx import { useEstimateMaxPriorityFeePerGas } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useEstimateMaxPriorityFeePerGas({ config, // [!code focus] }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Usage with config Source: https://wagmi.sh/react/api/hooks/usePublicClient Provide a custom Wagmi config instead of using the nearest WagmiProvider. ```tsx import { usePublicClient } from 'wagmi' import { config } from './config' // [!code focus] function App() { const client = usePublicClient({ config, // [!code focus] }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### usePublicClient Hook Source: https://wagmi.sh/react/api/hooks/usePublicClient Retrieves a Viem PublicClient instance for interacting with the blockchain. ```APIDOC ## usePublicClient ### Description Hook for getting a Viem PublicClient instance. ### Parameters #### Query Parameters - **chainId** (config['chains'][number]['id'] | undefined) - Optional - ID of chain to use when getting Viem Public Client. - **config** (Config | undefined) - Optional - Config to use instead of retrieving from the nearest WagmiProvider. ### Response - **PublicClient | undefined** - The Viem PublicClient instance. ``` -------------------------------- ### Create Storage with custom deserialize function Source: https://wagmi.sh/react/api/createStorage Create a storage object with a custom `deserialize` function. Ensure it can handle `bigint` and `Map` values. ```typescript import { createStorage, deserialize } from '{{packageName}}' const storage = createStorage({ deserialize, storage: localStorage, }) ``` -------------------------------- ### Return Type: useProof Source: https://wagmi.sh/react/api/hooks/useProof The return type for the `useProof` hook, including various data and status properties. ```APIDOC ## Return Type: useProof ```ts import { type UseProofReturnType } from 'wagmi' ``` ### data `{{TData}}` * The last successfully resolved data for the query. * Defaults to `undefined`. ### dataUpdatedAt `number` The timestamp for when the query most recently returned the `status` as `'success'`. ### error `null | {{TError}}` * The error object for the query, if an error was thrown. * Defaults to `null` ### errorUpdatedAt `number` The timestamp for when the query most recently returned the `status` as `'error'`. ### errorUpdateCount `number` The sum of all errors. ### failureCount `number` * The failure count for the query. * Incremented every time the query fails. * Reset to `0` when the query succeeds. ### failureReason `null | {{TError}}` * The failure reason for the query retry. * Reset to `null` when the query succeeds. ### fetchNextPage `(options?: FetchNextPageOptions) => Promise>` This function allows you to fetch the next "page" of results. ### fetchPreviousPage `(options?: FetchPreviousPageOptions) => Promise>` This function allows you to fetch the previous "page" of results. ### hasNextPage `boolean` This will be `true` if there is a next page to be fetched (known via the `getNextPageParam` option). ### hasPreviousPage `boolean` This will be `true` if there is a previous page to be fetched (known via the `getPreviousPageParam` option). ### isFetchingNextPage `boolean` Will be `true` while fetching the next page with `fetchNextPage`. ### isFetchingPreviousPage `boolean` Will be `true` while fetching the previous page with `fetchPreviousPage`. ### fetchStatus `'fetching' | 'idle' | 'paused'` * `fetching` Is `true` whenever the queryFn is executing, which includes initial `pending` as well as background refetches. * `paused` The query wanted to fetch, but has been `paused`. * `idle` The query is not fetching. * See [Network Mode](https://tanstack.com/query/v5/docs/react/guides/network-mode) for more information. ### isError / isPending / isSuccess `boolean` Boolean variables derived from [`status`](#status). ### isFetched `boolean` Will be `true` if the query has been fetched. ### isFetchedAfterMount `boolean` * Will be `true` if the query has been fetched after the component mounted. * This property can be used to not show any previously cached data. ### isFetching / isPaused `boolean` Boolean variables derived from [`fetchStatus`](#fetchstatus). ### isLoading `boolean` * Is `true` whenever the first fetch for a query is in-flight * Is the same as `isFetching && isPending` ### isLoadingError `boolean` Will be `true` if the query failed while fetching for the first time. ### isPlaceholderData `boolean` Will be `true` if the data shown is the placeholder data. ### isRefetchError `boolean` Will be `true` if the query failed while refetching. ### isRefetching `boolean` * Is `true` whenever a background refetch is in-flight, which *does not* include initial `'pending'`. * Is the same as `isFetching && !isPending` ### isStale `boolean` Will be `true` if the data in the cache is invalidated or if the data is older than the given `staleTime`. ``` -------------------------------- ### Provide Custom Config Source: https://wagmi.sh/react/api/hooks/useTransaction Override the default WagmiProvider config with a custom instance. ```tsx import { useTransaction } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useTransaction({ hash: '0x0fa64daeae54e207aa98613e308c2ba8abfe274f75507e741508cc4db82c8cb5', config, // [!code focus] }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Import Parameters Type Source: https://wagmi.sh/react/api/hooks/useSendTransaction Import the parameter type definition for the hook. ```ts import { type UseSendTransactionParameters } from 'wagmi' ``` -------------------------------- ### Configure Wagmi with Chains and Transports Source: https://wagmi.sh/react/api/hooks/useReadContract Set up the wagmi configuration with specified blockchain chains and their corresponding HTTP transports. This is a prerequisite for interacting with the blockchain. ```typescript import { createConfig, http, useReadContract } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), ``` -------------------------------- ### Update createConfig without configureChains Source: https://wagmi.sh/react/guides/migrate-from-v1-to-v2 Wagmi v2's `Config` has native multichain support. The `configureChains` function is removed. Configure chains directly within `createConfig` using the `chains` and `transports` parameters. ```typescript import { configureChains, createConfig } from 'wagmi' // [!code --] import { http, createConfig } from 'wagmi' // [!code ++] import { mainnet, sepolia } from 'wagmi/chains' const { chains, publicClient } = configureChains( // [!code --] [mainnet, sepolia], // [!code --] [publicProvider(), publicProvider()], // [!code --] ) // [!code --] export const config = createConfig({ publicClient, // [!code --] chains: [mainnet, sepolia], // [!code ++] transports: { // [!code ++] [mainnet.id]: http(), // [!code ++] [sepolia.id]: http(), // [!code ++] }, // [!code ++] }) ``` -------------------------------- ### Use Connector Client with useSimulateContract Source: https://wagmi.sh/react/api/hooks/useSimulateContract Utilize the `connector` property to specify the connector client for simulating transactions. This requires fetching the connector client using `useConnectorClient`. ```tsx import { useConnectorClient, useSimulateContract } from 'wagmi' import { abi } from './abi' import { config } from './config' function App() { const { data: connector } = useConnectorClient() const result = useSimulateContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], connector, // [!code focus] }) } ``` -------------------------------- ### Configure webSocket Transport for Chains Source: https://wagmi.sh/react/api/transports/webSocket Create a wagmi configuration with webSocket transports for mainnet and sepolia chains. Provide authenticated RPC URLs for each chain to prevent rate limiting. ```typescript import { createConfig, webSocket } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' export const config = createConfig({ chains: [mainnet, sepolia], connectors: [injected()], transports: { [mainnet.id]: webSocket('wss://foo-bar-baz.quiknode.pro/...'), [sepolia.id]: webSocket('wss://foo-bar-sep.quicknode.pro/...'), }, }) ``` -------------------------------- ### TanStack Query Integration Source: https://wagmi.sh/react/api/hooks/useConnect Required imports for utilizing TanStack Query with Wagmi mutation actions. ```APIDOC ## TanStack Query Imports ### Description Import the necessary types and mutation options to integrate Wagmi actions with TanStack Query. ### Code Example ```ts import { type {{typeName}}Data, type {{typeName}}Variables, type {{typeName}}Mutate, type {{typeName}}MutateAsync, {{actionName}}MutationOptions, } from '{{packageName}}/query' ``` ``` -------------------------------- ### Estimate Gas with Connector Source: https://wagmi.sh/react/api/hooks/useEstimateGas Use a specific connector for the gas estimation. ```ts import { getConnections, estimateGas } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' function App() { const connections = getConnections(config) const result = useEstimateGas({ connector: connections[0]?.connector, // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Import UseDisconnectParameters Source: https://wagmi.sh/react/api/hooks/useDisconnect Import the type definition for hook parameters. ```ts import { type UseDisconnectParameters } from 'wagmi' ``` -------------------------------- ### Import useReadContract Hook Source: https://wagmi.sh/react/api/hooks/useReadContract Import the useReadContract hook from the wagmi library. ```typescript import { useReadContract } from 'wagmi' ``` -------------------------------- ### Handle Loading and Error States Source: https://wagmi.sh/react/guides/read-from-contract Implement loading and error handling for `useReadContract` to provide a better user experience. Display a loading indicator when data is being fetched and show an error message if the contract call fails. ```tsx import { type BaseError, useReadContract } from 'wagmi' function ReadContract() { const { data: balance, error, isPending } = useReadContract({ ...wagmiContractConfig, functionName: 'balanceOf', args: ['0x03A71968491d55603FFe1b11A9e23eF013f75bCF'], }) if (isPending) return
Loading...
if (error) return (
Error: {(error as BaseError).shortMessage || error.message}
) return (
Balance: {balance?.toString()}
) } ``` -------------------------------- ### useCall - config parameter Source: https://wagmi.sh/react/api/hooks/useCall The `config` parameter allows specifying a custom Config to use instead of the nearest WagmiProvider. ```APIDOC ## useCall - config parameter ### Description [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ### Method N/A (This describes a parameter, not an endpoint) ### Endpoint N/A ### Parameters #### Request Body - **config** (Config | undefined) - Required - [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ### Request Example ```tsx import { useCall } from 'wagmi' import { config } from './config' function App() { const result = useCall({ config, account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) } ``` ### Response #### Success Response (200) - **N/A** (N/A) - N/A #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Basic Usage of useWaitForTransactionReceipt Source: https://wagmi.sh/react/api/hooks/useWaitForTransactionReceipt Use the hook to wait for a transaction receipt by providing the transaction hash. The hook will return the receipt once the transaction is confirmed. ```tsx import { useWaitForTransactionReceipt } from 'wagmi' function App() { const result = useWaitForTransactionReceipt({ hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', }) } ``` -------------------------------- ### Usage of useProof Source: https://wagmi.sh/react/api/hooks/useProof Basic implementation of the useProof hook within a React component. ```tsx import { useProof } from 'wagmi' function App() { const result = useProof({ address: '0x4200000000000000000000000000000000000016', storageKeys: [ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Query Configuration Options Source: https://wagmi.sh/react/api/hooks/useEnsAvatar Configuration options for controlling query behavior such as refetching, retries, and data staleness. ```APIDOC ## Query Configuration Options ### Parameters - **refetchOnReconnect** (boolean | 'always' | function) - Optional - Determines if the query refetches on reconnect. Defaults to true. - **refetchOnWindowFocus** (boolean | 'always' | function) - Optional - Determines if the query refetches on window focus. Defaults to true. - **retry** (boolean | number | function) - Optional - Configures retry behavior for failed queries. Defaults to 3 on client, 0 on server. - **retryDelay** (number | function) - Optional - Defines the delay in milliseconds before the next retry attempt. - **retryOnMount** (boolean) - Optional - If false, query will not retry on mount if it contains an error. Defaults to true. - **select** (function) - Optional - Used to transform or select a part of the returned data. - **staleTime** (number | Infinity) - Optional - Time in milliseconds after which data is considered stale. Defaults to 0. - **structuralSharing** (boolean | function) - Optional - Enables or disables structural sharing between query results. Defaults to true. ``` -------------------------------- ### Configure Hook with Custom Config Source: https://wagmi.sh/react/api/hooks/useSendTransaction Pass a custom configuration object to the hook instead of using the default provider context. ```tsx import { useSendTransaction } from 'wagmi' import { config } from './config' // [!code focus] function App() { const sendTransaction = useSendTransaction({ config, // [!code focus] }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Check for Initial Fetch Error Source: https://wagmi.sh/react/api/hooks/useWaitForTransactionReceipt `isLoadingError` is true if the query encountered an error during its very first fetch attempt. ```typescript isLoadingError: boolean ``` -------------------------------- ### Mutation API Source: https://wagmi.sh/react/api/hooks/useConnect Details on mutation functions and their associated states and callbacks, including mutate, mutateAsync, data, error, and status. ```APIDOC ## Mutation API ### mutate `(variables: {{TVariables}}, { onSuccess, onSettled, onError }) => void` The mutation function you can call with variables to trigger the mutation and optionally hooks on additional callback options. * #### variables `{{TVariables}}` The variables object to pass to the `mutate` action. * #### onSuccess `(data: {{TData}}, variables: {{TVariables}}, context: TContext) => void` This function will fire when the mutation is successful and will be passed the mutation's result. * #### onError `(error: {{TError}}, variables: {{TVariables}}, context: TContext | undefined) => void` This function will fire if the mutation encounters an error and will be passed the error. * #### onSettled `(data: {{TData}} | undefined, error: {{TError}} | null, variables: {{TVariables}}, context: TContext | undefined) => void` * This function will fire when the mutation is either successfully fetched or encounters an error and be passed either the data or error * If you make multiple requests, `onSuccess` will fire only after the latest call you've made. ### mutateAsync `(variables: {{TVariables}}, { onSuccess, onSettled, onError }) => Promise<{{TData}}>` Similar to [`mutate`](#mutate) but returns a promise which can be awaited. ### data `{{TData}} | undefined` * `mutate` return type * Defaults to `undefined` * The last successfully resolved data for the mutation. ### error `{{TError}} | null` The error object for the mutation, if an error was encountered. ### failureCount `number` * The failure count for the mutation. * Incremented every time the mutation fails. * Reset to `0` when the mutation succeeds. ### failureReason `{{TError}} | null` * The failure reason for the mutation retry. * Reset to `null` when the mutation succeeds. ### isError / isIdle / isPending / isSuccess `boolean` Boolean variables derived from [`status`](#status). ### isPaused `boolean` * will be `true` if the mutation has been `paused`. * see [Network Mode](https://tanstack.com/query/v5/docs/react/guides/network-mode) for more information. ### reset `() => void` A function to clean the mutation internal state (e.g. it resets the mutation to its initial state). ### status `'idle' | 'pending' | 'error' | 'success'` * `'idle'` initial status prior to the mutation function executing. * `'pending'` if the mutation is currently executing. * `'error'` if the last mutation attempt resulted in an error. * `'success'` if the last mutation attempt was successful. ### submittedAt `number` * The timestamp for when the mutation was submitted. * Defaults to `0`. ``` -------------------------------- ### Import useReconnect Hook Source: https://wagmi.sh/react/api/hooks/useReconnect Import the useReconnect hook from the wagmi library. ```typescript import { useReconnect } from 'wagmi' ``` -------------------------------- ### Import Safe Connector Source: https://wagmi.sh/react/api/connectors/safe Import the safe connector from the wagmi connectors package. ```typescript import { safe } from '{{connectorsPackageName}}' ``` -------------------------------- ### Configure enabled for useWatchBlocks Source: https://wagmi.sh/react/api/hooks/useWatchBlocks Controls whether the hook actively watches for new blocks. ```ts // {"path":"/vercel/path0/site/react/api/hooks/useWatchBlocks.md","from":2799,"to":2992} import { useWatchBlocks } from 'wagmi' function App() { useWatchBlocks({ enabled: false, // [!code focus] onBlock(block) { console.log('New block', block.number) }, }) } ``` ```ts import { createConfig, http } from '@wagmi/core' import { mainnet, sepolia } from '@wagmi/core/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Configure useStorageAt with custom config Source: https://wagmi.sh/react/api/hooks/useStorageAt Pass a custom Wagmi config to the hook instead of relying on the nearest WagmiProvider. ```tsx import { useStorageAt } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useStorageAt({ config, // [!code focus] address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', slot: '0x0', }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### useBytecode Hook Source: https://wagmi.sh/react/api/hooks/useBytecode Retrieves the bytecode at a specified contract address. ```APIDOC ## useBytecode ### Description Hook for retrieving the bytecode at an address. ### Parameters - **address** (Address | undefined) - Optional - The contract address. - **blockNumber** (bigint | undefined) - Optional - The block number to check the bytecode at. - **blockTag** ('latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined) - Optional - The block tag to check the bytecode at. - **chainId** (number | undefined) - Optional - The chain ID to check the bytecode at. - **config** (Config | undefined) - Optional - Config to use instead of retrieving from the nearest WagmiProvider. ### Request Example ```tsx import { useBytecode } from 'wagmi' function App() { const result = useBytecode({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', }) } ``` ``` -------------------------------- ### Query Options Source: https://wagmi.sh/react/api/hooks/useBalance Configuration options for managing query behavior, including data fetching, caching, and retries. ```APIDOC ## Query Options ### placeholderData `{{TData}} | ((previousValue: {{TData}} | undefined; previousQuery: Query | undefined) => {{TData}}) | undefined` * If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `pending` state. * `placeholderData` is **not persisted** to the cache * If you provide a function for `placeholderData`, as a first argument you will receive previously watched query data if available, and the second argument will be the complete previousQuery instance. ### queryClient `QueryClient | undefined` Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used. ### refetchInterval `number | false | ((data: {{TData}} | undefined, query: Query) => number | false | undefined) | undefined` * If set to a number, all queries will continuously refetch at this frequency in milliseconds * If set to a function, the function will be executed with the latest data and query to compute a frequency ### refetchIntervalInBackground `boolean | undefined` If set to `true`, queries that are set to continuously refetch with a `refetchInterval` will continue to refetch while their tab/window is in the background ### refetchOnMount `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` * Defaults to `true` * If set to `true`, the query will refetch on mount if the data is stale. * If set to `false`, the query will not refetch on mount. * If set to `'always'`, the query will always refetch on mount. * If set to a function, the function will be executed with the query to compute the value ### refetchOnReconnect `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` * Defaults to `true` * If set to `true`, the query will refetch on reconnect if the data is stale. * If set to `false`, the query will not refetch on reconnect. * If set to `'always'`, the query will always refetch on reconnect. * If set to a function, the function will be executed with the query to compute the value ### refetchOnWindowFocus `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` * Defaults to `true` * If set to `true`, the query will refetch on window focus if the data is stale. * If set to `false`, the query will not refetch on window focus. * If set to `'always'`, the query will always refetch on window focus. * If set to a function, the function will be executed with the query to compute the value ### retry `boolean | number | ((failureCount: number, error: {{TError}}) => boolean) | undefined` * If `false`, failed queries will not retry by default. * If `true`, failed queries will retry infinitely. * If set to a `number`, e.g. `3`, failed queries will retry until the failed query count meets that number. * Defaults to `3` on the client and `0` on the server ### retryDelay `number | ((retryAttempt: number, error: {{TError}}) => number) | undefined` * This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds. * A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff. * A function like `attempt => attempt * 1000` applies linear backoff. ### retryOnMount `boolean | undefined` If set to `false`, the query will not be retried on mount if it contains an error. Defaults to `true`. ### select `((data: {{TData}}) => unknown) | undefined` This option can be used to transform or select a part of the data returned by the query function. It affects the returned `data` value, but does not affect what gets stored in the query cache. ### staleTime `number | Infinity | undefined` * Defaults to `0` * The time in milliseconds after data is considered stale. This value only applies to the hook it is defined on. * If set to `Infinity`, the data will never be considered stale ### structuralSharing `boolean | (((oldData: {{TData}} | undefined, newData: {{TData}}) => {{TData}})) | undefined` * Defaults to `true` * If set to `false`, structural sharing between query results will be disabled. * If set to a function, the old and new data values will be passed through this function, which should combine them into resolved data for the query. This way, you can retain references from the old data to improve performance even when that data contains non-serializable values. ``` -------------------------------- ### Query Options Source: https://wagmi.sh/react/api/hooks/useTransactionConfirmations Configuration options for controlling query behavior such as refetching, retrying, and data selection. ```APIDOC ## Query Options ### refetchOnMount `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` * Defaults to `true` * If set to `true`, the query will refetch on mount if the data is stale. * If set to `false`, the query will not refetch on mount. * If set to `'always'`, the query will always refetch on mount. * If set to a function, the function will be executed with the query to compute the value ### refetchOnReconnect `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` * Defaults to `true` * If set to `true`, the query will refetch on reconnect if the data is stale. * If set to `false`, the query will not refetch on reconnect. * If set to `'always'`, the query will always refetch on reconnect. * If set to a function, the function will be executed with the query to compute the value ### refetchOnWindowFocus `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` * Defaults to `true` * If set to `true`, the query will refetch on window focus if the data is stale. * If set to `false`, the query will not refetch on window focus. * If set to `'always'`, the query will always refetch on window focus. * If set to a function, the function will be executed with the query to compute the value ### retry `boolean | number | ((failureCount: number, error: {{TError}}) => boolean) | undefined` * If `false`, failed queries will not retry by default. * If `true`, failed queries will retry infinitely. * If set to a `number`, e.g. `3`, failed queries will retry until the failed query count meets that number. * Defaults to `3` on the client and `0` on the server ### retryDelay `number | ((retryAttempt: number, error: {{TError}}) => number) | undefined` * This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds. * A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff. * A function like `attempt => attempt * 1000` applies linear backoff. ### retryOnMount `boolean | undefined` If set to `false`, the query will not be retried on mount if it contains an error. Defaults to `true`. ### select `((data: {{TData}}) => unknown) | undefined` This option can be used to transform or select a part of the data returned by the query function. It affects the returned `data` value, but does not affect what gets stored in the query cache. ### staleTime `number | Infinity | undefined` * Defaults to `0` * The time in milliseconds after data is considered stale. This value only applies to the hook it is defined on. * If set to `Infinity`, the data will never be considered stale ### structuralSharing `boolean | (((oldData: {{TData}} | undefined, newData: {{TData}}) => {{TData}})) | undefined` * Defaults to `true` * If set to `false`, structural sharing between query results will be disabled. * If set to a function, the old and new data values will be passed through this function, which should combine them into resolved data for the query. This way, you can retain references from the old data to improve performance even when that data contains non-serializable values. ``` -------------------------------- ### Convert Viem Client to Ethers Signer Source: https://wagmi.sh/react/guides/ethers Utility functions to bridge Wagmi's Viem-based clients to Ethers.js Signers. Choose the version matching your project's Ethers dependency. ```ts import { providers } from 'ethers' import { useMemo } from 'react' import type { Account, Chain, Client, Transport } from 'viem' import { Config, useConnectorClient } from 'wagmi' export function clientToSigner(client: Client) { const { account, chain, transport } = client const network = { chainId: chain.id, name: chain.name, ensAddress: chain.contracts?.ensRegistry?.address, } const provider = new providers.Web3Provider(transport, network) const signer = provider.getSigner(account.address) return signer } /** Action to convert a Viem Client to an ethers.js Signer. */ export function useEthersSigner({ chainId }: { chainId?: number } = {}) { const { data: client } = useConnectorClient({ chainId }) return useMemo(() => (client ? clientToSigner(client) : undefined), [client]) } ``` ```ts import { BrowserProvider, JsonRpcSigner } from 'ethers' import { useMemo } from 'react' import type { Account, Chain, Client, Transport } from 'viem' import { type Config, useConnectorClient } from 'wagmi' export function clientToSigner(client: Client) { const { account, chain, transport } = client const network = { chainId: chain.id, name: chain.name, ensAddress: chain.contracts?.ensRegistry?.address, } const provider = new BrowserProvider(transport, network) const signer = new JsonRpcSigner(provider, account.address) return signer } /** Hook to convert a viem Wallet Client to an ethers.js Signer. */ export function useEthersSigner({ chainId }: { chainId?: number } = {}) { const { data: client } = useConnectorClient({ chainId }) return useMemo(() => (client ? clientToSigner(client) : undefined), [client]) } ``` -------------------------------- ### Replace wagmi/providers with Viem Transports Source: https://wagmi.sh/react/guides/migrate-from-v1-to-v2 Instead of using hardcoded provider URLs from `wagmi/providers`, utilize Viem transports with RPC provider URLs. ```typescript import { alchemyProvider } from 'wagmi/providers/alchemy' // [!code --] import { http } from 'viem' // [!code ++] const transport = http('https://mainnet.example.com') ``` -------------------------------- ### Import useSignTypedData Hook Source: https://wagmi.sh/react/api/hooks/useSignTypedData Import the useSignTypedData hook from the wagmi library. ```typescript import { useSignTypedData } from 'wagmi' ``` -------------------------------- ### Cache Configuration Source: https://wagmi.sh/react/api/hooks/useEnsAvatar Options related to cache management, including garbage collection and initial data. ```APIDOC ## gcTime `number | Infinity | undefined` * Defaults to `5 * 60 * 1000` (5 minutes) or `Infinity` during SSR * The time in milliseconds that unused/inactive cache data remains in memory. When a query's cache becomes unused or inactive, that cache data will be garbage collected after this duration. When different garbage collection times are specified, the longest one will be used. * If set to `Infinity`, will disable garbage collection ## initialData `{{TData}} | (() => {{TData}}) | undefined` * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been created or cached yet) * If set to a function, the function will be called **once** during the shared/root query initialization, and be expected to synchronously return the initialData * Initial data is considered stale by default unless a `staleTime` has been set. * `initialData` **is persisted** to the cache ## initialDataUpdatedAt `number | ((() => number | undefined)) | undefined` If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. ## meta `Record | undefined` If set, stores additional information on the query cache entry that can be used as needed. It will be accessible wherever the `query` is available, and is also part of the `QueryFunctionContext` provided to the `queryFn`. ``` -------------------------------- ### Configure WalletConnect showQrModal Source: https://wagmi.sh/react/api/connectors/walletConnect Toggles the visibility of the QR code modal. Disabling this allows for custom QR code rendering by listening to the 'display_uri' event. ```ts-vue import { walletConnect } from '{{connectorsPackageName}}' const connector = walletConnect({ projectId: '3fcc6bba6f1de962d911bb5b5c3dba68', showQrModal: true, // [!code focus] }) ``` -------------------------------- ### Estimate Gas with Account Source: https://wagmi.sh/react/api/hooks/useEstimateGas Specify the account to use for the gas estimation. ```ts import { useEstimateGas } from 'wagmi' import { parseEther } from 'viem' import { config } from './config' function App() { const result = useEstimateGas({ account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### useReadContracts Configuration Source: https://wagmi.sh/react/api/hooks/useReadContracts Configuration options for the useReadContracts hook. ```APIDOC ## useReadContracts Configuration ### blockTag - **Type**: 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined - **Description**: The block tag to read against. ### config - **Type**: Config | undefined - **Description**: A custom Wagmi Config instance to use instead of the nearest WagmiProvider. ### multicallAddress - **Type**: Address - **Description**: The specific address of the multicall contract to use. ### query - **Description**: TanStack Query parameters for controlling query behavior. #### enabled - **Type**: boolean | undefined - **Description**: Set to false to disable the query from automatically running. #### gcTime - **Type**: number | Infinity | undefined - **Description**: Time in milliseconds that unused cache data remains in memory. Defaults to 5 minutes. #### initialData - **Type**: {{TData}} | (() => {{TData}}) | undefined - **Description**: Initial data used for the query cache. #### initialDataUpdatedAt - **Type**: number | ((() => number | undefined)) | undefined - **Description**: The timestamp in milliseconds of when the initialData was last updated. ``` -------------------------------- ### Configure batchSize for useReadContracts Source: https://wagmi.sh/react/api/hooks/useReadContracts Set the maximum size in bytes for each calldata chunk. Defaults to 1024. ```tsx import { useReadContracts } from 'wagmi' function App() { const result = useReadContracts({ batchSize: 1024, // [!code hl] contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, functionName: 'getChest', args: [69] }, // ... ], }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Config Parameter Source: https://wagmi.sh/react/api/hooks/useTransactionConfirmations Override the default WagmiProvider configuration. ```tsx import { useTransactionConfirmations } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useTransactionConfirmations({ config, // [!code focus] hash: '0x0fa64daeae54e207aa98613e308c2ba8abfe274f75507e741508cc4db82c8cb5', }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Query Configuration Options Source: https://wagmi.sh/react/api/hooks/useCapabilities Configuration options for controlling query behavior such as refetching, retries, and data transformation. ```APIDOC ## Query Configuration Options ### refetchOnReconnect - **Type**: `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` - **Description**: Determines if the query refetches on reconnect. Defaults to `true`. ### refetchOnWindowFocus - **Type**: `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` - **Description**: Determines if the query refetches on window focus. Defaults to `true`. ### retry - **Type**: `boolean | number | ((failureCount: number, error: {{TError}}) => boolean) | undefined` - **Description**: Configures retry behavior for failed queries. Defaults to `3` on client, `0` on server. ### retryDelay - **Type**: `number | ((retryAttempt: number, error: {{TError}}) => number) | undefined` - **Description**: Function to calculate delay before next retry attempt. ### retryOnMount - **Type**: `boolean | undefined` - **Description**: If `false`, query will not retry on mount if it contains an error. Defaults to `true`. ### select - **Type**: `((data: {{TData}}) => unknown) | undefined` - **Description**: Used to transform or select a part of the data returned by the query function. ### staleTime - **Type**: `number | Infinity | undefined` - **Description**: Time in milliseconds after which data is considered stale. Defaults to `0`. ### structuralSharing - **Type**: `boolean | (((oldData: {{TData}} | undefined, newData: {{TData}}) => {{TData}})) | undefined` - **Description**: Enables or disables structural sharing between query results. Defaults to `true`. ``` -------------------------------- ### Define Contract Configuration Source: https://wagmi.sh/react/guides/read-from-contract Define the contract's address and ABI for use with wagmi hooks. This configuration object is essential for interacting with any contract. ```ts export const wagmiContractConfig = { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: [ { type: 'function', name: 'balanceOf', stateMutability: 'view', inputs: [{ name: 'account', type: 'address' }], outputs: [{ type: 'uint256' }], }, { type: 'function', name: 'totalSupply', stateMutability: 'view', inputs: [], outputs: [{ name: 'supply', type: 'uint256' }], }, ], } as const ``` -------------------------------- ### useConnect Hook Source: https://wagmi.sh/react/api/hooks/useConnect The useConnect hook provides functionality to connect user accounts. It accepts an optional configuration object and various mutation callbacks. ```APIDOC ## useConnect ### Description Hook for connecting accounts with connectors. ### Parameters #### config - **config** (Config | undefined) - Optional - Configuration to use instead of retrieving from the nearest WagmiProvider. #### mutation - **gcTime** (number | Infinity | undefined) - Optional - Time in milliseconds that unused/inactive cache data remains in memory. - **meta** (Record | undefined) - Optional - Additional information stored on the mutation cache entry. - **networkMode** ('online' | 'always' | 'offlineFirst' | undefined) - Optional - Defines the network mode for the mutation. - **onError** (Function) - Optional - Callback fired if the mutation encounters an error. - **onMutate** (Function) - Optional - Callback fired before the mutation function is executed. - **onSuccess** (Function) - Optional - Callback fired when the mutation is successful. - **onSettled** (Function) - Optional - Callback fired when the mutation is either successful or encounters an error. - **queryClient** (QueryClient) - Optional - Custom QueryClient instance. ### Request Example ```tsx import { useConnect } from 'wagmi' import { injected } from 'wagmi/connectors' function App() { const connect = useConnect() return ( ) } ``` ``` -------------------------------- ### Mutation Configuration Source: https://wagmi.sh/react/api/hooks/useSignTransaction Configuration options for controlling mutation retry behavior and delays. ```APIDOC ## Mutation Configuration ### retry - **Type**: `boolean | number | ((failureCount: number, error: {{TError}}) => boolean) | undefined` - **Description**: Defines retry behavior. Defaults to `0`. If `false`, no retries. If `true`, infinite retries. If a `number`, retries until the count is met. ### retryDelay - **Type**: `number | ((retryAttempt: number, error: {{TError}}) => number) | undefined` - **Description**: A function that receives the retry attempt and error, returning the delay in milliseconds before the next attempt. ``` -------------------------------- ### Use key parameter Source: https://wagmi.sh/react/api/hooks/useEnsText Specify the ENS text record key to retrieve. ```ts import { useEnsText } from 'wagmi' import { normalize } from 'viem/ens' function App() { const result = useEnsText({ name: normalize('wevm.eth'), key: 'com.twitter', // [!code focus] }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Configure HTTP Transport for Chains Source: https://wagmi.sh/react/api/transports/http Set up the wagmi configuration with the http transport for different chains. It's recommended to provide authenticated RPC URLs to prevent rate limiting. ```typescript import { createConfig, http // [!code hl] } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' export const config = createConfig({ chains: [mainnet, sepolia], connectors: [injected()], transports: { [mainnet.id]: http('https://foo-bar-baz.quiknode.pro/...'), // [!code hl] [sepolia.id]: http('https://foo-bar-sep.quiknode.pro/...'), // [!code hl] }, }) ``` -------------------------------- ### Manual Refetch Function Source: https://wagmi.sh/react/api/hooks/useCallsStatus Details the `refetch` function used for manually triggering query refetches and its options. ```APIDOC ## Manual Refetch Function ### refetch `(options: { cancelRefetch?: boolean | undefined; throwOnError?: boolean | undefined }) => Promise>` * A function to manually refetch the query. * `throwOnError` * When set to `true`, an error will be thrown if the query fails. * When set to `false`, an error will be logged if the query fails. * `cancelRefetch` * When set to `true`, a currently running request will be cancelled before a new request is made. * When set to `false`, no refetch will be made if there is already a request running. * Defaults to `true` ``` -------------------------------- ### Infinite Query Callbacks Source: https://wagmi.sh/react/api/hooks/useReadContracts Functions to determine previous and next page parameters for infinite queries. ```APIDOC ## getPreviousPageParam ### Description This function can be set to automatically get the previous cursor for infinite queries. The result will also be used to determine the value of `hasPreviousPage`. ### Signature `(firstPage: TData, allPages: TData[], firstPageParam: TPageParam, allPageParams: TPageParam[]) => TPageParam | undefined | null` ## getNextPageParam ### Description This function can be set to automatically get the previous cursor for infinite queries. The result will also be used to determine the value of `hasPreviousPage`. ### Signature `(lastPage: TData, allPages: TData[], lastPageParam: TPageParam, allPageParams: TPageParam[]) => TPageParam | undefined | null` ``` -------------------------------- ### Import UseSimulateContractParameters Source: https://wagmi.sh/react/api/hooks/useSimulateContract Import the type definition for the hook parameters. ```ts import { type UseSimulateContractParameters } from 'wagmi' ``` -------------------------------- ### useTransactionCount Hook Configuration Source: https://wagmi.sh/react/api/hooks/useTransactionCount Demonstrates how to use the `config` option to specify a custom configuration for the `useTransactionCount` hook, overriding the default provider. ```APIDOC ## POST /api/users ### Description This endpoint allows for the creation of new user resources. ### Method POST ### Endpoint /api/users ### Parameters #### Path Parameters - None #### Query Parameters - **param1** (string) - Optional - Description for param1 #### Request Body - **field1** (string) - Required - Description for field1 - **field2** (number) - Optional - Description for field2 ### Request Example ```json { "field1": "value1", "field2": 123 } ``` ### Response #### Success Response (200) - **id** (string) - Description for id - **name** (string) - Description for name #### Response Example ```json { "id": "user-123", "name": "John Doe" } ``` ``` -------------------------------- ### Use Custom Wagmi Config Source: https://wagmi.sh/react/api/hooks/useWaitForTransactionReceipt Provide a custom Wagmi configuration to the hook if you are not using the default one provided by WagmiProvider. ```tsx import { useWaitForTransactionReceipt } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useWaitForTransactionReceipt({ hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', config, // [!code focus] }) } ``` ```typescript import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Import UseEnsAvatarParameters Source: https://wagmi.sh/react/api/hooks/useEnsAvatar Import the type definition for the hook parameters. ```ts import { type UseEnsAvatarParameters } from 'wagmi' ``` -------------------------------- ### webSocket Transport with Custom Key Source: https://wagmi.sh/react/api/transports/webSocket Instantiate a webSocket transport with a custom key. The key defaults to 'webSocket' if not provided. ```typescript const transport = webSocket('wss://foo-bar-baz.quiknode.pro/...', { key: 'alchemy', }) ``` -------------------------------- ### Hook Configuration Options Source: https://wagmi.sh/react/api/hooks/useEnsName Configuration properties for customizing hook behavior, including cache scoping and ENS resolver addresses. ```APIDOC ## Hook Configuration Options ### Description Configuration properties used to customize the behavior of Wagmi React hooks. ### Parameters - **scopeKey** (string | undefined) - Optional - Scopes the cache to a given context. Hooks with identical context share the same cache. - **universalResolverAddress** (Address | undefined) - Optional - Address of the ENS Universal Resolver Contract. Defaults to the current chain's address. ### Request Example ```ts import { useEnsName } from 'wagmi' function App() { const result = useEnsName({ address: '0xd2135CfB216b74109775236E36d4b433F1DF507B', scopeKey: 'foo', universalResolverAddress: '0x74E20Bd2A1fE0cdbe45b9A1d89cb7e0a45b36376', }) } ``` ``` -------------------------------- ### Basic Usage Source: https://wagmi.sh/react/api/hooks/useEstimateMaxPriorityFeePerGas Basic implementation of the hook within a React component. ```tsx import { useEstimateMaxPriorityFeePerGas } from 'wagmi' function App() { const result = useEstimateMaxPriorityFeePerGas() } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Refetch Function Source: https://wagmi.sh/react/api/hooks/useConnectorClient Manually trigger a query refetch with customizable options. ```APIDOC ## Refetch Function ### refetch `(options: { cancelRefetch?: boolean | undefined; throwOnError?: boolean | undefined }) => Promise>` * A function to manually refetch the query. * `throwOnError` * When set to `true`, an error will be thrown if the query fails. * When set to `false`, an error will be logged if the query fails. * `cancelRefetch` * When set to `true`, a currently running request will be cancelled before a new request is made. * When set to `false`, no refetch will be made if there is already a request running. * Defaults to `true` ``` -------------------------------- ### useEnsText Options Source: https://wagmi.sh/react/api/hooks/useEnsText Configuration options for the useEnsText hook. ```APIDOC ## useEnsText Options ### retryDelay `number | ((retryAttempt: number, error: {{TError}}) => number) | undefined` * This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds. * A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff. * A function like `attempt => attempt * 1000` applies linear backoff. ### retryOnMount `boolean | undefined` If set to `false`, the query will not be retried on mount if it contains an error. Defaults to `true`. ### select `((data: {{TData}}) => unknown) | undefined` This option can be used to transform or select a part of the data returned by the query function. It affects the returned `data` value, but does not affect what gets stored in the query cache. ### staleTime `number | Infinity | undefined` * Defaults to `0` * The time in milliseconds after data is considered stale. This value only applies to the hook it is defined on. * If set to `Infinity`, the data will never be considered stale ### structuralSharing `boolean | (((oldData: {{TData}} | undefined, newData: {{TData}}) => {{TData}})) | undefined` * Defaults to `true` * If set to `false`, structural sharing between query results will be disabled. * If set to a function, the old and new data values will be passed through this function, which should combine them into resolved data for the query. This way, you can retain references from the old data to improve performance even when that data contains non-serializable values. ``` -------------------------------- ### Fetch All Contract Events Source: https://wagmi.sh/react/api/hooks/useContractEvents Fetch event logs for every event on a contract using its ABI. This is a broad query and typically requires further filtering. ```tsx import { useContractEvents } from 'wagmi' import { abi } from './abi' function App() { // Fetch event logs for every event on every ERC-20 contract. const result = useContractEvents({ abi }) } ``` -------------------------------- ### Import useTransactionCount Hook Source: https://wagmi.sh/react/api/hooks/useTransactionCount Import the useTransactionCount hook from the wagmi library. ```typescript import { useTransactionCount } from 'wagmi' ``` -------------------------------- ### Replace useBalance with token parameter using useReadContracts Source: https://wagmi.sh/react/guides/migrate-from-v1-to-v2 The `token` parameter is no longer supported in `useBalance`. Use `useReadContracts` to fetch token balances. ```typescript import { useBalance } from 'wagmi' // [!code --] import { useReadContracts } from 'wagmi' // [!code ++] import { erc20Abi } from 'viem' // [!code ++] const result = useBalance({ // [!code --] address: '0x4557B18E779944BFE9d78A672452331C186a9f48', // [!code --] token: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // [!code --] }) // [!code --] const result = useReadContracts({ // [!code ++] allowFailure: false, // [!code ++] contracts: [ // [!code ++] { address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // [!code ++] abi: erc20Abi, // [!code ++] functionName: 'balanceOf', // [!code ++] args: ['0x4557B18E779944BFE9d78A672452331C186a9f48'], // [!code ++] }, { address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // [!code ++] abi: erc20Abi, // [!code ++] functionName: 'decimals', // [!code ++] }, { address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // [!code ++] abi: erc20Abi, // [!code ++] functionName: 'symbol', // [!code ++] }, ] // [!code ++] }) // [!code ++] ``` -------------------------------- ### Configure retryDelay Source: https://wagmi.sh/react/api/transports/custom Set the base delay in milliseconds for exponential backoff retries. ```ts const transport = custom(provider, { retryDelay: 100, // [!code focus] }) ``` -------------------------------- ### Import UseConnectionsParameters Type Source: https://wagmi.sh/react/api/hooks/useConnections Import the UseConnectionsParameters type for defining hook parameters. ```typescript import { type UseConnectionsParameters } from 'wagmi' ``` -------------------------------- ### Configure custom Config for useWatchContractEvent Source: https://wagmi.sh/react/api/hooks/useWatchContractEvent Allows providing a specific Wagmi Config instance instead of using the one from the nearest WagmiProvider. ```tsx import { useWatchContractEvent } from 'wagmi' import { abi } from './abi' import { config } from './config' function App() { useWatchContractEvent({ address: '0x6b175474e89094c44da98b954eedeac495271d0f', abi, config, // [!code focus] eventName: 'Transfer', onLogs(logs) { console.log('New logs!', logs) }, }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Configure contract arguments Source: https://wagmi.sh/react/api/hooks/useReadContract Pass arguments to the contract function call, inferred from the provided ABI and function name. ```tsx // {"path":"/vercel/path0/site/react/api/hooks/useReadContract.md","from":3060,"to":3362} import { useReadContract } from 'wagmi' import { abi } from './abi' function App() { const result = useReadContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'balanceOf', args: ['0x6b175474e89094c44da98b954eedeac495271d0f'], // [!code focus] }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Basic Usage of useConnection Source: https://wagmi.sh/react/api/hooks/useConnection Retrieve the current connection state within a component. ```tsx import { useConnection } from 'wagmi' function App() { const connection = useConnection() } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Import useWaitForCallsStatus Hook Source: https://wagmi.sh/react/api/hooks/useWaitForCallsStatus Import the `useWaitForCallsStatus` hook from the 'wagmi' library. ```typescript import { useWaitForCallsStatus } from 'wagmi' ``` -------------------------------- ### Configure Hook with Custom Config Source: https://wagmi.sh/react/api/hooks/useDeployContract Pass a custom Wagmi config to the hook instead of using the default provider context. ```tsx import { useDeployContract } from 'wagmi' import { config } from './config' // [!code focus] function App() { const deployContract = useDeployContract({ config, // [!code focus] }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Import UseWatchBlockNumberReturnType Source: https://wagmi.sh/react/api/hooks/useWatchBlockNumber Import the return type for the useWatchBlockNumber hook to handle watcher cleanup. ```ts import { type UseWatchBlockNumberReturnType } from 'wagmi' ``` -------------------------------- ### Fetch Contract Events by Address Source: https://wagmi.sh/react/api/hooks/useContractEvents Scope event log fetching to a specific contract address. Ensure the address is correctly formatted. ```tsx import { useContractEvents } from 'wagmi' import { abi } from './abi' function App() { const result = useContractEvents({ address: '0x6b175474e89094c44da98b954eedeac495271d0f', // [!code focus] abi, }) } ``` -------------------------------- ### Basic Usage of useWaitForCallsStatus Source: https://wagmi.sh/react/api/hooks/useWaitForCallsStatus Use the `useWaitForCallsStatus` hook with a call bundle ID to wait for its confirmation. Ensure you have a wagmi configuration set up. ```tsx import { useWaitForCallsStatus } from 'wagmi' function App() { const result = useWaitForCallsStatus({ id: '0x...', // [!code focus] }) } ``` ```typescript import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### meta Source: https://wagmi.sh/react/api/hooks/useEnsResolver Stores additional information on the query cache entry. ```APIDOC ## meta ### Description If set, stores additional information on the query cache entry that can be used as needed. It will be accessible wherever the `query` is available, and is also part of the `QueryFunctionContext` provided to the `queryFn`. ### Type `Record | undefined` ``` -------------------------------- ### Import MockParameters type Source: https://wagmi.sh/react/api/connectors/mock Import the type definition for mock connector parameters. ```ts-vue import { type MockParameters } from '{{connectorsPackageName}}' ``` -------------------------------- ### Configure Wagmi for SSR in Next.js App Router Source: https://wagmi.sh/react/guides/ssr Set up Wagmi configuration for server-side rendering by enabling `ssr` and configuring `cookieStorage`. This ensures state is correctly handled across server and client. ```typescript import { createConfig, http, cookieStorage, createStorage } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export function getConfig() { return createConfig({ chains: [mainnet, sepolia], ssr: true, storage: createStorage({ storage: cookieStorage, }), transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) } ``` -------------------------------- ### refetchIntervalInBackground Source: https://wagmi.sh/react/api/hooks/useEnsResolver Determines if queries should refetch while the tab/window is in the background. ```APIDOC ## refetchIntervalInBackground ### Description If set to `true`, queries that are set to continuously refetch with a `refetchInterval` will continue to refetch while their tab/window is in the background. ### Type `boolean | undefined` ``` -------------------------------- ### TanStack Query Imports Source: https://wagmi.sh/react/api/hooks/useEnsName Standard import patterns for TanStack Query types and keys in Wagmi React. ```APIDOC ## TanStack Query Imports ### Description Use these imports to access query types and options for specific actions. ### Code Example ```ts import { type {{typeName}}Data, type {{typeName}}Options, type {{typeName}}QueryFnData, type {{typeName}}QueryKey, {{actionName}}QueryKey, {{actionName}}QueryOptions, } from '{{packageName}}/query' ``` ``` -------------------------------- ### Import UseReadContractsReturnType Source: https://wagmi.sh/react/api/hooks/useReadContracts Import the return type definition for the useReadContracts hook. ```typescript import { type UseReadContractsReturnType } from 'wagmi' ``` -------------------------------- ### Check if Query is Loading Source: https://wagmi.sh/react/api/hooks/useWaitForTransactionReceipt The `isLoading` flag is true during the initial fetch of a query. It is equivalent to `isFetching && isPending`. ```typescript isLoading: boolean ``` -------------------------------- ### Access Chain-Specific Parameters Source: https://wagmi.sh/react/guides/chain-properties Access chain-specific properties like Celo's feeCurrency after registering the config. ```ts import { parseEther } from 'viem' import { useSimulateContract } from 'wagmi' const result = useSimulateContract({ to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), feeCurrency: '0x…', // [!code focus] }) ``` -------------------------------- ### Configure custom config parameter Source: https://wagmi.sh/react/api/hooks/useCall Allows providing a specific Wagmi Config instance instead of using the nearest provider. ```tsx // {"path":"/vercel/path0/site/react/api/hooks/useCall.md","from":7519,"to":7852} import { useCall } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useCall({ config, // [!code focus] account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Enable Batch JSON-RPC Source: https://wagmi.sh/react/api/transports/http Enable Batch JSON-RPC by setting the `batch` flag to `true` in the http transport options. This allows multiple JSON-RPC requests to be sent in a single HTTP request. ```typescript const transport = http('https://foo-bar-baz.quiknode.pro/...', { batch: true // [!code hl] }) ``` -------------------------------- ### Import UseReconnectParameters Type Source: https://wagmi.sh/react/api/hooks/useReconnect Import the UseReconnectParameters type for defining hook parameters. ```typescript import { type UseReconnectParameters } from 'wagmi' ``` -------------------------------- ### useWatchBlocks Configuration Source: https://wagmi.sh/react/api/hooks/useWatchBlocks Configuration options for the useWatchBlocks hook, including polling frequency and chain synchronization settings. ```APIDOC ## useWatchBlocks Configuration ### Parameters #### Request Body - **pollingInterval** (number) - Optional - Polling frequency in milliseconds. Defaults to the Config's pollingInterval. - **syncConnectedChain** (boolean) - Optional - Set up subscriber for connected chain changes. Defaults to Config['syncConnectedChain']. ### Request Example { "pollingInterval": 1000, "syncConnectedChain": false } ``` -------------------------------- ### Configure WalletConnect qrModalOptions Source: https://wagmi.sh/react/api/connectors/walletConnect Customizes the appearance and behavior of the QR code modal. ```ts-vue import { walletConnect } from '{{connectorsPackageName}}' const connector = walletConnect({ projectId: '3fcc6bba6f1de962d911bb5b5c3dba68', qrModalOptions: { // [!code focus] themeMode: 'dark', // [!code focus] }, // [!code focus] }) ``` -------------------------------- ### Basic Usage of useBlockNumber Source: https://wagmi.sh/react/api/hooks/useBlockNumber Basic implementation of the hook within a React component. ```tsx import { useBlockNumber } from 'wagmi' function App() { const result = useBlockNumber() } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Provide Arguments for Contract Function Source: https://wagmi.sh/react/api/hooks/useSimulateContract The `args` parameter accepts an array of arguments to pass to the contract function. These are inferred from the ABI and function name. ```tsx import { useSimulateContract } from 'wagmi' import { abi } from './abi' function App() { const result = useSimulateContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ // [!code focus] '0xd2135CfB216b74109775236E36d4b433F1DF507B', // [!code focus] '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', // [!code focus] 123n, // [!code focus] ], // [!code focus] }) } ``` -------------------------------- ### subscribe Source: https://wagmi.sh/react/api/createConfig Listens for state changes matching a selector function. ```APIDOC ## subscribe ### Description Listens for state changes matching the selector function. Returns an unsubscribe function. ### Parameters #### Request Body - **selector** (function) - Required - Function to select a slice of the state. - **listener** (function) - Required - Callback function triggered on state change. - **options** (object) - Optional - Configuration for subscription (emitImmediately, equalityFn). ### Request Example ```ts const unsubscribe = config.subscribe( (state) => state.chainId, (chainId) => console.log(`Chain ID changed to ${chainId}`), ) ``` ``` -------------------------------- ### Import useEnsName Hook Source: https://wagmi.sh/react/api/hooks/useEnsName Import the useEnsName hook from the wagmi library. ```typescript import { useEnsName } from 'wagmi' ``` -------------------------------- ### Define a Custom Chain Source: https://wagmi.sh/react/api/chains Create a chain object by implementing the Chain type from viem. This object includes essential network details like ID, name, native currency, RPC URLs, and contract addresses. ```typescript import { type Chain } from 'viem' export const mainnet = { id: 1, name: 'Ethereum', nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 }, rpcUrls: { default: { http: ['https://eth.merkle.io'] }, }, blockExplorers: { default: { name: 'Etherscan', url: 'https://etherscan.io' }, }, contracts: { ensRegistry: { address: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e', }, ensUniversalResolver: { address: '0xE4Acdd618deED4e6d2f03b9bf62dc6118FC9A4da', blockCreated: 16773775, }, multicall3: { address: '0xca11bde05977b3631167028862be2a173976ca11', } } } ``` -------------------------------- ### Basic Usage Source: https://wagmi.sh/react/api/hooks/useBalance Fetch the balance for a specific address. ```tsx import { useBalance } from 'wagmi' function App() { const result = useBalance({ address: '0x4557B18E779944BFE9d78A672452331C186a9f48', }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### useWatchAsset Hook Source: https://wagmi.sh/react/api/hooks/useWatchAsset The useWatchAsset hook returns a mutation function to request that a user tracks a token in their wallet. ```APIDOC ## useWatchAsset ### Description Hook for requesting user tracks the token in their wallet. Returns a boolean indicating if the token was successfully added. ### Parameters #### config - **config** (Config | undefined) - Optional - Config to use instead of retrieving from the nearest WagmiProvider. #### mutation - **gcTime** (number | Infinity | undefined) - Optional - The time in milliseconds that unused/inactive cache data remains in memory. - **meta** (Record | undefined) - Optional - Stores additional information on the mutation cache entry. - **networkMode** ('online' | 'always' | 'offlineFirst' | undefined) - Optional - Defines the network mode for the mutation. - **onError** (Function) - Optional - Callback function fired if the mutation encounters an error. - **onMutate** (Function) - Optional - Callback function fired before the mutation function is fired. - **onSuccess** (Function) - Optional - Callback function fired when the mutation is successful. - **onSettled** (Function) - Optional - Callback function fired when the mutation is either successfully fetched or encounters an error. ### Request Example ```tsx const { watchAsset } = useWatchAsset() watchAsset({ type: 'ERC20', options: { address: '0x0000000000000000000000000000000000000000', symbol: 'WAGMI', decimals: 18, }, }) ``` ``` -------------------------------- ### Usage with config parameter Source: https://wagmi.sh/react/api/hooks/useTransactionReceipt Provide a custom wagmi config instead of using the nearest WagmiProvider. ```tsx import { useTransactionReceipt } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useTransactionReceipt({ config, // [!code focus] hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', }) } ``` ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` -------------------------------- ### Migrate connector access from useDisconnect and useSwitchConnection Source: https://wagmi.sh/react/guides/migrate-from-v2-to-v3 Replace direct connector access from useDisconnect or useSwitchConnection with the useConnections hook. ```typescript import { useDisconnect, useSwitchConnection } from 'wagmi' // [!code --] import { useConnections } from 'wagmi' // [!code ++] const { connectors } = useDisconnect() // [!code --] const { connectors } = useSwitchConnection() // [!code --] const connections = useConnections() // [!code ++] const connectors = connections.map((connection) => connection.connector) // [!code ++] ``` -------------------------------- ### useReadContracts Hook Parameters Source: https://wagmi.sh/react/api/hooks/useReadContracts This section details the various parameters available for the useReadContracts hook, including args, chainId, allowFailure, batchSize, and blockNumber. ```APIDOC ## useReadContracts Hook Parameters ### args Arguments to pass when calling the contract. Inferred from `abi` and `functionName`. #### Parameters - **args** (unknown[]) - Required - Arguments to pass when calling the contract. ### chainId ID of chain to use when fetching data. #### Parameters - **chainId** (number) - Optional - ID of chain to use when fetching data. ### allowFailure Whether or not the Hook should throw if a call reverts. If set to `true` (default), and a call reverts, then `useReadContracts` will fail silently and its error will be logged in the results array. Defaults to `true`. #### Parameters - **allowFailure** (boolean) - Optional - Whether or not the Hook should throw if a call reverts. ### batchSize The maximum size (in bytes) for each calldata chunk. Set to `0` to disable the size limit. Defaults to `1024`. > Note: Some RPC Providers limit the amount of calldata (`data`) that can be sent in a single `eth_call` request. It is best to check with your RPC Provider to see if there are any calldata size limits to `eth_call` requests. #### Parameters - **batchSize** (number) - Optional - The maximum size (in bytes) for each calldata chunk. ### blockNumber The block number to perform the read against. #### Parameters - **blockNumber** (number) - Optional - The block number to perform the read against. ``` -------------------------------- ### custom Transport Source: https://wagmi.sh/react/api/transports/custom The `custom` Transport connects to a JSON-RPC API via custom logic. It wraps Viem's `custom` Transport. ```APIDOC ## POST /react/api/transports/custom ### Description Connects to a JSON-RPC API via custom logic. Wraps Viem's `custom` Transport. ### Method POST ### Endpoint /react/api/transports/custom ### Parameters #### Request Body - **provider** (object) - Required - An EIP-1193 `request` function. - **key** (string) - Optional - A key for the Transport. Defaults to "custom". - **name** (string) - Optional - A name for the Transport. Defaults to "Ethereum Provider". - **retryCount** (number) - Optional - The max number of times to retry when a request fails. Defaults to 3. - **retryDelay** (number) - Optional - The base delay (in ms) between retries. Defaults to exponential backoff. ### Request Example ```json { "provider": { "request": "async ({ method, params }) => { ... }" }, "key": "customKey", "name": "My Custom Provider", "retryCount": 5, "retryDelay": 100 } ``` ### Response #### Success Response (200) - **transport** (object) - The configured custom transport instance. #### Response Example ```json { "transport": "{ ... custom transport object ... }" } ``` ``` -------------------------------- ### useFeeHistory Hook Source: https://wagmi.sh/react/api/hooks/useFeeHistory Hook for fetching a collection of historical gas information. ```APIDOC ## useFeeHistory ### Description Hook for fetching a collection of historical gas information. ### Import ```ts import { useFeeHistory } from 'wagmi' ``` ### Usage ```tsx import { useFeeHistory } from 'wagmi' function App() { const result = useFeeHistory({ blockCount: 4, rewardPercentiles: [25, 75] }) } ``` ### Parameters #### blockCount `number | undefined` Number of blocks in the requested range. Between 1 and 1024 blocks can be requested in a single query. Less than requested may be returned if not all blocks are available. ```tsx useFeeHistory({ blockCount: 4, // [!code focus] rewardPercentiles: [25, 75] }) ``` #### rewardPercentiles `number[] | undefined` A monotonically increasing list of percentile values to sample from each block's effective priority fees per gas in ascending order, weighted by gas used. ```tsx useFeeHistory({ blockCount: 4, rewardPercentiles: [25, 75] // [!code focus] }) ``` #### blockNumber `bigint | undefined` Highest number block of the requested range. ```tsx useFeeHistory({ blockCount: 4, blockNumber: 1551231n, // [!code focus] rewardPercentiles: [25, 75] }) ``` #### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag of the highest number block of the requested range. ```tsx useFeeHistory({ blockCount: 4, blockTag: 'safe', // [!code focus] rewardPercentiles: [25, 75] }) ``` #### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ```tsx import { mainnet } from '@wagmi/core/chains' useFeeHistory({ blockCount: 4, chainId: mainnet.id, // [!code focus] rewardPercentiles: [25, 75] }) ``` ``` -------------------------------- ### Basic Usage of useBlockTransactionCount Source: https://wagmi.sh/react/api/hooks/useBlockTransactionCount Demonstrates the basic usage of the useBlockTransactionCount hook without any parameters. It fetches the transaction count for the latest block by default. ```tsx import { useBlockTransactionCount } from 'wagmi' function App() { const result = useBlockTransactionCount() } ``` -------------------------------- ### Refetch Interval Source: https://wagmi.sh/react/api/hooks/useReadContracts Configures the interval at which queries are refetched. ```APIDOC ## refetchInterval ### Description If set to a number, all queries will continuously refetch at this frequency in milliseconds. If set to a function, the function will be executed with the latest data and query to compute a frequency. ### Type `number | false | ((data: TData | undefined, query: Query) => number | false | undefined) | undefined` ``` -------------------------------- ### Display Connection Information Source: https://wagmi.sh/react/guides/connect-wallet Use hooks like `useConnection`, `useEnsAvatar`, and `useEnsName` to display the connected wallet's address, ENS name, and avatar. Includes a button to disconnect the wallet. ```tsx import { useConnection, useDisconnect, useEnsAvatar, useEnsName } from 'wagmi' export function Connection() { const { address } = useConnection() const { disconnect } = useDisconnect() const { data: ensName } = useEnsName({ address }) const { data: ensAvatar } = useEnsAvatar({ name: ensName! }) return (
{ensAvatar && ENS Avatar} {address &&
{ensName ? `${ensName} (${address})` : address}
}
) } ``` -------------------------------- ### refetchOnReconnect Source: https://wagmi.sh/react/api/hooks/useEnsResolver Configures refetching behavior when the network connection is re-established. ```APIDOC ## refetchOnReconnect ### Description If set to `true`, the query will refetch on reconnect if the data is stale. If set to `false`, the query will not refetch on reconnect. If set to `'always'`, the query will always refetch on reconnect. If set to a function, the function will be executed with the query to compute the value. ### Type `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` ### Default `true` ``` -------------------------------- ### useVerifyTypedData Hook Parameters Source: https://wagmi.sh/react/api/hooks/useVerifyTypedData Details regarding the configuration parameters for the useVerifyTypedData hook. ```APIDOC ## useVerifyTypedData Parameters ### signature - **Type**: Hex | ByteArray | undefined - **Description**: The signature that was generated by signing the typed data with the address's signer. ### chainId - **Type**: config['chains'][number]['id'] | undefined - **Description**: Only used when verifying a typed data that was signed by a Smart Contract Account. The ID of the chain to check if the contract was already deployed. ``` -------------------------------- ### MetaMask Connector API Source: https://wagmi.sh/react/api/connectors/metaMask The MetaMask connector allows your dApp to interact with the MetaMask browser extension. ```APIDOC ## metaMask Connector Connector for [MetaMask Connect](https://github.com/MetaMask/connect-monorepo). ### Import ```ts import { metaMask } from '{{connectorsPackageName}}' ``` ### Install ::: code-group ```bash [pnpm] pnpm add @metamask/connect-evm@{{connectorDependencyVersion}} ``` ```bash [npm] npm install @metamask/connect-evm@{{connectorDependencyVersion}} ``` ```bash [yarn] yarn add @metamask/connect-evm@{{connectorDependencyVersion}} ``` ```bash [bun] bun add @metamask/connect-evm@{{connectorDependencyVersion}} ``` ::: ### Usage ```ts import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' import { metaMask } from '{{connectorsPackageName}}' export const config = createConfig({ chains: [mainnet, sepolia], connectors: [metaMask()], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` ### Parameters #### dapp `DappMetadata | undefined` Metadata is used to fill details for the UX on confirmation screens in MetaMask, including the following fields: * `name`: `string` - The name of the dapp. * `url`: `string` - URL of the dapp (defaults to `window.location.origin`). * `iconUrl`: `string` - URL to the dapp's favicon or icon. Defaults to `{ name: window.location.hostname }`. ```ts import { metaMask } from '{{connectorsPackageName}}' const connector = metaMask({ dapp: { name: 'My Wagmi App', url: 'https://example.com', iconUrl: 'https://example.com/favicon.ico', } }) ``` #### debug `boolean | undefined` Enables debug mode for the MetaMask SDK. When enabled, provides additional logging and debugging information. ```ts import { metaMask } from '{{connectorsPackageName}}' const connector = metaMask({ debug: true }) ``` #### connectAndSign `string | undefined` Shortcut to connect and sign a message in a single operation. When provided, the connector will connect to MetaMask and immediately prompt the user to sign the specified message. This parameter is mutually exclusive with `connectWith` - only one can be used at a time. ```ts import { metaMask } from '{{connectorsPackageName}}' const connector = metaMask({ connectAndSign: 'Sign this message to connect', }) ``` #### connectWith `{ method: string; params: unknown[] } | undefined` Allows connecting with any RPC method. When provided, the connector will connect to MetaMask and immediately call the specified RPC method with the given parameters. This parameter is mutually exclusive with `connectAndSign` - only one can be used at a time. ```ts import { metaMask } from '{{connectorsPackageName}}' const connector = metaMask({ connectWith: { method: 'eth_requestAccounts', params: [], } }) ``` ### Advanced By default, if the EIP-6963 MetaMask injected provider is detected, this connector will replace it. EIP-6963 defines a standard way for dapps to interact with multiple wallets simultaneously by injecting providers into the browser. Wallets that implement this standard can make their presence known to dapps in a consistent and predictable manner. See the [`rdns` property](https://wagmi.sh/dev/creating-connectors#properties) for more information. ``` -------------------------------- ### Import useSignMessage Hook Source: https://wagmi.sh/react/api/hooks/useSignMessage Import the useSignMessage hook from the wagmi library. ```typescript import { useSignMessage } from 'wagmi' ```