From 4b900be61e9e5af7703780f8272e91453a698fb3 Mon Sep 17 00:00:00 2001 From: Tom Meagher Date: Fri, 13 Oct 2023 13:49:34 -0400 Subject: [PATCH] docs: progress --- docs/.vitepress/sidebar.ts | 10 +- docs/cli/config/options.md | 24 +- docs/core/api/actions/estimateFeesPerGas.md | 48 +-- docs/core/api/actions/getBlock.md | 4 + docs/core/api/actions/getTransaction.md | 102 +----- docs/core/api/actions/readContract.md | 79 ----- docs/core/api/actions/sendTransaction.md | 2 +- docs/core/api/actions/signMessage.md | 2 +- docs/core/api/actions/signTypedData.md | 2 +- docs/core/api/actions/simulateContract.md | 2 + .../api/actions/waitForTransactionReceipt.md | 23 +- docs/core/api/actions/watchBlockNumber.md | 89 ++++- docs/core/api/actions/watchBlocks.md | 10 +- docs/core/api/actions/watchContractEvent.md | 327 ++++++++++++++++++ .../api/actions/watchPendingTransactions.md | 4 +- docs/core/api/actions/writeContract.md | 2 +- docs/core/api/createConnector.md | 18 +- docs/core/guides/migrate-from-v1-to-v2.md | 43 ++- docs/index.md | 3 + .../api/hooks/useWaitForTransactionReceipt.md | 3 +- docs/react/guides/migrate-from-v1-to-v2.md | 38 ++ docs/shared/connectors/ledger.md | 20 +- docs/shared/faq.md | 2 +- docs/shared/query-options.md | 18 +- docs/snippets/abi-event.ts | 20 ++ .../core/src/actions/estimateFeesPerGas.ts | 2 + packages/core/src/actions/getBalance.ts | 2 + packages/core/src/actions/getToken.ts | 1 + .../core/src/connectors/createConnector.ts | 4 +- packages/react/src/hooks/useToken.ts | 6 +- 30 files changed, 632 insertions(+), 278 deletions(-) create mode 100644 docs/snippets/abi-event.ts diff --git a/docs/.vitepress/sidebar.ts b/docs/.vitepress/sidebar.ts index 6033234018..7325fcb7ec 100644 --- a/docs/.vitepress/sidebar.ts +++ b/docs/.vitepress/sidebar.ts @@ -14,7 +14,7 @@ export function getSidebar() { ], }, { - text: 'Guides 🚧', + text: 'Guides', items: [ { text: 'TanStack Query', @@ -251,7 +251,7 @@ export function getSidebar() { ], }, { - text: 'Guides 🚧', + text: 'Guides', items: [ { text: 'Viem', @@ -287,7 +287,7 @@ export function getSidebar() { text: 'Configuration', items: [ { text: 'createConfig', link: '/core/api/createConfig' }, - { text: 'createConnector 🚧', link: '/core/api/createConnector' }, + { text: 'createConnector', link: '/core/api/createConnector' }, { text: 'createStorage', link: '/core/api/createStorage' }, { text: 'Chains', link: '/core/api/chains' }, { @@ -338,7 +338,7 @@ export function getSidebar() { { text: 'getAccount', link: '/core/api/actions/getAccount' }, { text: 'getBalance', link: '/core/api/actions/getBalance' }, { - text: 'getBlock 🚧', + text: 'getBlock', link: '/core/api/actions/getBlock', }, { @@ -455,7 +455,7 @@ export function getSidebar() { link: '/core/api/actions/watchConnectors', }, { - text: 'watchContractEvent 🚧', + text: 'watchContractEvent', link: '/core/api/actions/watchContractEvent', }, { diff --git a/docs/cli/config/options.md b/docs/cli/config/options.md index 4c09514554..cced239f0e 100644 --- a/docs/cli/config/options.md +++ b/docs/cli/config/options.md @@ -13,8 +13,9 @@ Array of contracts to use when running [commands](/cli/api/commands). `abi` and `Address | Record | undefined` Contract address or addresses. Accepts an object `{ [chainId]: address }` for targeting specific chains. - -```ts {6,11-14} filename="wagmi.config.ts" + +::: code-group +```ts {6,11-14} [wagmi.config.ts] export default { out: 'src/generated.ts', contracts: [ @@ -34,6 +35,7 @@ export default { ], } ``` +::: ### abi @@ -41,7 +43,8 @@ export default { ABI for contract. Used by [plugins](/cli/plugins) to generate code base on properties. -```ts {5} filename="wagmi.config.ts" +::: code-group +```ts {5} [wagmi.config.ts] export default { out: 'src/generated.ts', contracts: [ @@ -52,6 +55,7 @@ export default { ], } ``` +::: ### name @@ -59,7 +63,8 @@ export default { Name of contract. Must be unique. Used by [plugins](/cli/plugins) to name generated code. -```ts {6} filename="wagmi.config.ts" +::: code-group +```ts {6} [wagmi.config.ts] export default { out: 'src/generated.ts', contracts: [ @@ -70,6 +75,7 @@ export default { ], } ``` +::: ## out @@ -77,7 +83,8 @@ export default { Path to output generated code. Must be unique per config. Use an [Array Config](/cli/configuration/configuring-cli#array-config) for multiple outputs. -```ts {2} filename="wagmi.config.ts" +::: code-group +```ts {2} [wagmi.config.ts] export default { out: 'src/generated.ts', contracts: [ @@ -88,6 +95,7 @@ export default { ], } ``` +::: ## plugins @@ -97,7 +105,8 @@ Plugins to use and their configuration. Wagmi CLI has multiple [built-in plugins](/cli/api/plugins) that are used to manage ABIs, generate code, etc. -```ts {1,5-20} filename="wagmi.config.ts" +::: code-group +```ts {1,5-20} [wagmi.config.ts] import { etherscan, react } from '@wagmi/cli/plugins' export default { @@ -119,4 +128,5 @@ export default { react(), ], } -``` \ No newline at end of file +``` +::: \ No newline at end of file diff --git a/docs/core/api/actions/estimateFeesPerGas.md b/docs/core/api/actions/estimateFeesPerGas.md index 34e14e24ab..ce804efeb9 100644 --- a/docs/core/api/actions/estimateFeesPerGas.md +++ b/docs/core/api/actions/estimateFeesPerGas.md @@ -21,23 +21,7 @@ import { estimateFeesPerGas } from '@wagmi/core' import { estimateFeesPerGas } from '@wagmi/core' import { config } from './config' -const { - maxFeePerGas, - maxPriorityFeePerGas -} = await estimateFeesPerGas(config) -/** - * { - * maxFeePerGas: 15_000_000_000n, - * maxPriorityFeePerGas: 1_000_000_000n, - * } - */ - -const { gasPrice } = await estimateFeesPerGas(config, { - type: 'legacy' -}) -/** - * { gasPrice: 15_000_000_000n } - */ +const result = await estimateFeesPerGas(config) ``` <<< @/snippets/core/config.ts[config.ts] ::: @@ -60,7 +44,7 @@ import { estimateFeesPerGas } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { config } from './config' -const feesPerGas = await estimateFeesPerGas(config, { +const result = await estimateFeesPerGas(config, { chainId: mainnet.id, // [!code focus] }) ``` @@ -88,16 +72,17 @@ const feesPerGas = estimateFeesPerGas(config, { ### type -`"legacy" | "eip1559"` +`'legacy' | 'eip1559'` -- Defaults to `"eip1559"` +- Fee value type. +- Defaults to `'eip1559'` ::: code-group ```ts [index.ts] import { estimateFeesPerGas } from '@wagmi/core' import { config } from './config' -const feesPerGas = estimateFeesPerGas(config, { +const result = estimateFeesPerGas(config, { type: 'legacy', // [!code focus] }) ``` @@ -110,8 +95,12 @@ const feesPerGas = estimateFeesPerGas(config, { import { type EstimateFeesPerGasReturnType } from '@wagmi/core' ``` -### formatted +[`FeeValues`](https://viem.sh/docs/glossary/types.html#feevalues) + +An estimate (in wei) for the fees per gas. +### formatted + `{ gasPrice: string | undefined; maxFeePerGas: string | undefined; maxPriorityFeePerGas: string | undefined; }` Object of formatted values using [`formatUnits`](#formatunits). @@ -120,25 +109,22 @@ Object of formatted values using [`formatUnits`](#formatunits). `bigint | undefined` -> Value is `undefined` if [`type`](#type) is `"eip1559"`. - -Gas price. +- Gas price. +- When [`type`](#type) is `'eip1559'`, value is `undefined`. ### maxFeePerGas `bigint | undefined` -> Value is `undefined` if [`type`](#type) is `"legacy"`. - -Max fee per gas. +- Max fee per gas. +- When [`type`](#type) is `'legacy'`, value is `undefined`. ### maxPriorityFeePerGas `bigint | undefined` -> Value is `undefined` if [`type`](#type) is `"legacy"`. - -Max priority fee per gas. +- Max priority fee per gas. +- When [`type`](#type) is `'legacy'`, value is `undefined`. ## Error diff --git a/docs/core/api/actions/getBlock.md b/docs/core/api/actions/getBlock.md index 517ceae5ac..980b026247 100644 --- a/docs/core/api/actions/getBlock.md +++ b/docs/core/api/actions/getBlock.md @@ -129,6 +129,10 @@ const blockNumber = await getBlock(config, { import { type GetBlockReturnType } from '@wagmi/core' ``` +[`Block`](https://viem.sh/docs/glossary/types.html#block) + +Information about the block. + ## Error ```ts diff --git a/docs/core/api/actions/getTransaction.md b/docs/core/api/actions/getTransaction.md index 992864ac54..8ebe770990 100644 --- a/docs/core/api/actions/getTransaction.md +++ b/docs/core/api/actions/getTransaction.md @@ -158,107 +158,7 @@ const transaction = getTransaction(config, { import { type GetTransactionReturnType } from '@wagmi/core' ``` -### accessList - -`AccessList | undefined` - -Access list for EIP-1559 or EIP-2930 transactions. - -### blockHash - -`` `0x${string}` | null `` - -Hash of block containing this transaction or `null` if pending. - -### blockNumber - -`bigint | null` - -Number of block containing this transaction or `null` if pending. - -### chainId - -`number | undefined` - -Chain ID where transaction took place. - -### from - -`Address` - -Transaction sender. - -### gas - -`bigint` - -Gas provided for transaction execution. - -### hash - -`` `0x${string}` `` - -Hash of this transaction. - -### input - -`` `0x${string}` `` - -Contract code or a hashed method call. - -### nonce - -`number` - -Unique number identifying this transaction. - -### r - -`` `0x${string}` `` - -ECDSA signature r. - -### s - -`` `0x${string}` `` - -ECDSA signature s. - -### to - -`Address | null` - -Transaction recipient or `null` if deploying a contract. - -### transactionIndex - -`number | null` - -Index of this transaction in the block or `null` if pending. - -### type - -`'legacy' | 'eip1559' | 'eip2930'` - -Transaction type. - -### typeHex - -`` `0x${string}` | null `` - -The type represented as hex. - -### v - -`bigint` - -ECDSA recovery ID. - -### value - -`bigint` - -Value in wei sent with this transaction. +[`Transaction`](https://viem.sh/docs/glossary/types.html#transaction) ## Error diff --git a/docs/core/api/actions/readContract.md b/docs/core/api/actions/readContract.md index 3df45faec9..b8da42ae8a 100644 --- a/docs/core/api/actions/readContract.md +++ b/docs/core/api/actions/readContract.md @@ -245,85 +245,6 @@ import { type ReadContractReturnType } from '@wagmi/core' With [`abi`](#abi) setup correctly, TypeScript will infer the correct types for [`functionName`](#functionname), [`args`](#args), and the return type. See the Wagmi [TypeScript docs](/core/typescript) for more information. -::: code-group -```ts twoslash [Inline] -import { createConfig, http, readContract } from '@wagmi/core' -import { mainnet, sepolia } from '@wagmi/core/chains' - -const config = createConfig({ - chains: [mainnet, sepolia], - transports: { - [mainnet.id]: http(), - [sepolia.id]: http(), - }, -}) -// ---cut--- -const result = await readContract(config, { - // ^? - 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' }], - }, - ], - address: '0x6b175474e89094c44da98b954eedeac495271d0f', - functionName: 'balanceOf', - // ^? - args: ['0xd2135CfB216b74109775236E36d4b433F1DF507B'], - // ^? -}) -``` -```ts twoslash [Const-Asserted] -import { createConfig, http, readContract } from '@wagmi/core' -import { mainnet, sepolia } from '@wagmi/core/chains' - -const config = createConfig({ - chains: [mainnet, sepolia], - transports: { - [mainnet.id]: http(), - [sepolia.id]: http(), - }, -}) -// ---cut--- -const 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 - -const result = await readContract(config, { - // ^? - abi, - address: '0x6b175474e89094c44da98b954eedeac495271d0f', - functionName: 'balanceOf', - // ^? - args: ['0xd2135CfB216b74109775236E36d4b433F1DF507B'], - // ^? -}) -``` -::: - ## Error ```ts diff --git a/docs/core/api/actions/sendTransaction.md b/docs/core/api/actions/sendTransaction.md index edecca9bd2..564477dabf 100644 --- a/docs/core/api/actions/sendTransaction.md +++ b/docs/core/api/actions/sendTransaction.md @@ -324,7 +324,7 @@ const result = await sendTransaction(config, { import { type SendTransactionReturnType } from '@wagmi/core' ``` -`` `0x${string}` `` +[`Hash`](https://viem.sh/docs/glossary/types.html#hash) Transaction hash. diff --git a/docs/core/api/actions/signMessage.md b/docs/core/api/actions/signMessage.md index 8e89fec90d..f4a1ac148c 100644 --- a/docs/core/api/actions/signMessage.md +++ b/docs/core/api/actions/signMessage.md @@ -108,7 +108,7 @@ const result = await signMessage(config, { import { type SignMessageReturnType } from '@wagmi/core' ``` -`` `0x${string}` `` +[`Hex`](https://viem.sh/docs/glossary/types.html#hex) The signed message. diff --git a/docs/core/api/actions/signTypedData.md b/docs/core/api/actions/signTypedData.md index 2d391a89c4..abcf711cc8 100644 --- a/docs/core/api/actions/signTypedData.md +++ b/docs/core/api/actions/signTypedData.md @@ -275,7 +275,7 @@ const result = await signTypedData(config, { import { type SignTypedDataReturnType } from '@wagmi/core' ``` -`` `0x${string}` `` +[`Hex`](https://viem.sh/docs/glossary/types.html#hex) The signed data. diff --git a/docs/core/api/actions/simulateContract.md b/docs/core/api/actions/simulateContract.md index 43e7ff31bc..960de134c4 100644 --- a/docs/core/api/actions/simulateContract.md +++ b/docs/core/api/actions/simulateContract.md @@ -568,6 +568,8 @@ const result = await simulateContract(config, { import { type SimulateContractReturnType } from '@wagmi/core' ``` +The simulation result and write request. + ### request Write request that includes [parameters](#parameters). diff --git a/docs/core/api/actions/waitForTransactionReceipt.md b/docs/core/api/actions/waitForTransactionReceipt.md index a4698b24b5..853189055d 100644 --- a/docs/core/api/actions/waitForTransactionReceipt.md +++ b/docs/core/api/actions/waitForTransactionReceipt.md @@ -94,11 +94,11 @@ const transactionReceipt = await waitForTransactionReceipt(config, { <<< @/snippets/core/config.ts[config.ts] ::: -### pollingInterval +### hash -`number | undefined` +`` `0x${string}` `` -Polling frequency (in ms). Defaults to the [Config's `pollingInterval` config](/core/api/createConfig#pollinginterval). +The transaction hash to wait for. ::: code-group ```ts [index.ts] @@ -106,18 +106,18 @@ import { waitForTransactionReceipt } from '@wagmi/core' import { config } from './config' const transactionReceipt = await waitForTransactionReceipt(config, { - hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', - pollingInterval: 1_000, // [!code focus] + hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: -### hash +### pollingInterval -`` `0x${string}` `` +`number | undefined` -The transaction hash to wait for. +- Polling frequency (in milliseconds). +- Defaults to the [Config's `pollingInterval` config](/core/api/createConfig#pollinginterval). ::: code-group ```ts [index.ts] @@ -125,7 +125,8 @@ import { waitForTransactionReceipt } from '@wagmi/core' import { config } from './config' const transactionReceipt = await waitForTransactionReceipt(config, { - hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', // [!code focus] + hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', + pollingInterval: 1_000, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] @@ -137,6 +138,10 @@ const transactionReceipt = await waitForTransactionReceipt(config, { import { type WaitForTransactionReceiptReturnType } from '@wagmi/core' ``` +[`TransactionReceipt`](https://viem.sh/docs/glossary/types.html#transactionreceipt) + +The transaction receipt. + ## Error ```ts diff --git a/docs/core/api/actions/watchBlockNumber.md b/docs/core/api/actions/watchBlockNumber.md index 7f7ca41b87..7a59d6d37a 100644 --- a/docs/core/api/actions/watchBlockNumber.md +++ b/docs/core/api/actions/watchBlockNumber.md @@ -54,6 +54,47 @@ unwatch() <<< @/snippets/core/config.ts[config.ts] ::: +### emitOnBegin + +Whether or not to emit the latest block number to the callback when the subscription opens. + +::: code-group +```ts [index.ts] +import { watchBlockNumber } from '@wagmi/core' +import { config } from './config' + +const unwatch = watchBlockNumber(config, { + emitOnBegin: true, // [!code focus] + onBlockNumber(blockNumber) { + console.log('Block number changed!', blockNumber) + }, +}) +unwatch() +``` +<<< @/snippets/core/config.ts[config.ts] +::: + +### emitMissed + +Whether or not to emit the missed block numbers to the callback. + +::: code-group +```ts [index.ts] +import { watchBlockNumber } from '@wagmi/core' +import { config } from './config' + +const unwatch = watchBlockNumber(config, { + emitMissed: true, // [!code focus] + onBlockNumber(blockNumber) { + console.log('Block number changed!', blockNumber) + }, +}) +unwatch() +``` +<<< @/snippets/core/config.ts[config.ts] +::: + + ### onBlockNumber `(blockNumber: bigint, prevBlockNumber: bigint | undefined) => void` @@ -91,7 +132,7 @@ const unwatch = watchBlockNumber(config, { console.log('Block number changed!', blockNumber) }, onError(error) { // [!code focus] - console.error("Block number error", error) // [!code focus] + console.error('Block number error', error) // [!code focus] }, // [!code focus] }) unwatch() @@ -99,6 +140,52 @@ unwatch() <<< @/snippets/core/config.ts[config.ts] ::: +### poll + +`boolean` + +- 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. + +::: code-group +```ts [index.ts] +import { watchBlockNumber } from '@wagmi/core' +import { config } from './config' + +const unwatch = watchBlockNumber(config, { + onBlockNumber(blockNumber) { + console.log('Block number changed!', blockNumber) + }, + poll: true, // [!code focus] +}) +unwatch() +``` +<<< @/snippets/core/config.ts[config.ts] +::: + +### pollingInterval + +`number | undefined` + +- Polling frequency (in milliseconds). +- Defaults to the [Config's `pollingInterval` config](/core/api/createConfig#pollinginterval). + +::: code-group +```ts [index.ts] +import { watchBlockNumber } from '@wagmi/core' +import { config } from './config' + +const unwatch = watchBlockNumber(config, { + onBlockNumber(blockNumber) { + console.log('Block number changed!', blockNumber) + }, + pollingInterval: 1_000, // [!code focus] +}) +unwatch() +``` +<<< @/snippets/core/config.ts[config.ts] +::: + ### syncConnectedChain `boolean | undefined` diff --git a/docs/core/api/actions/watchBlocks.md b/docs/core/api/actions/watchBlocks.md index b567dfdb75..f4ca494724 100644 --- a/docs/core/api/actions/watchBlocks.md +++ b/docs/core/api/actions/watchBlocks.md @@ -159,7 +159,7 @@ const unwatch = watchBlocks(config, { console.log('Block changed!', block) }, onError(error) { // [!code focus] - console.error("Block error", error) // [!code focus] + console.error('Block error', error) // [!code focus] }, // [!code focus] }) unwatch() @@ -171,7 +171,8 @@ unwatch() `boolean` -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. +- 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. ::: code-group ```ts [index.ts] @@ -191,9 +192,10 @@ unwatch() ### pollingInterval -`number` +`number | undefined` -Polling frequency (in ms). +- Polling frequency (in milliseconds). +- Defaults to the [Config's `pollingInterval` config](/core/api/createConfig#pollinginterval). ::: code-group ```ts [index.ts] diff --git a/docs/core/api/actions/watchContractEvent.md b/docs/core/api/actions/watchContractEvent.md index f38653ef47..1ac68dcd6c 100644 --- a/docs/core/api/actions/watchContractEvent.md +++ b/docs/core/api/actions/watchContractEvent.md @@ -19,8 +19,20 @@ import { watchContractEvent } from '@wagmi/core' ::: code-group ```ts [index.ts] import { watchContractEvent } from '@wagmi/core' +import { abi } from './abi' import { config } from './config' + +const unwatch = watchContractEvent(config, { + address: '0x6b175474e89094c44da98b954eedeac495271d0f', + abi, + eventName: 'Transfer', + onLogs(logs) { + console.log('New logs!', logs) + }, +}) +unwatch() ``` +<<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: @@ -30,12 +42,327 @@ import { config } from './config' import { type WatchContractEventParameters } from '@wagmi/core' ``` +### abi + +`Abi` + +The contract's ABI. Check out the [TypeScript docs](/react/typescript#const-assert-abis-typed-data) for how to set up ABIs for maximum type inference and safety. + +::: code-group +```ts [index.ts] +import { watchContractEvent } from '@wagmi/core' +import { abi } from './abi' // [!code focus] +import { config } from './config' + +const unwatch = watchContractEvent(config, { + abi, // [!code focus] + onLogs(logs) { + console.log('Logs changed!', logs) + }, +}) +unwatch() +``` +<<< @/snippets/abi-event.ts[abi.ts] +<<< @/snippets/core/config.ts[config.ts] +::: + +### address + +`Address | undefined` + +The contract's address. + +::: code-group +```ts [index.ts] +import { watchContractEvent } from '@wagmi/core' +import { abi } from './abi' +import { config } from './config' + +const unwatch = watchContractEvent(config, { + address: '0x6b175474e89094c44da98b954eedeac495271d0f', // [!code focus] + abi, + onLogs(logs) { + console.log('Logs changed!', logs) + }, +}) +unwatch() +``` +<<< @/snippets/abi-event.ts[abi.ts] +<<< @/snippets/core/config.ts[config.ts] +::: + +### args + +`object | readonly unknown[] | undefined` + +- Arguments to pass when calling the contract. +- Inferred from [`abi`](#abi) and [`eventName`](#eventname). + +::: code-group +```ts [index.ts] +import { watchContractEvent } from '@wagmi/core' +import { abi } from './abi' +import { config } from './config' + +const unwatch = watchContractEvent(config, { + abi, + args: { // [!code focus] + to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', // [!code focus] + }, // [!code focus] + onLogs(logs) { + console.log('Logs changed!', logs) + }, +}) +unwatch() +``` +<<< @/snippets/abi-event.ts[abi.ts] +<<< @/snippets/core/config.ts[config.ts] +::: + +### batch + +`boolean | undefined` + +- Whether or not the transaction hashes should be batched on each invocation. +- Defaults to `true`. + +::: code-group +```ts [index.ts] +import { watchContractEvent } from '@wagmi/core' +import { abi } from './abi' +import { config } from './config' + +const unwatch = watchContractEvent(config, { + abi, + batch: false, // [!code focus] + onLogs(logs) { + console.log('Logs changed!', logs) + }, +}) +unwatch() +``` +<<< @/snippets/abi-event.ts[abi.ts] +<<< @/snippets/core/config.ts[config.ts] +::: + +### chainId + +`config['chains'][number]['id'] | undefined` + +ID of chain to use when fetching data. + +::: code-group +```ts [index.ts] +import { watchContractEvent } from '@wagmi/core' +import { mainnet } from '@wagmi/core/chains' +import { abi } from './abi' +import { config } from './config' + +const unwatch = watchContractEvent(config, { + abi, + chainId: mainnet.id, // [!code focus] + onLogs(logs) { + console.log('Logs changed!', logs) + }, +}) +unwatch() +``` +<<< @/snippets/abi-event.ts[abi.ts] +<<< @/snippets/core/config.ts[config.ts] +::: + +### eventName + +`string` + +- Event to listen for the contract. +- Inferred from [`abi`](#abi). + +::: code-group +```ts [index.ts] +import { watchContractEvent } from '@wagmi/core' +import { abi } from './abi' +import { config } from './config' + +const unwatch = watchContractEvent(config, { + abi, + eventName: 'Approval', // [!code focus] + onLogs(logs) { + console.log('Logs changed!', logs) + }, +}) +unwatch() +``` +<<< @/snippets/abi-event.ts[abi.ts] +<<< @/snippets/core/config.ts[config.ts] +::: + +### onError + +`((error: Error) => void) | undefined` + +Error thrown from getting the block number. + +::: code-group +```ts [index.ts] +import { watchContractEvent } from '@wagmi/core' +import { abi } from './abi' +import { config } from './config' + +const unwatch = watchContractEvent(config, { + abi, + onLogs(logs) { + console.log('Logs changed!', logs) + }, + onError(error) { // [!code focus] + console.error('Logs error', error) // [!code focus] + }, // [!code focus] +}) +unwatch() +``` +<<< @/snippets/abi-event.ts[abi.ts] +<<< @/snippets/core/config.ts[config.ts] +::: + +### onLogs + +`(logs: Log[], prevLogs: Log[] | undefined) => void` + +Callback for when logs changes. + +::: code-group +```ts [index.ts] +import { watchContractEvent } from '@wagmi/core' +import { abi } from './abi' +import { config } from './config' + +const unwatch = watchContractEvent(config, { + abi, + onLogs(logs) { // [!code focus] + console.log('Logs changed!', logs) // [!code focus] + }, // [!code focus] +}) +unwatch() +``` +<<< @/snippets/abi-event.ts[abi.ts] +<<< @/snippets/core/config.ts[config.ts] +::: + +### poll + +`boolean` + +- 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. + +::: code-group +```ts [index.ts] +import { watchContractEvent } from '@wagmi/core' +import { abi } from './abi' +import { config } from './config' + +const unwatch = watchContractEvent(config, { + abi, + onLogs(logs) { + console.log('Logs changed!', logs) + }, + poll: true, // [!code focus] +}) +unwatch() +``` +<<< @/snippets/abi-event.ts[abi.ts] +<<< @/snippets/core/config.ts[config.ts] +::: + +### pollingInterval + +`number | undefined` + +- Polling frequency (in milliseconds). +- Defaults to the [Config's `pollingInterval` config](/core/api/createConfig#pollinginterval). + +::: code-group +```ts [index.ts] +import { watchContractEvent } from '@wagmi/core' +import { abi } from './abi' +import { config } from './config' + +const unwatch = watchContractEvent(config, { + abi, + onLogs(logs) { + console.log('Logs changed!', logs) + }, + pollingInterval: 1_000, // [!code focus] +}) +unwatch() +``` +<<< @/snippets/abi-event.ts[abi.ts] +<<< @/snippets/core/config.ts[config.ts] +::: + +### strict + +`boolean | undefined` + +- Defaults to `false`. + +::: code-group +```ts [index.ts] +import { watchContractEvent } from '@wagmi/core' +import { abi } from './abi' +import { config } from './config' + +const unwatch = watchContractEvent(config, { + abi, + onLogs(logs) { + console.log('Logs changed!', logs) + }, + strict: true, // [!code focus] +}) +unwatch() +``` +<<< @/snippets/abi-event.ts[abi.ts] +<<< @/snippets/core/config.ts[config.ts] +::: + +### syncConnectedChain + +`boolean | undefined` + +- Set up subscriber for connected chain changes. +- Defaults to [`Config['syncConnectedChain']`](/core/createConfig#syncconnectedchain). + +::: code-group +```ts [index.ts] +import { watchContractEvent } from '@wagmi/core' +import { abi } from './abi' +import { config } from './config' + +const unwatch = watchContractEvent(config, { + abi, + onLogs(logs) { + console.log('Logs changed!', logs) + }, + syncConnectedChain: false, // [!code focus] +}) +unwatch() +``` +<<< @/snippets/abi-event.ts[abi.ts] +<<< @/snippets/core/config.ts[config.ts] +::: + ## Return Type ```ts import { type WatchContractEventReturnType } from '@wagmi/core' ``` +Function for cleaning up watcher. + +## Type Inference + +With [`abi`](#abi) setup correctly, TypeScript will infer the correct types for [`eventName`](#eventname), [`args`](#args), and [`onLogs`](#onlogs) parameters. See the Wagmi [TypeScript docs](/core/typescript) for more information. + ## Error ```ts diff --git a/docs/core/api/actions/watchPendingTransactions.md b/docs/core/api/actions/watchPendingTransactions.md index a911390c47..2970a7f1ea 100644 --- a/docs/core/api/actions/watchPendingTransactions.md +++ b/docs/core/api/actions/watchPendingTransactions.md @@ -23,7 +23,7 @@ import { config } from './config' const unwatch = watchPendingTransactions(config, { onTransactions(transactions) { - console.log("New transactions!", transactions) + console.log('New transactions!', transactions) }, }) ``` @@ -53,7 +53,7 @@ import { config } from './config' const unswatch = watchPendingTransactions(config, { chainId: mainnet.id, // [!code focus] onTransactions(transactions) { - console.log("New transactions!", transactions) + console.log('New transactions!', transactions) }, }) ``` diff --git a/docs/core/api/actions/writeContract.md b/docs/core/api/actions/writeContract.md index 1043d07303..5064b9a4df 100644 --- a/docs/core/api/actions/writeContract.md +++ b/docs/core/api/actions/writeContract.md @@ -511,7 +511,7 @@ const result = await writeContract(config, { import { type WriteContractReturnType } from '@wagmi/core' ``` -`` `0x${string}` `` +[`Hash`](https://viem.sh/docs/glossary/types.html#hash) The transaction hash. diff --git a/docs/core/api/createConnector.md b/docs/core/api/createConnector.md index eb4750e70d..7cdbd00bdd 100644 --- a/docs/core/api/createConnector.md +++ b/docs/core/api/createConnector.md @@ -1,6 +1,6 @@ # createConnector -Creates new [`CreateConnectorFn`](#createconnectorfn). +Creates new [`CreateConnectorFn`](#parameters). ## Import @@ -13,9 +13,13 @@ import { createConnector } from '@wagmi/core' ```ts import { createConnector } from '@wagmi/core' -const connector = createConnector((config) => ({ - // ... -})) +export type InjectedParameters = {} + +export function injected(parameters: InjectedParameters = {}) { + return createConnector((config) => ({ + // ... + })) +} ``` ## Parameters @@ -24,8 +28,4 @@ const connector = createConnector((config) => ({ import { type CreateConnectorFn } from '@wagmi/core' ``` -## Return Type - -```ts -import { type CreateConnectorFn } from '@wagmi/core' -``` +Read [Creating Connectors](/dev/creating-connectors) for more info on the `CreateConnectorFn` type. \ No newline at end of file diff --git a/docs/core/guides/migrate-from-v1-to-v2.md b/docs/core/guides/migrate-from-v1-to-v2.md index 643f4f87f3..1579f3ce6f 100644 --- a/docs/core/guides/migrate-from-v1-to-v2.md +++ b/docs/core/guides/migrate-from-v1-to-v2.md @@ -468,8 +468,8 @@ const transport = http('https://mainnet.example.com') Moving forward, `getBalance` will only work for native currencies, thus the `token` parameter is no longer supported. Use [`readContracts`](/core/api/actions/readContracts) instead. ```ts -import { getBalance } from 'wagmi' // [!code --] -import { readContracts } from 'wagmi' // [!code ++] +import { getBalance } from '@wagmi/core' // [!code --] +import { readContracts } from '@wagmi/core' // [!code ++] import { erc20Abi } from 'viem' // [!code ++] const result = await getBalance({ // [!code --] @@ -499,6 +499,22 @@ const result = await readContracts({ // [!code ++] }) // [!code ++] ``` +### Deprecated `getBalance` `unit` parameter and `formatted` return value + +Moving forward, `getBalance` will not accept the `unit` parameter or return a `formatted` value. Instead you can call `formatUnits` from Viem directly or use another number formatting library, like [dnum](https://github.com/bpierre/dnum) instead. + +```ts +import { formatUnits } from 'viem' // [!code ++] +import { getBalance } from '@wagmi/core' + +const result = await getBalance({ + address: '0x4557B18E779944BFE9d78A672452331C186a9f48', + unit: 'ether', // [!code --] +}) +result.formatted // [!code --] +formatUnits(result.value, result.decimals) // [!code ++] +``` + ### Deprecated `getToken` Moving forward, `getToken` is no longer supported. Use [`readContracts`](/core/api/actions/readContracts) instead. @@ -538,6 +554,29 @@ const result = await readContracts({ // [!code ++] }) // [!code ++] ``` +### Deprecated `formatUnits` parameters and return values + +The `formatUnits` parameter and related return values (e.g. `result.formatted`) are deprecated for the following actions: + +- [`estimateFeesPerGas`](/core/api/actions/estimateFeesPerGas) +- [`getToken`](/core/api/actions/getToken) + +Instead you can call `formatUnits` from Viem directly or use another number formatting library, like [dnum](https://github.com/bpierre/dnum) instead. + +```ts +import { formatUnits } from 'viem' // [!code ++] +import { getToken } from '@wagmi/core' + +const result = await getToken({ + address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', + formatUnits: 'ether', +}) +result.totalSupply.formatted // [!code --] +formatUnits(result.totalSupply.value, 18) // [!code ++] +``` + +This allows us to invert control to users so they can handle number formatting however they want, taking into account precision, localization, and more. + ### Renamed actions The following actions were renamed to better reflect their functionality and underlying [Viem](https://viem.sh) actions: diff --git a/docs/index.md b/docs/index.md index 144f0b228d..b94db0a21b 100644 --- a/docs/index.md +++ b/docs/index.md @@ -17,6 +17,9 @@ hero: - theme: alt text: Why Wagmi link: /react/why-wagmi + - theme: alt + text: View on GitHub + link: https://github.com/wagmi-dev/wagmi/tree/alpha image: src: /logo-dark.svg alt: VitePress diff --git a/docs/react/api/hooks/useWaitForTransactionReceipt.md b/docs/react/api/hooks/useWaitForTransactionReceipt.md index 8da9d1bedf..88f54411bb 100644 --- a/docs/react/api/hooks/useWaitForTransactionReceipt.md +++ b/docs/react/api/hooks/useWaitForTransactionReceipt.md @@ -127,7 +127,8 @@ function App() { `number | undefined` -Polling frequency (in ms). Defaults to the [Config's `pollingInterval` config](/react/api/createConfig#pollinginterval). +- Polling frequency (in milliseconds). +- Defaults to the [Config's `pollingInterval` config](/react/api/createConfig#pollinginterval). ```ts [index.ts] import { useWaitForTransactionReceipt } from 'wagmi' diff --git a/docs/react/guides/migrate-from-v1-to-v2.md b/docs/react/guides/migrate-from-v1-to-v2.md index 80ec9bd1d5..8bcd92b8a5 100644 --- a/docs/react/guides/migrate-from-v1-to-v2.md +++ b/docs/react/guides/migrate-from-v1-to-v2.md @@ -536,6 +536,22 @@ const result = useReadContracts({ // [!code ++] }) // [!code ++] ``` +### Deprecated `useBalance` `unit` parameter and `formatted` return value + +Moving forward, `useBalance` will not accept the `unit` parameter or return a `formatted` value. Instead you can call `formatUnits` from Viem directly or use another number formatting library, like [dnum](https://github.com/bpierre/dnum) instead. + +```ts +import { formatUnits } from 'viem' // [!code ++] +import { useBalance } from 'wagmi' + +const result = useBalance({ + address: '0x4557B18E779944BFE9d78A672452331C186a9f48', + unit: 'ether', // [!code --] +}) +result.data!.formatted // [!code --] +formatUnits(result.data!.value, result.data!.decimals) // [!code ++] +``` + ### Deprecated `useToken` Moving forward, `useToken` is no longer supported. Use [`useReadContracts`](/react/api/hooks/useReadContracts) instead. @@ -575,6 +591,28 @@ const result = useReadContracts({ // [!code ++] }) // [!code ++] ``` +### Deprecated `formatUnits` parameters and return values + +The `formatUnits` parameter and related return values (e.g. `result.formatted`) are deprecated for the following hooks: + +- [`useEstimateFeesPerGas`](/react/api/hooks/useEstimateFeesPerGas) +- [`useToken`](/react/api/hooks/useToken) + +Instead you can call `formatUnits` from Viem directly or use another number formatting library, like [dnum](https://github.com/bpierre/dnum) instead. + +```ts +import { formatUnits } from 'viem' // [!code ++] + +const result = useToken({ + address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', + formatUnits: 'ether', +}) +result.data!.totalSupply.formatted // [!code --] +formatUnits(result.data!.totalSupply.value, 18) // [!code ++] +``` + +This allows us to invert control to users so they can handle number formatting however they want, taking into account precision, localization, and more. + ### Renamed hooks The following hooks were renamed to better reflect their functionality and underlying [Viem](https://viem.sh) actions: diff --git a/docs/shared/connectors/ledger.md b/docs/shared/connectors/ledger.md index 00817db0c9..aa0ba640f2 100644 --- a/docs/shared/connectors/ledger.md +++ b/docs/shared/connectors/ledger.md @@ -63,7 +63,7 @@ import { ledger } from '{{connectorsPackageName}}' const connector = ledger({ optionalEvents: [ // [!code focus] - "message", // [!code focus] + 'message', // [!code focus] ], // [!code focus] }) ``` @@ -79,9 +79,9 @@ import { ledger } from '{{connectorsPackageName}}' const connector = ledger({ optionalMethods: [ // [!code focus] - "wallet_switchEthereumChain", // [!code focus] - "wallet_addEthereumChain", // [!code focus] - "wallet_getPermissions", // [!code focus] + 'wallet_switchEthereumChain', // [!code focus] + 'wallet_addEthereumChain', // [!code focus] + 'wallet_getPermissions', // [!code focus] ], // [!code focus] }) ``` @@ -126,10 +126,10 @@ import { ledger } from '{{connectorsPackageName}}' const connector = ledger({ requiredEvents: [ // [!code focus] - "accountsChanged", // [!code focus] - "chainChanged", // [!code focus] - "connect", // [!code focus] - "disconnect", // [!code focus] + 'accountsChanged', // [!code focus] + 'chainChanged', // [!code focus] + 'connect', // [!code focus] + 'disconnect', // [!code focus] ], // [!code focus] }) ``` @@ -145,8 +145,8 @@ import { ledger } from '{{connectorsPackageName}}' const connector = ledger({ requiredMethods: [ // [!code focus] - "eth_sendTransaction", // [!code focus] - "personal_sign", // [!code focus] + 'eth_sendTransaction', // [!code focus] + 'personal_sign', // [!code focus] ], // [!code focus] }) ``` diff --git a/docs/shared/faq.md b/docs/shared/faq.md index 30f71aa1b9..4bc4a1fa48 100644 --- a/docs/shared/faq.md +++ b/docs/shared/faq.md @@ -37,7 +37,7 @@ const deserialized = deserialize(serialized) #### Lossy serialization -Lossy serialization means that the `BigInt` will be converted to a normal display string (e.g. `69420n` → `"69420"`). +Lossy serialization means that the `BigInt` will be converted to a normal display string (e.g. `69420n` → `'69420'`). The trade-off is that you will not be able to deserialize the `BigInt` with `JSON.parse` as it can not distinguish between a normal string and a `BigInt`. This method can be achieved by modifying `JSON.stringify` to include a BigInt `replacer`: diff --git a/docs/shared/query-options.md b/docs/shared/query-options.md index b4ff3c42ec..f03ae94c08 100644 --- a/docs/shared/query-options.md +++ b/docs/shared/query-options.md @@ -64,11 +64,11 @@ If set, stores additional information on the query cache entry that can be used #### notifyOnChangeProps -`string[] | "all" | (() => string[] | "all") | undefined` +`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 `'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. @@ -101,32 +101,32 @@ If set to `true`, queries that are set to continuously refetch with a `refetchIn #### refetchOnMount -`boolean | "always" | ((query: Query) => boolean | "always") | undefined` +`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 `'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` +`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 `'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` +`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 `'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 @@ -158,7 +158,7 @@ If set to `false`, the query will not be retried on mount if it contains an erro 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 diff --git a/docs/snippets/abi-event.ts b/docs/snippets/abi-event.ts new file mode 100644 index 0000000000..2d5b344ae9 --- /dev/null +++ b/docs/snippets/abi-event.ts @@ -0,0 +1,20 @@ +export const abi = [ + { + type: 'event', + name: 'Approval', + inputs: [ + { indexed: true, name: 'owner', type: 'address' }, + { indexed: true, name: 'spender', type: 'address' }, + { indexed: false, name: 'value', type: 'uint256' }, + ], + }, + { + type: 'event', + name: 'Transfer', + inputs: [ + { indexed: true, name: 'from', type: 'address' }, + { indexed: true, name: 'to', type: 'address' }, + { indexed: false, name: 'value', type: 'uint256' }, + ], + }, +] as const diff --git a/packages/core/src/actions/estimateFeesPerGas.ts b/packages/core/src/actions/estimateFeesPerGas.ts index a01d03aa80..9838e8dcb2 100644 --- a/packages/core/src/actions/estimateFeesPerGas.ts +++ b/packages/core/src/actions/estimateFeesPerGas.ts @@ -28,6 +28,7 @@ export type EstimateFeesPerGasParameters< 'chain' > & ChainIdParameter & { + /** @deprecated */ formatUnits?: Unit | undefined } > @@ -36,6 +37,7 @@ export type EstimateFeesPerGasReturnType< type extends FeeValuesType = FeeValuesType, > = Evaluate< viem_EstimateFeesPerGasReturnType & { + /** @deprecated */ formatted: UnionEvaluate< | (type extends 'legacy' ? FeeValuesLegacy : never) | (type extends 'eip1559' ? FeeValuesEIP1559 : never) diff --git a/packages/core/src/actions/getBalance.ts b/packages/core/src/actions/getBalance.ts index f00429a32a..fd1041f4f0 100644 --- a/packages/core/src/actions/getBalance.ts +++ b/packages/core/src/actions/getBalance.ts @@ -24,12 +24,14 @@ export type GetBalanceParameters = Evaluate< viem_GetBalanceParameters & { /** @deprecated */ token?: Address | undefined + /** @deprecated */ unit?: Unit | undefined } > export type GetBalanceReturnType = { decimals: number + /** @deprecated */ formatted: string symbol: string value: bigint diff --git a/packages/core/src/actions/getToken.ts b/packages/core/src/actions/getToken.ts index bcf77cad74..c165e8baaf 100644 --- a/packages/core/src/actions/getToken.ts +++ b/packages/core/src/actions/getToken.ts @@ -33,6 +33,7 @@ export type GetTokenReturnType = { export type GetTokenErrorType = ReadContractsErrorType +/** @deprecated */ export async function getToken( config: config, parameters: GetTokenParameters, diff --git a/packages/core/src/connectors/createConnector.ts b/packages/core/src/connectors/createConnector.ts index 3b84165da7..61586729ab 100644 --- a/packages/core/src/connectors/createConnector.ts +++ b/packages/core/src/connectors/createConnector.ts @@ -68,6 +68,6 @@ export function createConnector< provider, properties extends Record = {}, storageItem extends Record = {}, ->(fn: CreateConnectorFn) { - return fn +>(createConnectorFn: CreateConnectorFn) { + return createConnectorFn } diff --git a/packages/react/src/hooks/useToken.ts b/packages/react/src/hooks/useToken.ts index b30b92444c..beb84580db 100644 --- a/packages/react/src/hooks/useToken.ts +++ b/packages/react/src/hooks/useToken.ts @@ -34,7 +34,11 @@ export type UseTokenReturnType = UseQueryReturnType< GetTokenErrorType > -/** https://alpha.wagmi.sh/react/api/hooks/useToken */ +/** + * @deprecated + * + * https://alpha.wagmi.sh/react/api/hooks/useToken + */ export function useToken< config extends Config = ResolvedRegister['config'], selectData = GetTokenData,