diff --git a/bun.lockb b/bun.lockb index 330c1e7656..88837692f3 100755 Binary files a/bun.lockb and b/bun.lockb differ diff --git a/site/package.json b/site/package.json index ff6944213c..d626272c1f 100644 --- a/site/package.json +++ b/site/package.json @@ -10,6 +10,6 @@ "devDependencies": { "react": "^18.2.0", "react-dom": "^18.2.0", - "vocs": "1.0.0-alpha.30" + "vocs": "1.0.0-alpha.34" } } diff --git a/site/pages/docs/accounts/hd.md b/site/pages/docs/accounts/hd.md index de43d0097e..c1879e3838 100644 --- a/site/pages/docs/accounts/hd.md +++ b/site/pages/docs/accounts/hd.md @@ -10,7 +10,7 @@ viem internally uses [`@scure/bip32`](https://github.com/paulmillr/scure-bip32), ## Import -```ts +```ts twoslash import { HDKey, hdKeyToAccount } from 'viem/accounts' ``` @@ -26,7 +26,8 @@ The `HDKey` instance comes with a few static methods to derive a HD Key: - `fromExtendedKey` - `fromJSON` -```ts +```ts twoslash +// @noErrors import { createWalletClient, http } from 'viem' import { HDKey, hdKeyToAccount } from 'viem/accounts' import { mainnet } from 'viem/chains' @@ -52,7 +53,9 @@ const client = createWalletClient({ The BIP-39 mnemonic phrase. -```ts +```ts twoslash +import { mnemonicToAccount } from 'viem/accounts' +// ---cut--- const account = mnemonicToAccount( 'legal winner thank year wave sausage worth useful legal winner thank yellow' // [!code focus] ) @@ -65,7 +68,9 @@ const account = mnemonicToAccount( The account index to use in the path (`"m/44'/60'/${accountIndex}'/0/0"`) to derive a private key. -```ts +```ts twoslash +import { mnemonicToAccount } from 'viem/accounts' +// ---cut--- const account = mnemonicToAccount( 'legal winner thank year wave sausage worth useful legal winner thank yellow', { @@ -81,7 +86,9 @@ const account = mnemonicToAccount( The address index to use in the path (`"m/44'/60'/0'/0/${addressIndex}"`) to derive a private key. -```ts +```ts twoslash +import { mnemonicToAccount } from 'viem/accounts' +// ---cut--- const account = mnemonicToAccount( 'legal winner thank year wave sausage worth useful legal winner thank yellow', { @@ -98,7 +105,9 @@ const account = mnemonicToAccount( The change index to use in the path (`"m/44'/60'/0'/${changeIndex}/0"`) to derive a private key. -```ts +```ts twoslash +import { mnemonicToAccount } from 'viem/accounts' +// ---cut--- const account = mnemonicToAccount( 'legal winner thank year wave sausage worth useful legal winner thank yellow', { @@ -115,7 +124,9 @@ const account = mnemonicToAccount( The HD path to use to derive a private key. -```ts +```ts twoslash +import { mnemonicToAccount } from 'viem/accounts' +// ---cut--- const account = mnemonicToAccount( 'legal winner thank year wave sausage worth useful legal winner thank yellow', { diff --git a/site/pages/docs/accounts/jsonRpc.md b/site/pages/docs/accounts/jsonRpc.md index 880bb30b80..15854e8416 100644 --- a/site/pages/docs/accounts/jsonRpc.md +++ b/site/pages/docs/accounts/jsonRpc.md @@ -6,7 +6,9 @@ A JSON-RPC Account **defers** signing of transactions & messages to the target W A JSON-RPC Account can just be initialized as an [Address](/docs/glossary/types#address) string. In the usage below, we are extracting the address from a Browser Extension Wallet (e.g. MetaMask) with the `window.ethereum` Provider via `eth_requestAccounts`: -```ts +```ts twoslash +// @noErrors +import 'viem/window' import { createWalletClient, custom } from 'viem' import { mainnet } from 'viem/chains' @@ -17,6 +19,6 @@ const [address] = await window.ethereum.request({ // [!code focus:3] const client = createWalletClient({ account: address, // [!code focus] chain: mainnet, - transport: custom(window.ethereum) + transport: custom(window.ethereum!) }) ``` diff --git a/site/pages/docs/accounts/local.md b/site/pages/docs/accounts/local.md index 64b54dc406..3629643b14 100644 --- a/site/pages/docs/accounts/local.md +++ b/site/pages/docs/accounts/local.md @@ -14,7 +14,7 @@ Below are the steps to integrate a **Private Key Account**, but the same steps c Before we set up our Account and start consuming Wallet Actions, we will need to set up our Wallet Client with the [`http` Transport](/docs/clients/transports/http): -```ts +```ts twoslash import { createWalletClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -28,7 +28,7 @@ const client = createWalletClient({ Next, we will instantiate a Private Key Account using `privateKeyToAccount`: -```ts +```ts twoslash import { createWalletClient, http } from 'viem' import { privateKeyToAccount } from 'viem/accounts' // [!code focus] import { mainnet } from 'viem/chains' @@ -45,8 +45,8 @@ const account = privateKeyToAccount('0x...') // [!code focus:1] Now you can use that Account within Wallet Actions that need a signature from the user: -```ts -import { createWalletClient, http } from 'viem' +```ts twoslash +import { createWalletClient, http, parseEther } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { mainnet } from 'viem/chains' @@ -68,8 +68,8 @@ const hash = await client.sendTransaction({ // [!code focus:5] If you do not wish to pass an account around to every Action that requires an `account`, you can also hoist the account into the Wallet Client. -```ts -import { createWalletClient, http } from 'viem' +```ts twoslash +import { createWalletClient, http, parseEther } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { mainnet } from 'viem/chains' @@ -94,8 +94,10 @@ When using a Local Account, you may be finding yourself using a [Public Client]( In this case, you can extend your Wallet Client with [Public Actions](/docs/actions/public/introduction) to avoid having to handle multiple Clients. -```ts {12} +```ts twoslash {12} +// @noErrors import { createWalletClient, http, publicActions } from 'viem' +import { privateKeyToAccount } from 'viem/accounts' import { mainnet } from 'viem/chains' const account = privateKeyToAccount('0x...') diff --git a/site/pages/docs/accounts/mnemonic.md b/site/pages/docs/accounts/mnemonic.md index 7047a6e8c5..c003eaedfb 100644 --- a/site/pages/docs/accounts/mnemonic.md +++ b/site/pages/docs/accounts/mnemonic.md @@ -10,7 +10,7 @@ viem internally uses [`@scure/bip32`](https://github.com/paulmillr/scure-bip32), ## Import -```ts +```ts twoslash import { mnemonicToAccount } from 'viem/accounts' ``` @@ -18,7 +18,7 @@ import { mnemonicToAccount } from 'viem/accounts' To initialize a Mnemonic Account, you will need to pass a mnemonic phrase to `mnemonicToAccount`: -```ts +```ts twoslash import { createWalletClient, http } from 'viem' import { mnemonicToAccount } from 'viem/accounts' import { mainnet } from 'viem/chains' @@ -38,7 +38,7 @@ const client = createWalletClient({ You can generate a random BIP-39 mnemonic using the `generateMnemonic` function with a wordlist: -```ts +```ts twoslash import { english, generateMnemonic } from 'viem/accounts' const mnemonic = generateMnemonic(english) @@ -68,7 +68,9 @@ Available wordlists: The BIP-39 mnemonic phrase. -```ts +```ts twoslash +import { mnemonicToAccount } from 'viem/accounts' +// ---cut--- const account = mnemonicToAccount( 'legal winner thank year wave sausage worth useful legal winner thank yellow' // [!code focus] ) @@ -81,7 +83,9 @@ const account = mnemonicToAccount( The account index to use in the path (`"m/44'/60'/${accountIndex}'/0/0"`) to derive a private key. -```ts +```ts twoslash +import { mnemonicToAccount } from 'viem/accounts' +// ---cut--- const account = mnemonicToAccount( 'legal winner thank year wave sausage worth useful legal winner thank yellow', { @@ -97,7 +101,9 @@ const account = mnemonicToAccount( The address index to use in the path (`"m/44'/60'/0'/0/${addressIndex}"`) to derive a private key. -```ts +```ts twoslash +import { mnemonicToAccount } from 'viem/accounts' +// ---cut--- const account = mnemonicToAccount( 'legal winner thank year wave sausage worth useful legal winner thank yellow', { @@ -114,7 +120,9 @@ const account = mnemonicToAccount( The change index to use in the path (`"m/44'/60'/0'/${changeIndex}/0"`) to derive a private key. -```ts +```ts twoslash +import { mnemonicToAccount } from 'viem/accounts' +// ---cut--- const account = mnemonicToAccount( 'legal winner thank year wave sausage worth useful legal winner thank yellow', { @@ -131,7 +139,9 @@ const account = mnemonicToAccount( The HD path to use to derive a private key. -```ts +```ts twoslash +import { mnemonicToAccount } from 'viem/accounts' +// ---cut--- const account = mnemonicToAccount( 'legal winner thank year wave sausage worth useful legal winner thank yellow', { diff --git a/site/pages/docs/accounts/privateKey.md b/site/pages/docs/accounts/privateKey.md index e3c3918b8a..c9fde1c0cd 100644 --- a/site/pages/docs/accounts/privateKey.md +++ b/site/pages/docs/accounts/privateKey.md @@ -8,7 +8,7 @@ viem internally uses [`@noble/curves`](https://github.com/paulmillr/noble-curves ## Import -```ts +```ts twoslash import { privateKeyToAccount } from 'viem/accounts' ``` @@ -16,7 +16,7 @@ import { privateKeyToAccount } from 'viem/accounts' To initialize a Private Key Account, you will need to pass a private key to `privateKeyToAccount`: -```ts +```ts twoslash import { createWalletClient, http } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { mainnet } from 'viem/chains' @@ -36,7 +36,7 @@ const client = createWalletClient({ You can generate a random private key using the `generatePrivateKey` function: -```ts +```ts twoslash import { generatePrivateKey } from 'viem/accounts' const privateKey = generatePrivateKey() @@ -56,7 +56,9 @@ The private key to use for the Account. The address of the Account. -```ts +```ts twoslash +import { privateKeyToAccount } from 'viem/accounts' +// ---cut--- const account = privateKeyToAccount('0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80') account.address @@ -67,7 +69,9 @@ account.address Calculates an Ethereum-specific signature in [EIP-191 format](https://eips.ethereum.org/EIPS/eip-191): `keccak256("\x19Ethereum Signed Message:\n" + len(message) + message))`. -```ts +```ts twoslash +import { privateKeyToAccount } from 'viem/accounts' +// ---cut--- const account = privateKeyToAccount('0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80') account.signMessage({ message: 'Hello World' }) diff --git a/site/pages/docs/accounts/signMessage.md b/site/pages/docs/accounts/signMessage.md index aaa5d74506..68e19ea15b 100644 --- a/site/pages/docs/accounts/signMessage.md +++ b/site/pages/docs/accounts/signMessage.md @@ -9,7 +9,7 @@ With the calculated signature, you can: ## Usage -```ts +```ts twoslash import { privateKeyToAccount } from 'viem/accounts' const account = privateKeyToAccount('0x...') @@ -18,7 +18,7 @@ const signature = await account.signMessage({ // Hex data representation of message. message: { raw: '0x68656c6c6f20776f726c64' }, }) -// "0xa461f509887bd19e312c0c58467ce8ff8e300d3c1a90b608a760c5b80318eaf15fe57c96f9175d6cd4daad4663763baa7e78836e067d0163e9a2ccf2ff753f5b1b" +// @log: Output: "0xa461f509887bd19e312c0c58467ce8ff8e300d3c1a90b608a760c5b80318eaf15fe57c96f9175d6cd4daad4663763baa7e78836e067d0163e9a2ccf2ff753f5b1b" ``` ## Returns @@ -37,7 +37,11 @@ Message to sign. By default, viem signs the UTF-8 representation of the message. -```ts +```ts twoslash +import { privateKeyToAccount } from 'viem/accounts' + +const account = privateKeyToAccount('0x...') +// ---cut--- const signature = await account.signMessage({ message: 'hello world', // [!code focus:1] }) @@ -45,7 +49,11 @@ const signature = await account.signMessage({ To sign the data representation of the message, you can use the `raw` attribute. -```ts +```ts twoslash +import { privateKeyToAccount } from 'viem/accounts' + +const account = privateKeyToAccount('0x...') +// ---cut--- const signature = await account.signMessage({ message: { raw: '0x68656c6c6f20776f726c64' }, // [!code focus:1] }) diff --git a/site/pages/docs/accounts/signTransaction.md b/site/pages/docs/accounts/signTransaction.md index 921f97b719..3fffcd576b 100644 --- a/site/pages/docs/accounts/signTransaction.md +++ b/site/pages/docs/accounts/signTransaction.md @@ -4,27 +4,28 @@ Signs a transaction with the Account's private key. ## Usage -```ts +```ts twoslash import { parseGwei } from 'viem' import { privateKeyToAccount } from 'viem/accounts' const account = privateKeyToAccount('0x...') const signature = await account.signTransaction({ + chainId: 1, maxFeePerGas: parseGwei('20'), maxPriorityFeePerGas: parseGwei('3'), gas: 21000n, nonce: 69, to: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266' }) -// "0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33" +// @log: Output: "0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33" ``` ### Custom serializer viem has a built-in serializer for **Legacy**, **EIP-2930** (`0x01`) and **EIP-1559** (`0x02`) transaction types. If you would like to serialize on another transaction type that viem does not support internally, you can pass a custom serializer. -```ts +```ts import { parseGwei } from 'viem' import { privateKeyToAccount } from 'viem/accounts' @@ -70,7 +71,10 @@ The signed transaction. The access list. -```ts +```ts twoslash +import { privateKeyToAccount } from 'viem/accounts' +const account = privateKeyToAccount('0x...') +// ---cut--- const signature = await account.signTransaction({ accessList: [ // [!code focus:6] { @@ -78,6 +82,7 @@ const signature = await account.signTransaction({ storageKeys: ['0x1'], }, ], + type: 'eip1559' }) ``` @@ -87,7 +92,10 @@ const signature = await account.signTransaction({ The chain ID. -```ts +```ts twoslash +import { privateKeyToAccount } from 'viem/accounts' +const account = privateKeyToAccount('0x...') +// ---cut--- const signature = await account.signTransaction({ chainId: 1, // [!code focus] }) @@ -99,7 +107,10 @@ const signature = await account.signTransaction({ Transaction data. -```ts +```ts twoslash +import { privateKeyToAccount } from 'viem/accounts' +const account = privateKeyToAccount('0x...') +// ---cut--- const signature = await account.signTransaction({ data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2' // [!code focus] }) @@ -111,7 +122,10 @@ const signature = await account.signTransaction({ The gas limit for the transaction. -```ts +```ts twoslash +import { privateKeyToAccount } from 'viem/accounts' +const account = privateKeyToAccount('0x...') +// ---cut--- const signature = await account.signTransaction({ gas: 69420n, // [!code focus] }) @@ -123,7 +137,11 @@ const signature = await account.signTransaction({ The price (in wei) to pay per gas. Only applies to [Legacy Transactions](/docs/glossary/terms#legacy-transaction). -```ts +```ts twoslash +import { parseGwei } from 'viem' +import { privateKeyToAccount } from 'viem/accounts' +const account = privateKeyToAccount('0x...') +// ---cut--- const signature = await account.signTransaction({ gasPrice: parseGwei('20'), // [!code focus] }) @@ -135,8 +153,13 @@ const signature = await account.signTransaction({ Total fee per gas (in wei), inclusive of `maxPriorityFeePerGas`. Only applies to [EIP-1559 Transactions](/docs/glossary/terms#eip-1559-transaction) -```ts +```ts twoslash +import { parseGwei } from 'viem' +import { privateKeyToAccount } from 'viem/accounts' +const account = privateKeyToAccount('0x...') +// ---cut--- const signature = await account.signTransaction({ + chainId: 1, maxFeePerGas: parseGwei('20'), // [!code focus] }) ``` @@ -147,8 +170,13 @@ const signature = await account.signTransaction({ Max priority fee per gas (in wei). Only applies to [EIP-1559 Transactions](/docs/glossary/terms#eip-1559-transaction) -```ts +```ts twoslash +import { parseGwei } from 'viem' +import { privateKeyToAccount } from 'viem/accounts' +const account = privateKeyToAccount('0x...') +// ---cut--- const signature = await account.signTransaction({ + chainId: 1, maxPriorityFeePerGas: parseGwei('3'), // [!code focus] }) ``` @@ -159,7 +187,10 @@ const signature = await account.signTransaction({ Unique number identifying this transaction. -```ts +```ts twoslash +import { privateKeyToAccount } from 'viem/accounts' +const account = privateKeyToAccount('0x...') +// ---cut--- const signature = await account.signTransaction({ nonce: 69 // [!code focus] }) @@ -171,7 +202,10 @@ const signature = await account.signTransaction({ The transaction recipient. -```ts +```ts twoslash +import { privateKeyToAccount } from 'viem/accounts' +const account = privateKeyToAccount('0x...') +// ---cut--- const signature = await account.signTransaction({ to: '0x...' // [!code focus] }) @@ -183,7 +217,10 @@ const signature = await account.signTransaction({ The transaction type. -```ts +```ts twoslash +import { privateKeyToAccount } from 'viem/accounts' +const account = privateKeyToAccount('0x...') +// ---cut--- const signature = await account.signTransaction({ type: 'eip1559' // [!code focus] }) @@ -195,7 +232,11 @@ const signature = await account.signTransaction({ Value in wei sent with this transaction. -```ts +```ts twoslash +import { parseEther } from 'viem' +import { privateKeyToAccount } from 'viem/accounts' +const account = privateKeyToAccount('0x...') +// ---cut--- const signature = await account.signTransaction({ value: parseEther('1'), // [!code focus] }) diff --git a/site/pages/docs/accounts/signTypedData.md b/site/pages/docs/accounts/signTypedData.md index 060b29226c..900bdc3597 100644 --- a/site/pages/docs/accounts/signTypedData.md +++ b/site/pages/docs/accounts/signTypedData.md @@ -6,7 +6,7 @@ Signs typed data and calculates an Ethereum-specific signature in [https://eips. :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { privateKeyToAccount } from 'viem/accounts' import { domain, types } from './data' @@ -30,7 +30,7 @@ const signature = await account.signTypedData({ }) ``` -```ts [data.ts] +```ts twoslash [data.ts] filename="data.ts" // All properties on a domain are optional export const domain = { name: 'Ether Mail', diff --git a/site/pages/docs/actions/public/call.md b/site/pages/docs/actions/public/call.md index 852335b28b..1986b609dd 100644 --- a/site/pages/docs/actions/public/call.md +++ b/site/pages/docs/actions/public/call.md @@ -6,7 +6,7 @@ Executes a new message call immediately without submitting a transaction to the :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { account, publicClient } from './config' const data = await publicClient.call({ // [!code focus:7] @@ -16,15 +16,16 @@ const data = await publicClient.call({ // [!code focus:7] }) ``` -```ts [config.ts] +```ts twoslash [config.ts] filename="config.ts" import { createPublicClient, http } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { mainnet } from 'viem/chains' -// JSON-RPC Account +// @log: ↓ JSON-RPC Account export const account = '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266' -// Local Account -export const account = privateKeyToAccount('0x...') + +// @log: ↓ Local Account +// export const account = privateKeyToAccount(...) export const publicClient = createPublicClient({ chain: mainnet, @@ -50,7 +51,9 @@ The Account to call from. Accepts a [JSON-RPC Account](/docs/clients/wallet#json-rpc-accounts) or [Local Account (Private Key, etc)](/docs/clients/wallet#local-accounts-private-key-mnemonic-etc). -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const data = await publicClient.call({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', // [!code focus] data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', @@ -64,9 +67,11 @@ const data = await publicClient.call({ A contract hashed method call with encoded args. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const data = await publicClient.call({ - account, + account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) @@ -78,9 +83,11 @@ const data = await publicClient.call({ The contract address or recipient. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const data = await publicClient.call({ - account, + account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', // [!code focus] }) @@ -92,9 +99,11 @@ const data = await publicClient.call({ The access list. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const data = await publicClient.call({ - account, + account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', accessList: [ // [!code focus:6] { address: '0x1', @@ -112,10 +121,12 @@ const data = await publicClient.call({ The block number to perform the call against. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const data = await publicClient.call({ blockNumber: 15121123n, // [!code focus] - account, + account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) @@ -128,10 +139,12 @@ const data = await publicClient.call({ The block tag to perform the call against. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const data = await publicClient.call({ blockTag: 'safe', // [!code focus] - account, + account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) @@ -143,9 +156,11 @@ const data = await publicClient.call({ The gas provided for transaction execution. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const data = await publicClient.call({ - account, + account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', gas: 1_000_000n, // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', @@ -158,9 +173,13 @@ const data = await publicClient.call({ The price (in wei) to pay per gas. Only applies to [Legacy Transactions](/docs/glossary/terms#legacy-transaction). -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseGwei } from 'viem' + const data = await publicClient.call({ - account, + account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', gasPrice: parseGwei('20'), // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', @@ -173,9 +192,13 @@ const data = await publicClient.call({ Total fee per gas (in wei), inclusive of `maxPriorityFeePerGas`. Only applies to [EIP-1559 Transactions](/docs/glossary/terms#eip-1559-transaction). -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseGwei } from 'viem' + const data = await publicClient.call({ - account, + account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', maxFeePerGas: parseGwei('20'), // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', @@ -188,9 +211,13 @@ const data = await publicClient.call({ Max priority fee per gas (in wei). Only applies to [EIP-1559 Transactions](/docs/glossary/terms#eip-1559-transaction). -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseGwei } from 'viem' + const data = await publicClient.call({ - account, + account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', maxFeePerGas: parseGwei('20'), maxPriorityFeePerGas: parseGwei('2'), // [!code focus] @@ -204,11 +231,13 @@ const data = await publicClient.call({ Unique number identifying this transaction. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const data = await publicClient.call({ - account, + account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', - nonce: 420n, // [!code focus] + nonce: 420, // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ``` @@ -245,9 +274,13 @@ const data = await publicClient.call({ Value (in wei) sent with this transaction. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseEther } from 'viem' + const data = await publicClient.call({ - account, + account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), // [!code focus] diff --git a/site/pages/docs/actions/public/createBlockFilter.md b/site/pages/docs/actions/public/createBlockFilter.md index f60569846f..fb927a1a4a 100644 --- a/site/pages/docs/actions/public/createBlockFilter.md +++ b/site/pages/docs/actions/public/createBlockFilter.md @@ -6,14 +6,14 @@ Creates a Filter to listen for new block hashes that can be used with [`getFilte :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' const filter = await publicClient.createBlockFilter() // [!code focus:99] -// { id: "0x345a6572337856574a76364e457a4366", type: 'block' } +// @log: { id: "0x345a6572337856574a76364e457a4366", type: 'block' } ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' diff --git a/site/pages/docs/actions/public/createEventFilter.md b/site/pages/docs/actions/public/createEventFilter.md index b0e76a37bc..b23864a3fd 100644 --- a/site/pages/docs/actions/public/createEventFilter.md +++ b/site/pages/docs/actions/public/createEventFilter.md @@ -8,14 +8,14 @@ By default, an Event Filter with no arguments will query for/listen to all event :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' const filter = await publicClient.createEventFilter() -// { id: "0x345a6572337856574a76364e457a4366", type: 'event' } +// @log: { id: "0x345a6572337856574a76364e457a4366", type: 'event' } ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -41,7 +41,7 @@ A Filter can be scoped to an **address**: :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' const filter = await publicClient.createEventFilter({ @@ -49,7 +49,7 @@ const filter = await publicClient.createEventFilter({ }) ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -69,7 +69,7 @@ The `event` argument takes in an event in ABI format – we have a [`parseAbiIte :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { parseAbiItem } from 'viem' // [!code focus] import { publicClient } from './client' @@ -79,7 +79,7 @@ const filter = await publicClient.createEventFilter({ }) ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -95,7 +95,7 @@ By default, `event` accepts the [`AbiEvent`](/docs/glossary/types#abievent) type :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' const filter = await publicClient.createEventFilter(publicClient, { @@ -111,7 +111,7 @@ const filter = await publicClient.createEventFilter(publicClient, { }) ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -127,7 +127,11 @@ export const publicClient = createPublicClient({ A Filter can be scoped to given **_indexed_ arguments**: -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseAbiItem } from 'viem' + const filter = await publicClient.createEventFilter({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'), @@ -142,7 +146,11 @@ Only indexed arguments in `event` are candidates for `args`. A Filter Argument can also be an array to indicate that other values can exist in the position: -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseAbiItem } from 'viem' + const filter = await publicClient.createEventFilter({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'), @@ -161,7 +169,11 @@ const filter = await publicClient.createEventFilter({ A Filter can be scoped to a **block range**: -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseAbiItem } from 'viem' + const filter = await publicClient.createEventFilter({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'), @@ -174,7 +186,11 @@ const filter = await publicClient.createEventFilter({ A Filter can be scoped to **multiple events**: -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseAbi } from 'viem' + const filter = await publicClient.createEventFilter({ events: parseAbi([ // [!code focus:4] 'event Approval(address indexed owner, address indexed sender, uint256 value)', @@ -190,7 +206,11 @@ Note: A Filter scoped to multiple events cannot be also scoped with [indexed arg By default, `createEventFilter` will include logs that [do not conform](/docs/glossary/terms#non-conforming-log) to the indexed & non-indexed arguments on the `event`. viem will not return a value for arguments that do not conform to the ABI, thus, some arguments on `args` may be undefined. -```ts {8} +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseAbiItem } from 'viem' + const filter = await publicClient.createEventFilter({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'), @@ -198,12 +218,22 @@ const filter = await publicClient.createEventFilter({ const logs = await publicClient.getFilterLogs({ filter }) logs[0].args -// ^? { address?: Address, to?: Address, value?: bigint } +// ^? + + + + + + ``` You can turn on `strict` mode to only return logs that conform to the indexed & non-indexed arguments on the `event`, meaning that `args` will always be defined. The trade-off is that non-conforming logs will be filtered out. -```ts {9} +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseAbiItem } from 'viem' + const filter = await publicClient.createEventFilter({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'), @@ -212,7 +242,13 @@ const filter = await publicClient.createEventFilter({ const logs = await publicClient.getFilterLogs({ filter }) logs[0].args -// ^? { address: Address, to: Address, value: bigint } +// ^? + + + + + + ``` ## Returns @@ -227,7 +263,9 @@ logs[0].args The contract address or a list of addresses from which Logs should originate. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const filter = await publicClient.createEventFilter({ address: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2' // [!code focus] }) @@ -241,7 +279,9 @@ The event in ABI format. A [`parseAbiItem` utility](/docs/abi/parseAbiItem) is exported from viem that converts from a human-readable event signature → ABI. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- import { parseAbiItem } from 'viem' // [!code focus] const filter = await publicClient.createEventFilter({ @@ -256,7 +296,11 @@ const filter = await publicClient.createEventFilter({ A list of _indexed_ event arguments. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseAbiItem } from 'viem' + const filter = await publicClient.createEventFilter({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'), @@ -273,7 +317,9 @@ const filter = await publicClient.createEventFilter({ Block to start querying/listening from. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const filter = await publicClient.createEventFilter({ fromBlock: 69420n // [!code focus] }) @@ -285,7 +331,9 @@ const filter = await publicClient.createEventFilter({ Block to query/listen until. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const filter = await publicClient.createEventFilter({ toBlock: 70120n // [!code focus] }) diff --git a/site/pages/docs/actions/public/createPendingTransactionFilter.md b/site/pages/docs/actions/public/createPendingTransactionFilter.md index e7680307c7..dbbb6fde9a 100644 --- a/site/pages/docs/actions/public/createPendingTransactionFilter.md +++ b/site/pages/docs/actions/public/createPendingTransactionFilter.md @@ -6,14 +6,14 @@ Creates a Filter to listen for new pending transaction hashes that can be used w :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' const filter = await publicClient.createPendingTransactionFilter() // [!code focus:99] -// { id: "0x345a6572337856574a76364e457a4366", type: 'transaction' } +// @log: Output: { id: "0x345a6572337856574a76364e457a4366", type: 'transaction' } ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' diff --git a/site/pages/docs/actions/public/estimateFeesPerGas.md b/site/pages/docs/actions/public/estimateFeesPerGas.md index dcd3651c5f..b4ba7c3063 100644 --- a/site/pages/docs/actions/public/estimateFeesPerGas.md +++ b/site/pages/docs/actions/public/estimateFeesPerGas.md @@ -14,29 +14,25 @@ Otherwise, for EIP-1159 Transactions, viem will estimate the fees using a combin :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' const { maxFeePerGas, maxPriorityFeePerGas } = await publicClient.estimateFeesPerGas() -/** - * { - * maxFeePerGas: 15_000_000_000n, - * maxPriorityFeePerGas: 1_000_000_000n, - * } - */ +// @log: { +// @log: maxFeePerGas: 15_000_000_000n, +// @log: maxPriorityFeePerGas: 1_000_000_000n, +// @log: } const { gasPrice } = await publicClient.estimateFeesPerGas({ type: 'legacy' }) -/** - * { gasPrice: 15_000_000_000n } - */ +// @log: { gasPrice: 15_000_000_000n } ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -63,7 +59,9 @@ An estimate (in wei) for the fees per gas. Optional Chain override. Used to infer the fees per gas from [`chain.fees.estimateFeesPerGas`](/docs/actions/public/estimateFeesPerGas). -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- import { optimism } from 'viem/chains' // [!code focus] const { maxFeePerGas, maxPriorityFeePerGas } = @@ -77,7 +75,9 @@ const { maxFeePerGas, maxPriorityFeePerGas } = - **Type:** `"legacy" | "eip1559"` - **Default:** `"eip1559"` -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const { gasPrice } = await publicClient.estimateFeesPerGas({ type: 'legacy' // [!code focus] }) diff --git a/site/pages/docs/actions/public/estimateGas.md b/site/pages/docs/actions/public/estimateGas.md index 1f7e18da31..8beb3a8b67 100644 --- a/site/pages/docs/actions/public/estimateGas.md +++ b/site/pages/docs/actions/public/estimateGas.md @@ -6,25 +6,26 @@ Estimates the gas necessary to complete a transaction without submitting it to t :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { account, publicClient } from './config' -const gasEstimate = await publicClient.estimateGas({ // [!code focus:7] +const gas = await publicClient.estimateGas({ // [!code focus:7] account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }) ``` -```ts [config.ts] +```ts twoslash [config.ts] filename="config.ts" import { createPublicClient, http } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { mainnet } from 'viem/chains' -// JSON-RPC Account +// @log: ↓ JSON-RPC Account export const account = '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266' -// Local Account -export const account = privateKeyToAccount(...) + +// @log: ↓ Local Account +// export const account = privateKeyToAccount('0x...') export const publicClient = createPublicClient({ chain: mainnet, @@ -50,8 +51,12 @@ The Account to estimate gas from. Accepts a [JSON-RPC Account](/docs/clients/wallet#json-rpc-accounts) or [Local Account (Private Key, etc)](/docs/clients/wallet#local-accounts-private-key-mnemonic-etc). -```ts -const gasEstimate = await publicClient.estimateGas({ +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseEther } from 'viem' + +const gas = await publicClient.estimateGas({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') @@ -64,8 +69,12 @@ const gasEstimate = await publicClient.estimateGas({ Contract code or a hashed method call with encoded args. -```ts -const gasEstimate = await publicClient.estimateGas({ +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseEther } from 'viem' + +const gas = await publicClient.estimateGas({ data: '0x...', // [!code focus] account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', @@ -79,8 +88,12 @@ const gasEstimate = await publicClient.estimateGas({ The price (in wei) to pay per gas. Only applies to [Legacy Transactions](/docs/glossary/terms#legacy-transaction). -```ts -const gasEstimate = await publicClient.estimateGas({ +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseEther, parseGwei } from 'viem' + +const gas = await publicClient.estimateGas({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', gasPrice: parseGwei('20'), // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', @@ -94,8 +107,12 @@ const gasEstimate = await publicClient.estimateGas({ Total fee per gas (in wei), inclusive of `maxPriorityFeePerGas`. Only applies to [EIP-1559 Transactions](/docs/glossary/terms#eip-1559-transaction) -```ts -const gasEstimate = await publicClient.estimateGas({ +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseEther, parseGwei } from 'viem' + +const gas = await publicClient.estimateGas({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', maxFeePerGas: parseGwei('20'), // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', @@ -109,8 +126,12 @@ const gasEstimate = await publicClient.estimateGas({ Max priority fee per gas (in wei). Only applies to [EIP-1559 Transactions](/docs/glossary/terms#eip-1559-transaction) -```ts -const gasEstimate = await publicClient.estimateGas({ +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseEther, parseGwei } from 'viem' + +const gas = await publicClient.estimateGas({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', maxFeePerGas: parseGwei('20'), maxPriorityFeePerGas: parseGwei('2'), // [!code focus] @@ -125,8 +146,12 @@ const gasEstimate = await publicClient.estimateGas({ Transaction recipient. -```ts -const gasEstimate = await publicClient.estimateGas({ +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseEther } from 'viem' + +const gas = await publicClient.estimateGas({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', // [!code focus] value: parseEther('1') @@ -139,8 +164,12 @@ const gasEstimate = await publicClient.estimateGas({ Value (in wei) sent with this transaction. -```ts -const gasEstimate = await publicClient.estimateGas({ +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseEther } from 'viem' + +const gas = await publicClient.estimateGas({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') // [!code focus] @@ -153,8 +182,12 @@ const gasEstimate = await publicClient.estimateGas({ The block number to perform the gas estimate against. -```ts -const gasEstimate = await publicClient.estimateGas({ +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseEther } from 'viem' + +const gas = await publicClient.estimateGas({ blockNumber: 15121123n, // [!code focus] account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', @@ -169,8 +202,12 @@ const gasEstimate = await publicClient.estimateGas({ The block tag to perform the gas estimate against. -```ts -const gasEstimate = await publicClient.estimateGas({ +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseEther } from 'viem' + +const gas = await publicClient.estimateGas({ blockTag: 'safe', // [!code focus] account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', diff --git a/site/pages/docs/actions/public/estimateMaxPriorityFeePerGas.md b/site/pages/docs/actions/public/estimateMaxPriorityFeePerGas.md index 6465f2c239..4a8ac3982b 100644 --- a/site/pages/docs/actions/public/estimateMaxPriorityFeePerGas.md +++ b/site/pages/docs/actions/public/estimateMaxPriorityFeePerGas.md @@ -14,15 +14,14 @@ Otherwise, the Action will either call [`eth_maxPriorityFeePerGas`](https://gith :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' -const maxPriorityFeePerGas = - await publicClient.estimateMaxPriorityFeePerGas() -// 1_000_000_000n +const maxPriorityFeePerGas = await publicClient.estimateMaxPriorityFeePerGas() +// @log: Output: 1_000_000_000n ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -49,7 +48,9 @@ An estimate (in wei) for the max priority fee per gas. Optional Chain override. Used to infer the default `maxPriorityFeePerGas` from [`chain.fees.defaultPriorityFee`](/docs/chains/fees#feesdefaultpriorityfee). -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- import { optimism } from 'viem/chains' // [!code focus] const maxPriorityFeePerGas = diff --git a/site/pages/docs/actions/public/getBalance.md b/site/pages/docs/actions/public/getBalance.md index 880ea60c3e..5fe4a7f655 100644 --- a/site/pages/docs/actions/public/getBalance.md +++ b/site/pages/docs/actions/public/getBalance.md @@ -10,23 +10,17 @@ Returns the balance of an address in wei. :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' const balance = await publicClient.getBalance({ // [!code focus:4] address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', }) -// 10000000000000000000000n (wei) +// @log: > 10000000000000000000000n (wei) ``` -```ts [client.ts] -import { createPublicClient, http } from 'viem' -import { mainnet } from 'viem/chains' - -export const publicClient = createPublicClient({ - chain: mainnet, - transport: http() -}) +```ts twoslash [client.ts] filename="client.ts" +// [!include ~/snippets/publicClient.ts] ``` ::: @@ -45,7 +39,9 @@ The balance of the address in wei. The address of the account. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const balance = await publicClient.getBalance({ address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', // [!code focus] }) @@ -57,7 +53,9 @@ const balance = await publicClient.getBalance({ The balance of the account at a block number. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const balance = await publicClient.getBalance({ address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', blockNumber: 69420n // [!code focus] @@ -70,7 +68,9 @@ const balance = await publicClient.getBalance({ The balance of the account at a block tag. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const balance = await publicClient.getBalance({ address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', blockTag: 'safe' // [!code focus] @@ -81,7 +81,11 @@ const balance = await publicClient.getBalance({ - You can convert the balance to ether units with [`formatEther`](/docs/utilities/formatEther). -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { formatEther } from 'viem' // [!code focus] + const balance = await publicClient.getBalance({ address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', blockTag: 'safe' diff --git a/site/pages/docs/actions/public/getBlock.md b/site/pages/docs/actions/public/getBlock.md index 81309befe7..d2ea4c33d4 100644 --- a/site/pages/docs/actions/public/getBlock.md +++ b/site/pages/docs/actions/public/getBlock.md @@ -10,28 +10,20 @@ Returns information about a block at a block number, hash or tag. :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' const block = await publicClient.getBlock() // [!code focus:99] -/** - * { - * baseFeePerGas: 10789405161n, - * difficulty: 11569232145203128n, - * extraData: '0x75732d656173742d38', - * ... - * } - */ +// @log: Output: { +// @log: baseFeePerGas: 10789405161n, +// @log: difficulty: 11569232145203128n, +// @log: extraData: '0x75732d656173742d38', +// @log: ... +// @log: } ``` -```ts [client.ts] -import { createPublicClient, http } from 'viem' -import { mainnet } from 'viem/chains' - -export const publicClient = createPublicClient({ - chain: mainnet, - transport: http() -}) +```ts twoslash [client.ts] filename="client.ts" +// [!include ~/snippets/publicClient.ts] ``` ::: @@ -50,7 +42,9 @@ Information about the block. Information at a given block hash. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const block = await publicClient.getBlock({ blockHash: '0x89644bbd5c8d682a2e9611170e6c1f02573d866d286f006cbf517eec7254ec2d' // [!code focus] }) @@ -62,7 +56,9 @@ const block = await publicClient.getBlock({ Information at a given block number. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const block = await publicClient.getBlock({ blockNumber: 42069n // [!code focus] }) @@ -75,7 +71,9 @@ const block = await publicClient.getBlock({ Information at a given block tag. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const block = await publicClient.getBlock({ blockTag: 'safe' // [!code focus] }) @@ -87,7 +85,9 @@ const block = await publicClient.getBlock({ Whether or not to include transactions (as a structured array of `Transaction` objects). -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const block = await publicClient.getBlock({ includeTransactions: true // [!code focus] }) diff --git a/site/pages/docs/actions/public/getBlockNumber.md b/site/pages/docs/actions/public/getBlockNumber.md index 26ba8fe353..06c95f5a43 100644 --- a/site/pages/docs/actions/public/getBlockNumber.md +++ b/site/pages/docs/actions/public/getBlockNumber.md @@ -10,21 +10,15 @@ Returns the number of the most recent block seen. :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' -const block = await publicClient.getBlockNumber() // [!code focus:99] -// 69420n +const blockNumber = await publicClient.getBlockNumber() // [!code focus:99] +// @log: Output: 69420n ``` -```ts [client.ts] -import { createPublicClient, http } from 'viem' -import { mainnet } from 'viem/chains' - -export const publicClient = createPublicClient({ - chain: mainnet, - transport: http() -}) +```ts twoslash [client.ts] filename="client.ts" +// [!include ~/snippets/publicClient.ts] ``` ::: @@ -44,7 +38,9 @@ The number of the block. Time (in ms) that cached block number will remain in memory. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const block = await publicClient.getBlockNumber({ cacheTime: 4_000 // [!code focus] }) diff --git a/site/pages/docs/actions/public/getBlockTransactionCount.md b/site/pages/docs/actions/public/getBlockTransactionCount.md index c3eebd12bc..05d59b4432 100644 --- a/site/pages/docs/actions/public/getBlockTransactionCount.md +++ b/site/pages/docs/actions/public/getBlockTransactionCount.md @@ -10,14 +10,14 @@ Returns the number of Transactions at a block number, hash or tag. :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' const count = await publicClient.getBlockTransactionCount() // [!code focus:99] -// 23 +// @log: Output: 23 ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -43,7 +43,9 @@ The block transaction count. Count at a given block hash. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const count = await publicClient.getBlockTransactionCount({ blockHash: '0x89644bbd5c8d682a2e9611170e6c1f02573d866d286f006cbf517eec7254ec2d' // [!code focus] }) @@ -55,7 +57,9 @@ const count = await publicClient.getBlockTransactionCount({ Count at a given block number. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const block = await publicClient.getBlockTransactionCount({ blockNumber: 42069n // [!code focus] }) @@ -68,7 +72,9 @@ const block = await publicClient.getBlockTransactionCount({ Count at a given block tag. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const block = await publicClient.getBlockTransactionCount({ blockTag: 'safe' // [!code focus] }) diff --git a/site/pages/docs/actions/public/getChainId.md b/site/pages/docs/actions/public/getChainId.md index 6355dfcc89..ee189ed3fc 100644 --- a/site/pages/docs/actions/public/getChainId.md +++ b/site/pages/docs/actions/public/getChainId.md @@ -10,14 +10,14 @@ Returns the chain ID associated with the current network :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' const chainId = await publicClient.getChainId() // [!code focus:99] -// 1 +// @log: 1 ``` -```ts [client.ts] +```ts [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' diff --git a/site/pages/docs/actions/public/getFeeHistory.md b/site/pages/docs/actions/public/getFeeHistory.md index 668a1d6e64..4232e63113 100644 --- a/site/pages/docs/actions/public/getFeeHistory.md +++ b/site/pages/docs/actions/public/getFeeHistory.md @@ -10,7 +10,7 @@ Returns a collection of historical gas information. :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' const feeHistory = await publicClient.getFeeHistory({ // [!code focus:4] @@ -19,7 +19,7 @@ const feeHistory = await publicClient.getFeeHistory({ // [!code focus:4] }) ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -45,7 +45,9 @@ The fee history. 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. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const feeHistory = await publicClient.getFeeHistory({ blockCount: 4, // [!code focus] rewardPercentiles: [25, 75] @@ -58,7 +60,9 @@ const feeHistory = await publicClient.getFeeHistory({ 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. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const feeHistory = await publicClient.getFeeHistory({ blockCount: 4, rewardPercentiles: [25, 75] // [!code focus] @@ -71,7 +75,9 @@ const feeHistory = await publicClient.getFeeHistory({ Highest number block of the requested range. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const feeHistory = await publicClient.getFeeHistory({ blockCount: 4, blockNumber: 1551231n, // [!code focus] @@ -86,7 +92,9 @@ const feeHistory = await publicClient.getFeeHistory({ Highest number block of the requested range. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const feeHistory = await publicClient.getFeeHistory({ blockCount: 4, blockTag: 'safe', // [!code focus] diff --git a/site/pages/docs/actions/public/getFilterChanges.md b/site/pages/docs/actions/public/getFilterChanges.md index 792ef34a0f..a6ecf73371 100644 --- a/site/pages/docs/actions/public/getFilterChanges.md +++ b/site/pages/docs/actions/public/getFilterChanges.md @@ -19,15 +19,15 @@ A Filter can be created from the following actions: :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' const filter = await publicClient.createBlockFilter() // [!code focus:99] const hashes = await publicClient.getFilterChanges({ filter }) -// ["0x10d86dc08ac2f18f00ef0daf7998dcc8673cbcf1f1501eeb2fac1afd2f851128", ...] +// @log: Output: ["0x10d86dc08ac2f18f00ef0daf7998dcc8673cbcf1f1501eeb2fac1afd2f851128", ...] ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -43,7 +43,7 @@ export const publicClient = createPublicClient({ :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' const filter = await publicClient.createContractEventFilter({ // [!code focus:99] @@ -51,12 +51,11 @@ const filter = await publicClient.createContractEventFilter({ // [!code focus:99 abi: wagmiAbi, eventName: 'Transfer' }) -// ... const logs = await publicClient.getFilterChanges({ filter }) -// [{ ... }, { ... }, { ... }] +// @log: Output: [{ ... }, { ... }, { ... }] ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -72,7 +71,7 @@ export const publicClient = createPublicClient({ :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { parseAbiItem } from 'viem' import { publicClient } from './client' @@ -80,12 +79,11 @@ const filter = await publicClient.createEventFilter({ // [!code focus:99] address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'), }) -// ... const logs = await publicClient.getFilterChanges({ filter }) -// [{ ... }, { ... }, { ... }] +// @log: Output: [{ ... }, { ... }, { ... }] ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -101,15 +99,15 @@ export const publicClient = createPublicClient({ :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' const filter = await publicClient.createPendingTransactionFilter() // [!code focus:99] const hashes = await publicClient.getFilterChanges({ filter }) -// ["0x89b3aa1c01ca4da5d15eca9fab459d062db5c0c9b76609acb0741901f01f6d19", ...] +// @log: Output: ["0x89b3aa1c01ca4da5d15eca9fab459d062db5c0c9b76609acb0741901f01f6d19", ...] ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -147,7 +145,9 @@ If the filter was created with `createBlockFilter`, it returns a list of block h A created filter. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const filter = await publicClient.createPendingTransactionFilter() const logs = await publicClient.getFilterChanges({ filter, // [!code focus] diff --git a/site/pages/docs/actions/public/getFilterLogs.md b/site/pages/docs/actions/public/getFilterLogs.md index baac8b84b7..c90c6409bd 100644 --- a/site/pages/docs/actions/public/getFilterLogs.md +++ b/site/pages/docs/actions/public/getFilterLogs.md @@ -12,7 +12,7 @@ Note: `getFilterLogs` is only compatible with **event filters**. :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { parseAbiItem } from 'viem' import { publicClient } from './client' @@ -20,12 +20,11 @@ const filter = await publicClient.createEventFilter({ // [!code focus:99] address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'), }) -// ... const logs = await publicClient.getFilterLogs({ filter }) -// [{ ... }, { ... }, { ... }] +// @log: [{ ... }, { ... }, { ... }] ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -52,7 +51,9 @@ A list of event logs. An **event** filter. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const filter = await publicClient.createEventFilter() const logs = await publicClient.getFilterChanges({ filter, // [!code focus] diff --git a/site/pages/docs/actions/public/getGasPrice.md b/site/pages/docs/actions/public/getGasPrice.md index 72edf0ceae..c79918f0ea 100644 --- a/site/pages/docs/actions/public/getGasPrice.md +++ b/site/pages/docs/actions/public/getGasPrice.md @@ -10,13 +10,13 @@ Returns the current price of gas (in wei). :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' const gasPrice = await publicClient.getGasPrice() // [!code focus:4] ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' diff --git a/site/pages/docs/actions/public/getLogs.md b/site/pages/docs/actions/public/getLogs.md index 2859b2f9ef..5cf828ba7e 100644 --- a/site/pages/docs/actions/public/getLogs.md +++ b/site/pages/docs/actions/public/getLogs.md @@ -12,14 +12,14 @@ By default, `getLogs` returns all events. In practice, you must use scoping to f :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' const logs = await publicClient.getLogs() // [!code focus:99] -// [{ ... }, { ... }, { ... }] +// @log: Output: [{ ... }, { ... }, { ... }] ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -37,7 +37,7 @@ You can also scope to a set of given attributes. :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { parseAbiItem } from 'viem' import { publicClient } from './client' @@ -53,7 +53,7 @@ const logs = await publicClient.getLogs({ // [!code focus:99] }) ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -69,7 +69,7 @@ By default, `event` accepts the [`AbiEvent`](/docs/glossary/types#abievent) type :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' const logs = await publicClient.getLogs(publicClient, { @@ -91,7 +91,7 @@ const logs = await publicClient.getLogs(publicClient, { }) ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -109,7 +109,7 @@ Logs can be scoped to an **address**: :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' const logs = await publicClient.getLogs({ @@ -117,7 +117,7 @@ const logs = await publicClient.getLogs({ }) ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -137,7 +137,7 @@ The `event` argument takes in an event in ABI format – we have a [`parseAbiIte :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { parseAbiItem } from 'viem' // [!code focus] import { publicClient } from './client' @@ -147,7 +147,7 @@ const logs = await publicClient.getLogs({ }) ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -163,7 +163,11 @@ export const publicClient = createPublicClient({ Logs can be scoped to given **_indexed_ arguments**: -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseAbiItem } from 'viem' + const logs = await publicClient.getLogs({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'), @@ -178,7 +182,11 @@ Only indexed arguments in `event` are candidates for `args`. An argument can also be an array to indicate that other values can exist in the position: -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseAbiItem } from 'viem' + const logs = await publicClient.getLogs({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'), @@ -197,7 +205,11 @@ const logs = await publicClient.getLogs({ Logs can be scoped to a **block range**: -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseAbiItem } from 'viem' + const logs = await publicClient.getLogs({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'), @@ -210,7 +222,11 @@ const logs = await publicClient.getLogs({ Logs can be scoped to **multiple events**: -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseAbi } from 'viem' + const logs = await publicClient.getLogs({ events: parseAbi([ // [!code focus:4] 'event Approval(address indexed owner, address indexed sender, uint256 value)', @@ -226,19 +242,33 @@ Note: Logs scoped to multiple events cannot be also scoped with [indexed argumen By default, `getLogs` will include logs that [do not conform](/docs/glossary/terms#non-conforming-log) to the indexed & non-indexed arguments on the `event`. viem will not return a value for arguments that do not conform to the ABI, thus, some arguments on `args` may be undefined. -```ts {7} +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseAbiItem } from 'viem' + const logs = await publicClient.getLogs({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)') }) logs[0].args -// ^? { address?: Address, to?: Address, value?: bigint } +// ^? + + + + + + ``` You can turn on `strict` mode to only return logs that conform to the indexed & non-indexed arguments on the `event`, meaning that `args` will always be defined. The trade-off is that non-conforming logs will be filtered out. -```ts {7} +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseAbiItem } from 'viem' + const logs = await publicClient.getLogs({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'), @@ -246,7 +276,13 @@ const logs = await publicClient.getLogs({ }) logs[0].args -// ^? { address: Address, to: Address, value: bigint } +// ^? + + + + + + ``` ## Returns @@ -263,7 +299,9 @@ A list of event logs. A contract address or a list of contract addresses. Only logs originating from the contract(s) will be included in the result. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const logs = await publicClient.getLogs({ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', // [!code focus] }) @@ -277,7 +315,11 @@ The event in ABI format. A [`parseAbiItem` utility](/docs/abi/parseAbiItem) is exported from viem that converts from a human-readable event signature → ABI. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseAbiItem } from 'viem' + const logs = await publicClient.getLogs({ event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'), // [!code focus] }) @@ -289,7 +331,11 @@ const logs = await publicClient.getLogs({ A list of _indexed_ event arguments. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseAbiItem } from 'viem' + const logs = await publicClient.getLogs({ event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'), args: { // [!code focus:4] @@ -305,7 +351,9 @@ const logs = await publicClient.getLogs({ Block to start including logs from. Mutually exclusive with `blockHash`. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const filter = await publicClient.createEventFilter({ fromBlock: 69420n // [!code focus] }) @@ -317,7 +365,9 @@ const filter = await publicClient.createEventFilter({ Block to stop including logs from. Mutually exclusive with `blockHash`. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const filter = await publicClient.createEventFilter({ toBlock: 70120n // [!code focus] }) @@ -329,7 +379,9 @@ const filter = await publicClient.createEventFilter({ Block hash to include logs from. Mutually exclusive with `fromBlock`/`toBlock`. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const logs = await publicClient.getLogs({ blockHash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d' // [!code focus] }) diff --git a/site/pages/docs/actions/public/getProof.md b/site/pages/docs/actions/public/getProof.md index 0e8e985350..b7c823e7f5 100644 --- a/site/pages/docs/actions/public/getProof.md +++ b/site/pages/docs/actions/public/getProof.md @@ -10,7 +10,7 @@ Returns the account and storage values of the specified account including the Me :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' const proof = await publicClient.getProof({ @@ -21,7 +21,7 @@ const proof = await publicClient.getProof({ }) ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { optimism } from 'viem/chains' @@ -47,7 +47,9 @@ Proof data. Account address. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const proof = await publicClient.getProof({ address: '0x4200000000000000000000000000000000000016', // [!code focus] storageKeys: [ @@ -63,7 +65,9 @@ const proof = await publicClient.getProof({ Array of storage-keys that should be proofed and included. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const proof = await publicClient.getProof({ address: '0x4200000000000000000000000000000000000016', storageKeys: [ // [!code focus:3] diff --git a/site/pages/docs/actions/public/getTransaction.md b/site/pages/docs/actions/public/getTransaction.md index 06821f8718..bf65521b88 100644 --- a/site/pages/docs/actions/public/getTransaction.md +++ b/site/pages/docs/actions/public/getTransaction.md @@ -10,23 +10,21 @@ Returns information about a [Transaction](/docs/glossary/terms#transaction) give :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' const transaction = await publicClient.getTransaction({ // [!code focus:99] hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d' }) -/** - * { - * blockHash: '0xaf1dadb8a98f1282e8f7b42cc3da8847bfa2cf4e227b8220403ae642e1173088', - * blockNumber: 15132008n, - * from: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', - * ... - * } - */ +// @log: { +// @log: blockHash: '0xaf1dadb8a98f1282e8f7b42cc3da8847bfa2cf4e227b8220403ae642e1173088', +// @log: blockNumber: 15132008n, +// @log: from: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', +// @log: ... +// @log: } ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -52,7 +50,9 @@ The transaction information. Get information about a transaction given a transaction hash. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const transaction = await publicClient.getTransaction({ hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d' // [!code focus] }) @@ -64,7 +64,9 @@ const transaction = await publicClient.getTransaction({ Get information about a transaction given a block hash (and index). -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const transaction = await publicClient.getTransaction({ blockHash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', // [!code focus:2] index: 0 @@ -77,7 +79,9 @@ const transaction = await publicClient.getTransaction({ Get information about a transaction given a block number (and index). -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const transaction = await publicClient.getTransaction({ blockNumber: 69420n, // [!code focus:2] index: 0 @@ -90,7 +94,9 @@ const transaction = await publicClient.getTransaction({ Get information about a transaction given a block tag (and index). -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const transaction = await publicClient.getTransaction({ blockTag: 'safe', // [!code focus:2] index: 0 @@ -103,7 +109,9 @@ const transaction = await publicClient.getTransaction({ An index to be used with a block identifier (number, hash or tag). -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const transaction = await publicClient.getTransaction({ blockTag: 'safe', index: 0 // [!code focus] diff --git a/site/pages/docs/actions/public/getTransactionConfirmations.md b/site/pages/docs/actions/public/getTransactionConfirmations.md index f76b0f78dc..62d88bf9c9 100644 --- a/site/pages/docs/actions/public/getTransactionConfirmations.md +++ b/site/pages/docs/actions/public/getTransactionConfirmations.md @@ -10,7 +10,7 @@ Returns the number of blocks passed (confirmations) since the transaction was pr :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' const transactionReceipt = await publicClient.getTransactionReceipt({ hash: '...' }) @@ -20,7 +20,7 @@ const confirmations = await publicClient.getTransactionConfirmations({ // [!cod // 15n ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -36,16 +36,16 @@ You can also fetch confirmations by Transaction hash: :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' const confirmations = await publicClient.getTransactionConfirmations({ // [!code focus:99] hash: '0x...' }) -// 15n +// @log: 15n ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -71,7 +71,10 @@ The number of blocks passed since the transaction was processed. If confirmation The transaction receipt. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +// @noErrors const balance = await publicClient.getTransactionConfirmations({ transactionReceipt: { ... }, // [!code focus] }) @@ -83,7 +86,9 @@ const balance = await publicClient.getTransactionConfirmations({ The hash of the transaction. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const balance = await publicClient.getTransactionConfirmations({ hash: '0x...' // [!code focus] }) diff --git a/site/pages/docs/actions/public/getTransactionCount.md b/site/pages/docs/actions/public/getTransactionCount.md index 71978fbab9..1bae15a855 100644 --- a/site/pages/docs/actions/public/getTransactionCount.md +++ b/site/pages/docs/actions/public/getTransactionCount.md @@ -10,23 +10,17 @@ Returns the number of [Transactions](/docs/glossary/terms#transaction) an Accoun :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' const transactionCount = await publicClient.getTransactionCount({ // [!code focus:99] address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', }) -// 420 +// @log: > 420 ``` -```ts [client.ts] -import { createPublicClient, http } from 'viem' -import { mainnet } from 'viem/chains' - -export const publicClient = createPublicClient({ - chain: mainnet, - transport: http() -}) +```ts [client.ts] filename="client.ts" +// [!include ~/snippets/publicClient.ts] ``` ::: @@ -45,7 +39,9 @@ The number of transactions an account has sent. The address of the account. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const transactionCount = await publicClient.getTransactionCount({ address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', // [!code focus] }) @@ -57,7 +53,9 @@ const transactionCount = await publicClient.getTransactionCount({ Get the count at a block number. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const transactionCount = await publicClient.getTransactionCount({ address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', blockNumber: 69420n // [!code focus] @@ -70,7 +68,9 @@ const transactionCount = await publicClient.getTransactionCount({ Get the count at a block tag. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const transactionCount = await publicClient.getTransactionCount({ address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', blockTag: 'safe' // [!code focus] diff --git a/site/pages/docs/actions/public/getTransactionReceipt.md b/site/pages/docs/actions/public/getTransactionReceipt.md index 9b880c1a0d..a8985420bc 100644 --- a/site/pages/docs/actions/public/getTransactionReceipt.md +++ b/site/pages/docs/actions/public/getTransactionReceipt.md @@ -10,24 +10,22 @@ Returns the [Transaction Receipt](/docs/glossary/terms#transaction-receipt) give :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' const transaction = await publicClient.getTransactionReceipt({ // [!code focus:99] hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d' }) -/** - * { - * blockHash: '0xaf1dadb8a98f1282e8f7b42cc3da8847bfa2cf4e227b8220403ae642e1173088', - * blockNumber: 15132008n, - * from: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', - * ... - * status: 'success', - * } - */ +// @log: { +// @log: blockHash: '0xaf1dadb8a98f1282e8f7b42cc3da8847bfa2cf4e227b8220403ae642e1173088', +// @log: blockNumber: 15132008n, +// @log: from: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', +// @log: ... +// @log: status: 'success', +// @log: } ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -53,7 +51,9 @@ The transaction receipt. A transaction hash. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const transaction = await publicClient.getTransactionReceipt({ hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d' // [!code focus] }) diff --git a/site/pages/docs/actions/public/uninstallFilter.md b/site/pages/docs/actions/public/uninstallFilter.md index e9f17786b0..8d5d9a9fe9 100644 --- a/site/pages/docs/actions/public/uninstallFilter.md +++ b/site/pages/docs/actions/public/uninstallFilter.md @@ -14,7 +14,7 @@ Destroys a [`Filter`](/docs/glossary/types#filter) that was created from one of :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' const filter = await publicClient.createPendingTransactionFilter() @@ -22,7 +22,7 @@ const uninstalled = await publicClient.uninstallFilter({ filter }) // [!code foc // true ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -48,7 +48,9 @@ A boolean indicating if the Filter was successfully uninstalled. A created filter. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const filter = await publicClient.createPendingTransactionFilter() const uninstalled = await publicClient.uninstallFilter({ filter, // [!code focus] diff --git a/site/pages/docs/actions/public/verifyMessage.md b/site/pages/docs/actions/public/verifyMessage.md index 56d8940033..f59b975ff8 100644 --- a/site/pages/docs/actions/public/verifyMessage.md +++ b/site/pages/docs/actions/public/verifyMessage.md @@ -6,7 +6,9 @@ description: Verifies if a signed message was generated by the provided address. Verify that a message was signed by the provided address. -:::info 💡 Why should I use this over the [`verifyMessage`](../../utilities/verifyMessage.md) util? +:::info +**Why should I use this over the [`verifyMessage`](../../utilities/verifyMessage.md) util?** + This Action supports verifying messages that were signed by either a Smart Contract Account or Externally Owned Account. The [`verifyMessage`](../../utilities/verifyMessage.md) util only supports Externally Owned Accounts. This is getting increasingly important as more wallets implement [Account Abstraction](https://eips.ethereum.org/EIPS/eip-4337). ::: @@ -14,7 +16,7 @@ This Action supports verifying messages that were signed by either a Smart Contr :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { account, walletClient, publicClient } from './client' const signature = await walletClient.signMessage({ @@ -27,11 +29,13 @@ const valid = await publicClient.verifyMessage({ message: 'hello world', signature, }) -// true +// @log: true ``` -```ts [client.ts] -import { createPublicClient, http } from 'viem' +```ts twoslash [client.ts] filename="client.ts" +import 'viem/window' +// ---cut--- +import { createPublicClient, createWalletClient, custom, http } from 'viem' import { mainnet } from 'viem/chains' export const publicClient = createPublicClient({ @@ -40,13 +44,14 @@ export const publicClient = createPublicClient({ }) export const walletClient = createWalletClient({ - transport: custom(window.ethereum) + transport: custom(window.ethereum!) }) -// JSON-RPC Account +// @log: ↓ JSON-RPC Account export const [account] = await walletClient.getAddresses() -// Local Account -export const account = privateKeyToAccount(...) + +// @log: ↓ Local Account +// export const account = privateKeyToAccount(...) ``` ::: @@ -65,7 +70,9 @@ Wheather the signed message is valid for the given address. The Ethereum address that signed the original message. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const valid = await publicClient.verifyMessage({ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', // [!code focus:1] message: 'hello world', @@ -82,7 +89,9 @@ The message to be verified. By default, viem verifies the UTF-8 representation of the message. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const valid = await publicClient.verifyMessage({ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message: 'hello world', // [!code focus:1] @@ -93,7 +102,9 @@ const valid = await publicClient.verifyMessage({ To verify the data representation of the message, you can use the `raw` attribute. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const valid = await publicClient.verifyMessage({ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message: { raw: '0x68656c6c6f20776f726c64' }, // [!code focus:1] @@ -108,7 +119,9 @@ const valid = await publicClient.verifyMessage({ The signature that was generated by signing the message with the address's signer. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const valid = await publicClient.verifyMessage({ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message: 'hello world', @@ -123,7 +136,9 @@ const valid = await publicClient.verifyMessage({ Only used when verifying a message that was signed by a Smart Contract Account. The block number to check if the contract was already deployed. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const valid = await publicClient.verifyMessage({ blockNumber: 42069n, // [!code focus] address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', @@ -140,7 +155,9 @@ const valid = await publicClient.verifyMessage({ Only used when verifying a message that was signed by a Smart Contract Account. The block tag to check if the contract was already deployed. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const valid = await publicClient.verifyMessage({ blockTag: 'safe', // [!code focus] address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', diff --git a/site/pages/docs/actions/public/verifyTypedData.md b/site/pages/docs/actions/public/verifyTypedData.md index ebb1dc7d8c..1ed376464f 100644 --- a/site/pages/docs/actions/public/verifyTypedData.md +++ b/site/pages/docs/actions/public/verifyTypedData.md @@ -6,7 +6,9 @@ description: Verifies a typed data signature Verify that typed data was signed by the provided address. -:::info 💡 Why should I use this over the [`verifyTypedData`](../../utilities/verifyTypedData.md) util? +:::info +**Why should I use this over the [`verifyTypedData`](../../utilities/verifyTypedData.md) util?** + This Action supports verifying typed data that was signed by either a Smart Contract Account or Externally Owned Account (via [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492)). The [`verifyTypedData`](../../utilities/verifyTypedData.md) util only supports Externally Owned Accounts. This is getting increasingly important as more wallets implement [Account Abstraction](https://eips.ethereum.org/EIPS/eip-4337). ::: @@ -14,8 +16,9 @@ This Action supports verifying typed data that was signed by either a Smart Cont :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { account, walletClient, publicClient } from './client' +import { domain, types } from './data' const message = { from: { @@ -27,7 +30,7 @@ const message = { wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', -} as const +} const signature = await walletClient.signTypedData({ account, @@ -48,7 +51,7 @@ const valid = await publicClient.verifyTypedData({ // true ``` -```ts [data.ts] +```ts twoslash [data.ts] filename="data.ts" // All properties on a domain are optional export const domain = { name: 'Ether Mail', @@ -71,8 +74,10 @@ export const types = { } as const ``` -```ts [client.ts] -import { createPublicClient, http } from 'viem' +```ts twoslash [client.ts] filename="client.ts" +import 'viem/window' +// ---cut--- +import { createPublicClient, createWalletClient, custom, http } from 'viem' import { mainnet } from 'viem/chains' export const publicClient = createPublicClient({ @@ -81,13 +86,14 @@ export const publicClient = createPublicClient({ }) export const walletClient = createWalletClient({ - transport: custom(window.ethereum) + transport: custom(window.ethereum!) }) -// JSON-RPC Account +// @log: ↓ JSON-RPC Account export const [account] = await walletClient.getAddresses() -// Local Account -export const account = privateKeyToAccount(...) + +// @log: ↓ Local Account +// export const account = privateKeyToAccount(...) ``` ::: @@ -106,8 +112,10 @@ Wheather the signed message is valid for the given address. The Ethereum address that signed the original message. -```ts -const valid = await verifyTypedData({ +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +const valid = await publicClient.verifyTypedData({ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', // [!code focus:1] domain: { name: 'Ether Mail', @@ -115,7 +123,17 @@ const valid = await verifyTypedData({ chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', }, - types, + 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: { @@ -138,8 +156,10 @@ const valid = await verifyTypedData({ The typed data domain. -```ts -const valid = await verifyTypedData({ +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +const valid = await publicClient.verifyTypedData({ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', domain: { // [!code focus:6] name: 'Ether Mail', @@ -147,7 +167,17 @@ const valid = await verifyTypedData({ chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', }, - types, + 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: { @@ -168,10 +198,17 @@ const valid = await verifyTypedData({ The type definitions for the typed data. -```ts -const valid = await verifyTypedData({ +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +const valid = await publicClient.verifyTypedData({ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', - domain, + domain: { + name: 'Ether Mail', + version: '1', + chainId: 1, + verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', + }, types: { // [!code focus:11] Person: [ { name: 'name', type: 'string' }, @@ -205,10 +242,17 @@ const valid = await verifyTypedData({ The primary type to extract from `types` and use in `value`. -```ts -const valid = await verifyTypedData({ +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +const valid = await publicClient.verifyTypedData({ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', - domain, + domain: { + name: 'Ether Mail', + version: '1', + chainId: 1, + verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', + }, types: { Person: [ { name: 'name', type: 'string' }, @@ -240,10 +284,17 @@ const valid = await verifyTypedData({ **Type:** Inferred from `types` & `primaryType`. -```ts -const valid = await verifyTypedData({ +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +const valid = await publicClient.verifyTypedData({ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', - domain, + domain: { + name: 'Ether Mail', + version: '1', + chainId: 1, + verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', + }, types: { Person: [ { name: 'name', type: 'string' }, @@ -277,10 +328,17 @@ const valid = await verifyTypedData({ The signature of the typed data. -```ts -const valid = await verifyTypedData({ +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +const valid = await publicClient.verifyTypedData({ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', - domain, + domain: { + name: 'Ether Mail', + version: '1', + chainId: 1, + verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', + }, types: { Person: [ { name: 'name', type: 'string' }, @@ -314,8 +372,10 @@ const valid = await verifyTypedData({ Only used when verifying a typed data that was signed by a Smart Contract Account. The block number to check if the contract was already deployed. -```ts -const valid = await verifyTypedData({ +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +const valid = await publicClient.verifyTypedData({ blockNumber: 42069n, // [!code focus] address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', domain: { @@ -324,7 +384,17 @@ const valid = await verifyTypedData({ chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', }, - types, + 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: { @@ -348,8 +418,10 @@ const valid = await verifyTypedData({ Only used when verifying a typed data that was signed by a Smart Contract Account. The block tag to check if the contract was already deployed. -```ts -const valid = await verifyTypedData({ +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +const valid = await publicClient.verifyTypedData({ blockNumber: 42069n, // [!code focus] address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', domain: { @@ -358,7 +430,17 @@ const valid = await verifyTypedData({ chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', }, - types, + 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: { diff --git a/site/pages/docs/actions/public/waitForTransactionReceipt.md b/site/pages/docs/actions/public/waitForTransactionReceipt.md index e870667414..63b5e927dc 100644 --- a/site/pages/docs/actions/public/waitForTransactionReceipt.md +++ b/site/pages/docs/actions/public/waitForTransactionReceipt.md @@ -12,24 +12,22 @@ The `waitForTransactionReceipt` action additionally supports Replacement detecti :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' const transaction = await publicClient.waitForTransactionReceipt( // [!code focus:99] { hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d' } ) -/** - * { - * blockHash: '0xaf1dadb8a98f1282e8f7b42cc3da8847bfa2cf4e227b8220403ae642e1173088', - * blockNumber: 15132008n, - * from: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', - * ... - * status: 'success', - * } - */ +// @log: { +// @log: blockHash: '0xaf1dadb8a98f1282e8f7b42cc3da8847bfa2cf4e227b8220403ae642e1173088', +// @log: blockNumber: 15132008n, +// @log: from: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', +// @log: ... +// @log: status: 'success', +// @log: } ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -56,7 +54,9 @@ The transaction receipt. The number of confirmations (blocks that have passed) to wait before resolving. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const transaction = await publicClient.waitForTransactionReceipt( { confirmations: 5, // [!code focus:1] @@ -71,7 +71,9 @@ const transaction = await publicClient.waitForTransactionReceipt( Optional callback to emit if the transaction has been replaced. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const transaction = await publicClient.waitForTransactionReceipt( { hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', @@ -86,7 +88,9 @@ const transaction = await publicClient.waitForTransactionReceipt( Polling frequency (in ms). Defaults to the Client's `pollingInterval` config. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const transaction = await publicClient.waitForTransactionReceipt( { hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', @@ -133,7 +137,9 @@ const transaction = await publicClient.waitForTransactionReceipt( Optional timeout (in milliseconds) to wait before stopping polling. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const transaction = await publicClient.waitForTransactionReceipt( { hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', diff --git a/site/pages/docs/actions/public/watchBlockNumber.md b/site/pages/docs/actions/public/watchBlockNumber.md index a613acef68..6abdef8b55 100644 --- a/site/pages/docs/actions/public/watchBlockNumber.md +++ b/site/pages/docs/actions/public/watchBlockNumber.md @@ -12,20 +12,18 @@ Pass through your Public Client, along with a listener. :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' const unwatch = publicClient.watchBlockNumber( // [!code focus:99] { onBlockNumber: blockNumber => console.log(blockNumber) } ) -/** - * > 69420n - * > 69421n - * > 69422n - */ +// @log: > 69420n +// @log: > 69421n +// @log: > 69422n ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -60,7 +58,9 @@ Whether or not to emit missed block numbers to the callback. Missed block numbers may occur in instances where internet connection is lost, or the block time is lesser than the [polling interval](/docs/clients/public#pollinginterval-optional) of the client. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const unwatch = publicClient.watchBlockNumber( { emitMissed: true, // [!code focus] @@ -76,7 +76,9 @@ const unwatch = publicClient.watchBlockNumber( Whether or not to emit the latest block number to the callback when the subscription opens. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const unwatch = publicClient.watchBlockNumber( { emitOnBegin: true, // [!code focus] @@ -94,7 +96,7 @@ Whether or not to use a polling mechanism to check for new block numbers instead This option is only configurable for Clients with a [WebSocket Transport](/docs/clients/transports/websocket). -```ts +```ts twoslash import { createPublicClient, webSocket } from 'viem' import { mainnet } from 'viem/chains' @@ -117,7 +119,9 @@ const unwatch = publicClient.watchBlockNumber( Polling frequency (in ms). Defaults to Client's `pollingInterval` config. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const unwatch = publicClient.watchBlockNumber( { onBlockNumber: blockNumber => console.log(blockNumber), diff --git a/site/pages/docs/actions/public/watchBlocks.md b/site/pages/docs/actions/public/watchBlocks.md index 47cbe3b81b..0298322135 100644 --- a/site/pages/docs/actions/public/watchBlocks.md +++ b/site/pages/docs/actions/public/watchBlocks.md @@ -12,30 +12,28 @@ Pass through your Public Client, along with a listener. :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' const unwatch = publicClient.watchBlocks( // [!code focus:99] { onBlock: block => console.log(block) } ) -/** - * > { - * baseFeePerGas: 10789405161n, - * difficulty: 11569232145203128n, - * extraData: '0x75732d656173742d38', - * ... - * } - * - * > { - * baseFeePerGas: 12394051511n, - * difficulty: 11512315412421123n, - * extraData: '0x5123ab1512dd14aa', - * ... - * } - */ +// @log: > { +// @log: baseFeePerGas: 10789405161n, +// @log: difficulty: 11569232145203128n, +// @log: extraData: '0x75732d656173742d38', +// @log: ... +// @log: } + +// @log: > { +// @log: baseFeePerGas: 12394051511n, +// @log: difficulty: 11512315412421123n, +// @log: extraData: '0x5123ab1512dd14aa', +// @log: ... +// @log: } ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -61,7 +59,9 @@ A function that can be invoked to stop watching for new blocks. The block information. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const unwatch = publicClient.watchBlocks( { onBlock: block => console.log(block) } // [!code focus:1] ) @@ -73,7 +73,9 @@ const unwatch = publicClient.watchBlocks( Error thrown from getting a block. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const unwatch = publicClient.watchBlocks( { onBlock: block => console.log(block), @@ -89,7 +91,9 @@ const unwatch = publicClient.watchBlocks( Watch for new blocks on a given tag. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const unwatch = publicClient.watchBlocks( { blockTag: 'safe', @@ -107,7 +111,9 @@ Whether or not to emit missed blocks to the callback. Missed blocks may occur in instances where internet connection is lost, or the block time is lesser than the [polling interval](/docs/clients/public#pollinginterval-optional) of the client. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const unwatch = publicClient.watchBlocks( { emitMissed: true, // [!code focus] @@ -123,7 +129,9 @@ const unwatch = publicClient.watchBlocks( Whether or not to emit the block to the callback when the subscription opens. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const unwatch = publicClient.watchBlocks( { emitOnBegin: true, // [!code focus] @@ -138,7 +146,9 @@ const unwatch = publicClient.watchBlocks( Whether or not to include transactions (as a structured array of `Transaction` objects). -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const unwatch = publicClient.watchBlocks( { includeTransactions: true, // [!code focus] @@ -156,7 +166,7 @@ Whether or not to use a polling mechanism to check for new blocks instead of a W This option is only configurable for Clients with a [WebSocket Transport](/docs/clients/transports/websocket). -```ts +```ts twoslash import { createPublicClient, webSocket } from 'viem' import { mainnet } from 'viem/chains' @@ -179,7 +189,9 @@ const unwatch = publicClient.watchBlocks( Polling frequency (in ms). Defaults to the Client's `pollingInterval` config. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const unwatch = publicClient.watchBlocks( { onBlock: block => console.log(block), diff --git a/site/pages/docs/actions/public/watchEvent.md b/site/pages/docs/actions/public/watchEvent.md index b032308638..607994c394 100644 --- a/site/pages/docs/actions/public/watchEvent.md +++ b/site/pages/docs/actions/public/watchEvent.md @@ -18,19 +18,19 @@ These events will be batched up into [Event Logs](/docs/glossary/terms#event-log :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' import { wagmiAbi } from './abi' const unwatch = publicClient.watchEvent({ onLogs: logs => console.log(logs) }) -// > [{ ... }, { ... }, { ... }] -// > [{ ... }, { ... }] -// > [{ ... }, { ... }, { ... }, { ... }] +// @log: > [{ ... }, { ... }, { ... }] +// @log: > [{ ... }, { ... }] +// @log: > [{ ... }, { ... }, { ... }, { ... }] ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -52,7 +52,7 @@ You can also scope `watchEvent` to a set of given attributes (listed below). :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' import { wagmiAbi } from './abi' @@ -60,12 +60,12 @@ const unwatch = publicClient.watchEvent({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', // [!code focus] onLogs: logs => console.log(logs) }) -// > [{ ... }, { ... }, { ... }] -// > [{ ... }, { ... }] -// > [{ ... }, { ... }, { ... }, { ... }] +// @log: > [{ ... }, { ... }, { ... }] +// @log: > [{ ... }, { ... }] +// @log: > [{ ... }, { ... }, { ... }, { ... }] ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -85,7 +85,7 @@ The `event` argument takes in an event in ABI format – we have a [`parseAbiIte :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { parseAbiItem } from 'viem' // [!code focus] import { publicClient } from './client' import { wagmiAbi } from './abi' @@ -95,12 +95,12 @@ const unwatch = publicClient.watchEvent({ event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'), // [!code focus] onLogs: logs => console.log(logs) }) -// > [{ ... }, { ... }, { ... }] -// > [{ ... }, { ... }] -// > [{ ... }, { ... }, { ... }, { ... }] +// @log: > [{ ... }, { ... }, { ... }] +// @log: > [{ ... }, { ... }] +// @log: > [{ ... }, { ... }, { ... }, { ... }] ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -116,7 +116,7 @@ By default, `event` accepts the [`AbiEvent`](/docs/glossary/types#abievent) type :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' const unwatch = publicClient.watchEvent(publicClient, { @@ -133,7 +133,7 @@ const unwatch = publicClient.watchEvent(publicClient, { }) ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -151,7 +151,7 @@ export const publicClient = createPublicClient({ :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { parseAbiItem } from 'viem' import { publicClient } from './client' @@ -169,7 +169,7 @@ const unwatch = publicClient.watchEvent({ // > [{ ... }, { ... }, { ... }, { ... }] ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -185,7 +185,11 @@ Only indexed arguments in `event` are candidates for `args`. These arguments can also be an array to indicate that other values can exist in the position: -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseAbiItem } from 'viem' + const unwatch = publicClient.watchEvent({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'), @@ -196,7 +200,7 @@ const unwatch = publicClient.watchEvent({ '0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac', '0xa152f8bb749c55e9943a3a0a3111d18ee2b3f94e', ], - } + }, onLogs: logs => console.log(logs) }) ``` @@ -205,7 +209,11 @@ const unwatch = publicClient.watchEvent({ `watchEvent` can be scoped to **multiple events**: -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseAbi } from 'viem' + const unwatch = publicClient.watchEvent({ events: parseAbi([ // [!code focus:5] 'event Approval(address indexed owner, address indexed sender, uint256 value)', @@ -231,7 +239,9 @@ A function that can be invoked to stop watching for new Event Logs. The new Event Logs. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const unwatch = publicClient.watchEvent( { onLogs: logs => console.log(logs) } // [!code focus:1] ) @@ -243,7 +253,9 @@ const unwatch = publicClient.watchEvent( The contract address or a list of addresses from which Logs should originate. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const unwatch = publicClient.watchEvent( { address: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2', // [!code focus] @@ -260,7 +272,9 @@ The event in ABI format. A [`parseAbiItem` utility](/docs/abi/parseAbiItem) is exported from viem that converts from a human-readable event signature → ABI. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- import { parseAbiItem } from 'viem' // [!code focus] const unwatch = publicClient.watchEvent( @@ -278,15 +292,19 @@ const unwatch = publicClient.watchEvent( A list of _indexed_ event arguments. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +import { parseAbiItem } from 'viem' + const unwatch = publicClient.watchEvent( { address: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2', event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'), args: { // [!code focus:4] - from: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', + from: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', to: '0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac' - } + }, onLogs: logs => console.log(logs) } ) @@ -299,7 +317,9 @@ const unwatch = publicClient.watchEvent( Whether or not to batch the Event Logs between polling intervals. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const unwatch = publicClient.watchEvent( { batch: false, // [!code focus] @@ -314,7 +334,9 @@ const unwatch = publicClient.watchEvent( Error thrown from listening for new Event Logs. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const unwatch = publicClient.watchEvent( { onError: error => console.log(error) // [!code focus:1] @@ -332,7 +354,7 @@ Whether or not to use a polling mechanism to check for new logs instead of a Web This option is only configurable for Clients with a [WebSocket Transport](/docs/clients/transports/websocket). -```ts +```ts twoslash import { createPublicClient, webSocket } from 'viem' import { mainnet } from 'viem/chains' @@ -355,7 +377,9 @@ const unwatch = publicClient.watchEvent( Polling frequency (in ms). Defaults to the Client's `pollingInterval` config. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const unwatch = publicClient.watchEvent( { pollingInterval: 1_000, // [!code focus] diff --git a/site/pages/docs/actions/public/watchPendingTransactions.md b/site/pages/docs/actions/public/watchPendingTransactions.md index 75e683c739..fce5671c45 100644 --- a/site/pages/docs/actions/public/watchPendingTransactions.md +++ b/site/pages/docs/actions/public/watchPendingTransactions.md @@ -13,20 +13,18 @@ This Action will batch up all the pending transactions found within the [`pollin :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { publicClient } from './client' const unwatch = publicClient.watchPendingTransactions( // [!code focus:99] { onTransactions: hashes => console.log(hashes) } ) -/** - * > ['0x...', '0x...', '0x...'] - * > ['0x...', '0x...'] - * > ['0x...', '0x...', '0x...', ...] - */ +// @log: > ['0x...', '0x...', '0x...'] +// @log: > ['0x...', '0x...'] +// @log: > ['0x...', '0x...', '0x...', ...] ``` -```ts [client.ts] +```ts twoslash [client.ts] filename="client.ts" import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -52,7 +50,9 @@ A function that can be invoked to stop watching for new pending transaction hash The new pending transaction hashes. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const unwatch = publicClient.watchPendingTransactions( { onTransactions: hashes => console.log(hashes) } // [!code focus:1] ) @@ -65,7 +65,9 @@ const unwatch = publicClient.watchPendingTransactions( Whether or not to batch the transaction hashes between polling intervals. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- const unwatch = publicClient.watchPendingTransactions( { batch: false, // [!code focus] @@ -80,10 +82,13 @@ const unwatch = publicClient.watchPendingTransactions( Error thrown from listening for new pending transactions. -```ts +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +// @noErrors const unwatch = publicClient.watchPendingTransactions( { - onError: error => console.log(error) // [!code focus:1] + onError: error => console.log(error), // [!code focus:1] onTransactions: hashes => console.log(hashes), } ) @@ -98,7 +103,7 @@ Whether or not to use a polling mechanism to check for new pending transactions This option is only configurable for Clients with a [WebSocket Transport](/docs/clients/transports/websocket). -```ts +```ts twoslash import { createPublicClient, webSocket } from 'viem' import { mainnet } from 'viem/chains' @@ -121,8 +126,11 @@ const unwatch = publicClient.watchPendingTransactions( Polling frequency (in ms). Defaults to the Client's `pollingInterval` config. -```ts -const unwatch = publicClient..watchPendingTransactions( +```ts twoslash +// [!include ~/snippets/publicClient.ts] +// ---cut--- +// @noErrors +const unwatch = publicClient.watchPendingTransactions( { pollingInterval: 1_000, // [!code focus] onTransactions: hashes => console.log(hashes), diff --git a/site/pages/docs/actions/wallet/addChain.md b/site/pages/docs/actions/wallet/addChain.md index e2986f8ab0..68231c643c 100644 --- a/site/pages/docs/actions/wallet/addChain.md +++ b/site/pages/docs/actions/wallet/addChain.md @@ -10,21 +10,15 @@ Adds an EVM chain to the wallet. :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { avalanche } from 'viem/chains' import { walletClient } from './client' await walletClient.addChain({ chain: avalanche }) // [!code focus] ``` -```ts [client.ts] -import { createWalletClient, custom } from 'viem' -import { mainnet } from 'viem/chains' - -export const walletClient = createWalletClient({ - chain: mainnet, - transport: custom(window.ethereum) -}) +```ts twoslash [client.ts] filename="client.ts" +// [!include ~/snippets/walletClient.ts] ``` ::: diff --git a/site/pages/docs/actions/wallet/getAddresses.md b/site/pages/docs/actions/wallet/getAddresses.md index d3ab5d7a5f..50e2a6c0c9 100644 --- a/site/pages/docs/actions/wallet/getAddresses.md +++ b/site/pages/docs/actions/wallet/getAddresses.md @@ -10,21 +10,15 @@ Returns a list of account addresses owned by the wallet or client. :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { walletClient } from './client' const accounts = await walletClient.getAddresses() // [!code focus:99] // ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'] ``` -```ts [client.ts] -import { createWalletClient, custom } from 'viem' -import { mainnet } from 'viem/chains' - -export const walletClient = createWalletClient({ - chain: mainnet, - transport: custom(window.ethereum) -}) +```ts twoslash [client.ts] filename="client.ts" +// [!include ~/snippets/walletClient.ts] ``` ::: diff --git a/site/pages/docs/actions/wallet/getPermissions.md b/site/pages/docs/actions/wallet/getPermissions.md index fceee64aa4..0e6ff4530f 100644 --- a/site/pages/docs/actions/wallet/getPermissions.md +++ b/site/pages/docs/actions/wallet/getPermissions.md @@ -10,20 +10,14 @@ Gets the wallets current permissions. :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { walletClient } from './client' const permissions = await walletClient.getPermissions() // [!code focus:99] ``` -```ts [client.ts] -import { createWalletClient, custom } from 'viem' -import { mainnet } from 'viem/chains' - -export const walletClient = createWalletClient({ - chain: mainnet, - transport: custom(window.ethereum) -}) +```ts twoslash [client.ts] filename="client.ts" +// [!include ~/snippets/walletClient.ts] ``` ::: diff --git a/site/pages/docs/actions/wallet/prepareTransactionRequest.md b/site/pages/docs/actions/wallet/prepareTransactionRequest.md index c9386b18a4..c89537bb6f 100644 --- a/site/pages/docs/actions/wallet/prepareTransactionRequest.md +++ b/site/pages/docs/actions/wallet/prepareTransactionRequest.md @@ -10,7 +10,7 @@ Prepares a transaction request for signing by populating a nonce, gas limit, fee :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { account, walletClient } from './config' const request = await walletClient.prepareTransactionRequest({ // [!code focus:16] @@ -18,36 +18,38 @@ const request = await walletClient.prepareTransactionRequest({ // [!code focus:1 to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n }) -/** - * { - * account: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', - * to: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8', - * maxFeePerGas: 150000000000n, - * maxPriorityFeePerGas: 1000000000n, - * nonce: 69, - * type: 'eip1559', - * value: 1000000000000000000n - * } - */ +// @log: { +// @log: account: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', +// @log: to: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8', +// @log: maxFeePerGas: 150000000000n, +// @log: maxPriorityFeePerGas: 1000000000n, +// @log: nonce: 69, +// @log: type: 'eip1559', +// @log: value: 1000000000000000000n +// @log: } + const signature = await walletClient.signTransaction(request) const hash = await walletClient.sendRawTransaction(signature) ``` -```ts [config.ts] +```ts twoslash [config.ts] filename="config.ts" +import 'viem/window' +// ---cut--- import { createWalletClient, custom } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { mainnet } from 'viem/chains' export const walletClient = createWalletClient({ chain: mainnet, - transport: custom(window.ethereum) + transport: custom(window.ethereum!) }) -// JSON-RPC Account -export const [account] = await walletClient.getAddresses() -// Local Account -export const account = privateKeyToAccount(...) +// @log: ↓ JSON-RPC Account +export const account = '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266' + +// @log: ↓ Local Account +// export const account = privateKeyToAccount(...) ``` ::: @@ -60,30 +62,29 @@ If you do not wish to pass an `account` to every `prepareTransactionRequest`, yo :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { walletClient } from './config' const request = await walletClient.prepareTransactionRequest({ // [!code focus:16] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n }) -/** - * { - * account: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', - * to: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8', - * maxFeePerGas: 150000000000n, - * maxPriorityFeePerGas: 1000000000n, - * nonce: 69, - * type: 'eip1559', - * value: 1000000000000000000n - * } - */ +// @log: { +// @log: account: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', +// @log: to: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8', +// @log: maxFeePerGas: 150000000000n, +// @log: maxPriorityFeePerGas: 1000000000n, +// @log: nonce: 69, +// @log: type: 'eip1559', +// @log: value: 1000000000000000000n +// @log: } + const signature = await walletClient.signTransaction(request) const hash = await walletClient.sendRawTransaction(signature) ``` -```ts [config.ts (JSON-RPC Account)] {4-6,9} +```ts [config.ts (JSON-RPC Account)] import { createWalletClient, custom } from 'viem' // Retrieve Account from an EIP-1193 Provider. @@ -93,17 +94,17 @@ const [account] = await window.ethereum.request({ export const walletClient = createWalletClient({ account, - transport: custom(window.ethereum) + transport: custom(window.ethereum!) }) ``` -```ts [config.ts (Local Account)] {5} -import { createWalletClient, custom } from 'viem' +```ts twoslash [config.ts (Local Account)] filename="config.ts" +import { createWalletClient, http } from 'viem' import { privateKeyToAccount } from 'viem/accounts' export const walletClient = createWalletClient({ account: privateKeyToAccount('0x...'), - transport: custom(window.ethereum) + transport: http() }) ``` @@ -125,7 +126,9 @@ The Account to send the transaction from. Accepts a [JSON-RPC Account](/docs/clients/wallet#json-rpc-accounts) or [Local Account (Private Key, etc)](/docs/clients/wallet#local-accounts-private-key-mnemonic-etc). -```ts +```ts twoslash +// [!include config.ts] +// ---cut--- const request = await walletClient.prepareTransactionRequest({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', @@ -139,7 +142,9 @@ const request = await walletClient.prepareTransactionRequest({ The transaction recipient or contract address. -```ts +```ts twoslash +// [!include config.ts] +// ---cut--- const request = await walletClient.prepareTransactionRequest({ account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', // [!code focus] @@ -154,8 +159,10 @@ const request = await walletClient.prepareTransactionRequest({ The access list. -```ts -const request = await publicClient.prepareTransactionRequest({ +```ts twoslash +// [!include config.ts] +// ---cut--- +const request = await walletClient.prepareTransactionRequest({ accessList: [ // [!code focus:6] { address: '0x1', @@ -176,7 +183,9 @@ The target chain. If there is a mismatch between the wallet's current chain & th The chain is also used to infer its request type (e.g. the Celo chain has a `gatewayFee` that you can pass through to `prepareTransactionRequest`). -```ts +```ts twoslash +// [!include config.ts] +// ---cut--- import { optimism } from 'viem/chains' // [!code focus] const request = await walletClient.prepareTransactionRequest({ @@ -193,7 +202,9 @@ const request = await walletClient.prepareTransactionRequest({ A contract hashed method call with encoded args. -```ts +```ts twoslash +// [!include config.ts] +// ---cut--- const request = await walletClient.prepareTransactionRequest({ data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', // [!code focus] account, @@ -208,7 +219,11 @@ const request = await walletClient.prepareTransactionRequest({ The price (in wei) to pay per gas. Only applies to [Legacy Transactions](/docs/glossary/terms#legacy-transaction). -```ts +```ts twoslash +// [!include config.ts] +// ---cut--- +import { parseEther, parseGwei } from 'viem' + const request = await walletClient.prepareTransactionRequest({ account, gasPrice: parseGwei('20'), // [!code focus] @@ -223,7 +238,11 @@ const request = await walletClient.prepareTransactionRequest({ Total fee per gas (in wei), inclusive of `maxPriorityFeePerGas`. Only applies to [EIP-1559 Transactions](/docs/glossary/terms#eip-1559-transaction) -```ts +```ts twoslash +// [!include config.ts] +// ---cut--- +import { parseEther, parseGwei } from 'viem' + const request = await walletClient.prepareTransactionRequest({ account, maxFeePerGas: parseGwei('20'), // [!code focus] @@ -238,7 +257,11 @@ const request = await walletClient.prepareTransactionRequest({ Max priority fee per gas (in wei). Only applies to [EIP-1559 Transactions](/docs/glossary/terms#eip-1559-transaction) -```ts +```ts twoslash +// [!include config.ts] +// ---cut--- +import { parseEther, parseGwei } from 'viem' + const request = await walletClient.prepareTransactionRequest({ account, maxFeePerGas: parseGwei('20'), @@ -254,7 +277,9 @@ const request = await walletClient.prepareTransactionRequest({ Unique number identifying this transaction. -```ts +```ts twoslash +// [!include config.ts] +// ---cut--- const request = await walletClient.prepareTransactionRequest({ account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', @@ -272,7 +297,9 @@ Parameters to prepare. For instance, if `["gas", "nonce"]` is provided, then only the `gas` and `nonce` parameters will be prepared. -```ts +```ts twoslash +// [!include config.ts] +// ---cut--- const request = await walletClient.prepareTransactionRequest({ account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', @@ -287,7 +314,11 @@ const request = await walletClient.prepareTransactionRequest({ Value in wei sent with this transaction. -```ts +```ts twoslash +// [!include config.ts] +// ---cut--- +import { parseEther } from 'viem' + const request = await walletClient.prepareTransactionRequest({ account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', diff --git a/site/pages/docs/actions/wallet/requestAddresses.md b/site/pages/docs/actions/wallet/requestAddresses.md index 77e0130f36..ee21dc1e4d 100644 --- a/site/pages/docs/actions/wallet/requestAddresses.md +++ b/site/pages/docs/actions/wallet/requestAddresses.md @@ -14,21 +14,15 @@ This API can be useful for dapps that need to access the user's accounts in orde :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { walletClient } from './client' const accounts = await walletClient.requestAddresses() // [!code focus:99] // ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'] ``` -```ts [client.ts] -import { createWalletClient, custom } from 'viem' -import { mainnet } from 'viem/chains' - -export const walletClient = createWalletClient({ - chain: mainnet, - transport: custom(window.ethereum) -}) +```ts twoslash [client.ts] filename="client.ts" +// [!include ~/snippets/walletClient.ts] ``` ::: diff --git a/site/pages/docs/actions/wallet/requestPermissions.md b/site/pages/docs/actions/wallet/requestPermissions.md index 44b6df37bb..e8826c519f 100644 --- a/site/pages/docs/actions/wallet/requestPermissions.md +++ b/site/pages/docs/actions/wallet/requestPermissions.md @@ -10,20 +10,14 @@ Requests permissions for a wallet. :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { walletClient } from './client' const permissions = await walletClient.requestPermissions({ eth_accounts: {} }) // [!code focus:99] ``` -```ts [client.ts] -import { createWalletClient, custom } from 'viem' -import { mainnet } from 'viem/chains' - -export const walletClient = createWalletClient({ - chain: mainnet, - transport: custom(window.ethereum) -}) +```ts twoslash [client.ts] filename="client.ts" +// [!include ~/snippets/walletClient.ts] ``` ::: diff --git a/site/pages/docs/actions/wallet/sendRawTransaction.md b/site/pages/docs/actions/wallet/sendRawTransaction.md index ee1091a44f..9d0a8d9591 100644 --- a/site/pages/docs/actions/wallet/sendRawTransaction.md +++ b/site/pages/docs/actions/wallet/sendRawTransaction.md @@ -10,7 +10,7 @@ Sends a **signed** transaction to the network. Can be used with both [Public Cli :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { account, walletClient } from './config' const request = await walletClient.prepareTransactionRequest({ @@ -24,22 +24,18 @@ const signature = await walletClient.signTransaction(request) const hash = await walletClient.sendRawTransaction({ serializedTransaction: signature }) // [!code focus] ``` -```ts [config.ts] -import { createWalletClient, custom } from 'viem' -import { privateKeyToAccount } from 'viem/accounts' -import { mainnet } from 'viem/chains' +```ts twoslash [config.ts] filename="config.ts" +// [!include ~/snippets/walletClient.ts] -export const walletClient = createWalletClient({ - chain: mainnet, - transport: custom(window.ethereum) -}) - -// JSON-RPC Account export const [account] = await walletClient.getAddresses() -// Local Account -export const account = privateKeyToAccount(...) +// @log: ↑ JSON-RPC Account + +// export const account = privateKeyToAccount(...) +// @log: ↑ Local Account ``` +::: + ## Returns [`Hash`](/docs/glossary/types#hash) @@ -54,8 +50,10 @@ The [Transaction](/docs/glossary/terms#transaction) hash. The signed serialized transaction. -```ts -const signature = await walletClient.signTransaction({ +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- +const signature = await walletClient.sendRawTransaction({ serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33' // [!code focus] }) ``` diff --git a/site/pages/docs/actions/wallet/sendTransaction.md b/site/pages/docs/actions/wallet/sendTransaction.md index 0ebdf04786..e224709ced 100644 --- a/site/pages/docs/actions/wallet/sendTransaction.md +++ b/site/pages/docs/actions/wallet/sendTransaction.md @@ -10,7 +10,7 @@ Creates, signs, and sends a new transaction to the network. :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { account, walletClient } from './config' const hash = await walletClient.sendTransaction({ // [!code focus:99] @@ -21,20 +21,14 @@ const hash = await walletClient.sendTransaction({ // [!code focus:99] // '0x...' ``` -```ts [config.ts] -import { createWalletClient, custom } from 'viem' -import { privateKeyToAccount } from 'viem/accounts' -import { mainnet } from 'viem/chains' +```ts twoslash [config.ts] filename="config.ts" +// [!include ~/snippets/walletClient.ts] -export const walletClient = createWalletClient({ - chain: mainnet, - transport: custom(window.ethereum) -}) - -// JSON-RPC Account export const [account] = await walletClient.getAddresses() -// Local Account -export const account = privateKeyToAccount(...) +// @log: ↑ JSON-RPC Account + +// export const account = privateKeyToAccount(...) +// @log: ↑ Local Account ``` ::: @@ -47,7 +41,7 @@ If you do not wish to pass an `account` to every `sendTransaction`, you can also :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { walletClient } from './config' const hash = await walletClient.sendTransaction({ // [!code focus:99] @@ -57,7 +51,7 @@ const hash = await walletClient.sendTransaction({ // [!code focus:99] // '0x...' ``` -```ts [config.ts (JSON-RPC Account)] {4-6,9} +```ts [config.ts (JSON-RPC Account)] import { createWalletClient, custom } from 'viem' // Retrieve Account from an EIP-1193 Provider. @@ -67,17 +61,17 @@ const [account] = await window.ethereum.request({ export const walletClient = createWalletClient({ account, - transport: custom(window.ethereum) + transport: custom(window.ethereum!) }) ``` -```ts [config.ts (Local Account)] {5} -import { createWalletClient, custom } from 'viem' +```ts twoslash [config.ts (Local Account)] filename="config.ts" +import { createWalletClient, http } from 'viem' import { privateKeyToAccount } from 'viem/accounts' export const walletClient = createWalletClient({ account: privateKeyToAccount('0x...'), - transport: custom(window.ethereum) + transport: http() }) ``` @@ -99,7 +93,10 @@ The Account to send the transaction from. Accepts a [JSON-RPC Account](/docs/clients/wallet#json-rpc-accounts) or [Local Account (Private Key, etc)](/docs/clients/wallet#local-accounts-private-key-mnemonic-etc). -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- +// @noErrors const hash = await walletClient.sendTransaction({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', @@ -113,7 +110,10 @@ const hash = await walletClient.sendTransaction({ The transaction recipient or contract address. -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- +// @noErrors const hash = await walletClient.sendTransaction({ account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', // [!code focus] @@ -128,7 +128,10 @@ const hash = await walletClient.sendTransaction({ The access list. -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- +// @noErrors const hash = await publicClient.sendTransaction({ accessList: [ // [!code focus:6] { @@ -150,7 +153,10 @@ The target chain. If there is a mismatch between the wallet's current chain & th The chain is also used to infer its request type (e.g. the Celo chain has a `gatewayFee` that you can pass through to `sendTransaction`). -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- +// @noErrors import { optimism } from 'viem/chains' // [!code focus] const hash = await walletClient.sendTransaction({ @@ -167,7 +173,10 @@ const hash = await walletClient.sendTransaction({ A contract hashed method call with encoded args. -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- +// @noErrors const hash = await walletClient.sendTransaction({ data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', // [!code focus] account, @@ -182,7 +191,10 @@ const hash = await walletClient.sendTransaction({ The price (in wei) to pay per gas. Only applies to [Legacy Transactions](/docs/glossary/terms#legacy-transaction). -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- +// @noErrors const hash = await walletClient.sendTransaction({ account, gasPrice: parseGwei('20'), // [!code focus] @@ -197,7 +209,10 @@ const hash = await walletClient.sendTransaction({ Total fee per gas (in wei), inclusive of `maxPriorityFeePerGas`. Only applies to [EIP-1559 Transactions](/docs/glossary/terms#eip-1559-transaction) -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- +// @noErrors const hash = await walletClient.sendTransaction({ account, maxFeePerGas: parseGwei('20'), // [!code focus] @@ -212,7 +227,10 @@ const hash = await walletClient.sendTransaction({ Max priority fee per gas (in wei). Only applies to [EIP-1559 Transactions](/docs/glossary/terms#eip-1559-transaction) -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- +// @noErrors const hash = await walletClient.sendTransaction({ account, maxFeePerGas: parseGwei('20'), @@ -228,7 +246,10 @@ const hash = await walletClient.sendTransaction({ Unique number identifying this transaction. -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- +// @noErrors const hash = await walletClient.sendTransaction({ account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', @@ -243,7 +264,10 @@ const hash = await walletClient.sendTransaction({ Value in wei sent with this transaction. -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- +// @noErrors const hash = await walletClient.sendTransaction({ account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', diff --git a/site/pages/docs/actions/wallet/signMessage.md b/site/pages/docs/actions/wallet/signMessage.md index e2fa1bb933..4c92ae0e24 100644 --- a/site/pages/docs/actions/wallet/signMessage.md +++ b/site/pages/docs/actions/wallet/signMessage.md @@ -14,37 +14,31 @@ With the calculated signature, you can: :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { account, walletClient } from './config' -const signature = await walletClient.signMessage({ // [!code focus:99] +const signature_1 = await walletClient.signMessage({ // [!code focus:99] account, message: 'hello world', }) -// "0xa461f509887bd19e312c0c58467ce8ff8e300d3c1a90b608a760c5b80318eaf15fe57c96f9175d6cd4daad4663763baa7e78836e067d0163e9a2ccf2ff753f5b1b" +// @log: Output: "0xa461f509887bd19e312c0c58467ce8ff8e300d3c1a90b608a760c5b80318eaf15fe57c96f9175d6cd4daad4663763baa7e78836e067d0163e9a2ccf2ff753f5b1b" -const signature = await walletClient.signMessage({ +const signature_2 = await walletClient.signMessage({ account, // Hex data representation of message. message: { raw: '0x68656c6c6f20776f726c64' }, }) -// "0xa461f509887bd19e312c0c58467ce8ff8e300d3c1a90b608a760c5b80318eaf15fe57c96f9175d6cd4daad4663763baa7e78836e067d0163e9a2ccf2ff753f5b1b" +// @log: Output: "0xa461f509887bd19e312c0c58467ce8ff8e300d3c1a90b608a760c5b80318eaf15fe57c96f9175d6cd4daad4663763baa7e78836e067d0163e9a2ccf2ff753f5b1b" ``` -```ts [config.ts] -import { createWalletClient, custom } from 'viem' -import { privateKeyToAccount } from 'viem/accounts' -import { mainnet } from 'viem/chains' +```ts twoslash [config.ts] filename="client.ts" +// [!include ~/snippets/walletClient.ts] -export const walletClient = createWalletClient({ - chain: mainnet, - transport: custom(window.ethereum) -}) - -// JSON-RPC Account export const [account] = await walletClient.getAddresses() -// Local Account -export const account = privateKeyToAccount(...) +// @log: ↑ JSON-RPC Account + +// export const account = privateKeyToAccount(...) +// @log: ↑ Local Account ``` ::: @@ -57,16 +51,16 @@ If you do not wish to pass an `account` to every `signMessage`, you can also hoi :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { walletClient } from './config' const signature = await walletClient.signMessage({ // [!code focus:99] message: 'hello world', }) -// "0xa461f509887bd19e312c0c58467ce8ff8e300d3c1a90b608a760c5b80318eaf15fe57c96f9175d6cd4daad4663763baa7e78836e067d0163e9a2ccf2ff753f5b1b" +// @log: "0xa461f509887bd19e312c0c58467ce8ff8e300d3c1a90b608a760c5b80318eaf15fe57c96f9175d6cd4daad4663763baa7e78836e067d0163e9a2ccf2ff753f5b1b" ``` -```ts [config.ts (JSON-RPC Account)] {4-6,9} +```ts [config.ts (JSON-RPC Account)] import { createWalletClient, custom } from 'viem' // Retrieve Account from an EIP-1193 Provider. @@ -76,17 +70,17 @@ const [account] = await window.ethereum.request({ export const walletClient = createWalletClient({ account, - transport: custom(window.ethereum) + transport: custom(window.ethereum!) }) ``` -```ts [config.ts (Local Account)] {5} -import { createWalletClient, custom } from 'viem' +```ts twoslash [config.ts (Local Account)] filename="config.ts" +import { createWalletClient, http } from 'viem' import { privateKeyToAccount } from 'viem/accounts' export const walletClient = createWalletClient({ account: privateKeyToAccount('0x...'), - transport: custom(window.ethereum) + transport: http() }) ``` @@ -108,7 +102,9 @@ Account to use for signing. Accepts a [JSON-RPC Account](/docs/clients/wallet#json-rpc-accounts) or [Local Account (Private Key, etc)](/docs/clients/wallet#local-accounts-private-key-mnemonic-etc). -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- const signature = await walletClient.signMessage({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', // [!code focus:1] message: 'hello world', @@ -123,7 +119,9 @@ Message to sign. By default, viem signs the UTF-8 representation of the message. -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- const signature = await walletClient.signMessage({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message: 'hello world', // [!code focus:1] @@ -132,7 +130,9 @@ const signature = await walletClient.signMessage({ To sign the data representation of the message, you can use the `raw` attribute. -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- const signature = await walletClient.signMessage({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message: { raw: '0x68656c6c6f20776f726c64' }, // [!code focus:1] diff --git a/site/pages/docs/actions/wallet/signTransaction.md b/site/pages/docs/actions/wallet/signTransaction.md index b6590e400c..e72959dc3f 100644 --- a/site/pages/docs/actions/wallet/signTransaction.md +++ b/site/pages/docs/actions/wallet/signTransaction.md @@ -10,7 +10,7 @@ Signs a transaction. :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { account, walletClient } from './config' const request = await walletClient.prepareTransactionRequest({ @@ -25,20 +25,14 @@ const signature = await walletClient.signTransaction(request) // [!code focus:2] const hash = await walletClient.sendRawTransaction(signature) ``` -```ts [config.ts] -import { createWalletClient, custom } from 'viem' -import { privateKeyToAccount } from 'viem/accounts' -import { mainnet } from 'viem/chains' +```ts twoslash [config.ts] filename="config.ts" +// [!include ~/snippets/walletClient.ts] -export const walletClient = createWalletClient({ - chain: mainnet, - transport: custom(window.ethereum) -}) - -// JSON-RPC Account export const [account] = await walletClient.getAddresses() -// Local Account -export const account = privateKeyToAccount(...) +// @log: ↑ JSON-RPC Account + +// export const account = privateKeyToAccount(...) +// @log: ↑ Local Account ``` ::: @@ -51,7 +45,7 @@ If you do not wish to pass an `account` to every `prepareTransactionRequest`, yo :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { walletClient } from './config' const request = await walletClient.prepareTransactionRequest({ @@ -65,7 +59,7 @@ const signature = await walletClient.signTransaction(request) // [!code focus:2] const hash = await walletClient.sendRawTransaction(signature) ``` -```ts [config.ts (JSON-RPC Account)] {4-6,9} +```ts [config.ts (JSON-RPC Account)] import { createWalletClient, custom } from 'viem' // Retrieve Account from an EIP-1193 Provider. @@ -75,17 +69,17 @@ const [account] = await window.ethereum.request({ export const walletClient = createWalletClient({ account, - transport: custom(window.ethereum) + transport: custom(window.ethereum!) }) ``` -```ts [config.ts (Local Account)] {5} -import { createWalletClient, custom } from 'viem' +```ts twoslash [config.ts (Local Account)] filename="config.ts" +import { createWalletClient, http } from 'viem' import { privateKeyToAccount } from 'viem/accounts' export const walletClient = createWalletClient({ account: privateKeyToAccount('0x...'), - transport: custom(window.ethereum) + transport: http() }) ``` @@ -107,7 +101,10 @@ The Account to send the transaction from. Accepts a [JSON-RPC Account](/docs/clients/wallet#json-rpc-accounts) or [Local Account (Private Key, etc)](/docs/clients/wallet#local-accounts-private-key-mnemonic-etc). -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- +// @noErrors const signature = await walletClient.signTransaction({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', @@ -121,7 +118,10 @@ const signature = await walletClient.signTransaction({ The transaction recipient or contract address. -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- +// @noErrors const signature = await walletClient.signTransaction({ account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', // [!code focus] @@ -136,7 +136,9 @@ const signature = await walletClient.signTransaction({ The access list. -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- const signature = await publicClient.signTransaction({ accessList: [ // [!code focus:6] { @@ -158,7 +160,10 @@ The target chain. If there is a mismatch between the wallet's current chain & th The chain is also used to infer its request type (e.g. the Celo chain has a `gatewayFee` that you can pass through to `signTransaction`). -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- +// @noErrors import { optimism } from 'viem/chains' // [!code focus] const signature = await walletClient.signTransaction({ @@ -175,7 +180,10 @@ const signature = await walletClient.signTransaction({ A contract hashed method call with encoded args. -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- +// @noErrors const signature = await walletClient.signTransaction({ data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', // [!code focus] account, @@ -190,7 +198,10 @@ const signature = await walletClient.signTransaction({ The price (in wei) to pay per gas. Only applies to [Legacy Transactions](/docs/glossary/terms#legacy-transaction). -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- +// @noErrors const signature = await walletClient.signTransaction({ account, gasPrice: parseGwei('20'), // [!code focus] @@ -205,7 +216,10 @@ const signature = await walletClient.signTransaction({ Total fee per gas (in wei), inclusive of `maxPriorityFeePerGas`. Only applies to [EIP-1559 Transactions](/docs/glossary/terms#eip-1559-transaction) -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- +// @noErrors const signature = await walletClient.signTransaction({ account, maxFeePerGas: parseGwei('20'), // [!code focus] @@ -220,7 +234,10 @@ const signature = await walletClient.signTransaction({ Max priority fee per gas (in wei). Only applies to [EIP-1559 Transactions](/docs/glossary/terms#eip-1559-transaction) -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- +// @noErrors const signature = await walletClient.signTransaction({ account, maxFeePerGas: parseGwei('20'), @@ -236,7 +253,10 @@ const signature = await walletClient.signTransaction({ Unique number identifying this transaction. -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- +// @noErrors const signature = await walletClient.signTransaction({ account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', @@ -251,7 +271,10 @@ const signature = await walletClient.signTransaction({ Value in wei sent with this transaction. -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- +// @noErrors const signature = await walletClient.signTransaction({ account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', diff --git a/site/pages/docs/actions/wallet/signTypedData.md b/site/pages/docs/actions/wallet/signTypedData.md index c468975ffd..1d58464a12 100644 --- a/site/pages/docs/actions/wallet/signTypedData.md +++ b/site/pages/docs/actions/wallet/signTypedData.md @@ -10,7 +10,7 @@ Signs typed data and calculates an Ethereum-specific signature in [https://eips. :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { account, walletClient } from './config' import { domain, types } from './data' @@ -33,7 +33,7 @@ const signature = await walletClient.signTypedData({ }) ``` -```ts [data.ts] +```ts twoslash [data.ts] // All properties on a domain are optional export const domain = { name: 'Ether Mail', @@ -56,20 +56,14 @@ export const types = { } as const ``` -```ts [config.ts] -import { createWalletClient, custom } from 'viem' -import { privateKeyToAccount } from 'viem/accounts' -import { mainnet } from 'viem/chains' +```ts twoslash [config.ts] filename="config.ts" +// [!include ~/snippets/walletClient.ts] -export const walletClient = createWalletClient({ - chain: mainnet, - transport: custom(window.ethereum) -}) - -// JSON-RPC Account export const [account] = await walletClient.getAddresses() -// Local Account -export const account = privateKeyToAccount('0x...') +// @log: ↑ JSON-RPC Account + +// export const account = privateKeyToAccount(...) +// @log: ↑ Local Account ``` ::: @@ -82,7 +76,7 @@ If you do not wish to pass an `account` to every `signTypedData`, you can also h :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { walletClient } from './config' import { domain, types } from './data' @@ -104,7 +98,7 @@ const signature = await walletClient.signTypedData({ }) ``` -```ts [data.ts] +```ts twoslash [data.ts] // All properties on a domain are optional export const domain = { name: 'Ether Mail', @@ -127,7 +121,7 @@ export const types = { } as const ``` -```ts [config.ts (JSON-RPC Account)] {4-6,9} +```ts [config.ts (JSON-RPC Account)] import { createWalletClient, custom } from 'viem' // Retrieve Account from an EIP-1193 Provider. @@ -137,17 +131,17 @@ const [account] = await window.ethereum.request({ export const walletClient = createWalletClient({ account, - transport: custom(window.ethereum) + transport: custom(window.ethereum!) }) ``` -```ts [config.ts (Local Account)] {5} -import { createWalletClient, custom } from 'viem' +```ts twoslash [config.ts (Local Account)] filename="config.ts" +import { createWalletClient, http } from 'viem' import { privateKeyToAccount } from 'viem/accounts' export const walletClient = createWalletClient({ account: privateKeyToAccount('0x...'), - transport: custom(window.ethereum) + transport: http() }) ``` @@ -169,7 +163,9 @@ The Account to use for signing. Accepts a [JSON-RPC Account](/docs/clients/wallet#json-rpc-accounts) or [Local Account (Private Key, etc)](/docs/clients/wallet#local-accounts-private-key-mnemonic-etc). -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- const signature = await walletClient.signTypedData({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', // [!code focus] domain: { @@ -178,7 +174,17 @@ const signature = await walletClient.signTypedData({ chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', }, - types, + 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: { @@ -200,7 +206,9 @@ const signature = await walletClient.signTypedData({ The typed data domain. -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- const signature = await walletClient.signTypedData({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', domain: { // [!code focus:6] @@ -209,7 +217,17 @@ const signature = await walletClient.signTypedData({ chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', }, - types, + 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: { @@ -229,10 +247,17 @@ const signature = await walletClient.signTypedData({ The type definitions for the typed data. -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- const signature = await walletClient.signTypedData({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', - domain, + domain: { + name: 'Ether Mail', + version: '1', + chainId: 1, + verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', + }, types: { // [!code focus:11] Person: [ { name: 'name', type: 'string' }, @@ -265,10 +290,17 @@ const signature = await walletClient.signTypedData({ The primary type to extract from `types` and use in `value`. -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- const signature = await walletClient.signTypedData({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', - domain, + domain: { + name: 'Ether Mail', + version: '1', + chainId: 1, + verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', + }, types: { Person: [ { name: 'name', type: 'string' }, @@ -299,10 +331,17 @@ const signature = await walletClient.signTypedData({ **Type:** Inferred from `types` & `primaryType`. -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- const signature = await walletClient.signTypedData({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', - domain, + domain: { + name: 'Ether Mail', + version: '1', + chainId: 1, + verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', + }, types: { Person: [ { name: 'name', type: 'string' }, diff --git a/site/pages/docs/actions/wallet/switchChain.md b/site/pages/docs/actions/wallet/switchChain.md index c8dbe206cf..4009e16506 100644 --- a/site/pages/docs/actions/wallet/switchChain.md +++ b/site/pages/docs/actions/wallet/switchChain.md @@ -10,19 +10,15 @@ Switch the target chain in a wallet. :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { avalanche } from 'viem/chains' import { walletClient } from './client' await walletClient.switchChain({ id: avalanche.id }) // [!code focus] ``` -```ts [client.ts] -import { createWalletClient, custom } from 'viem' - -export const walletClient = createWalletClient({ - transport: custom(window.ethereum) -}) +```ts twoslash [client.ts] filename="client.ts" +// [!include ~/snippets/walletClient.ts] ``` ::: diff --git a/site/pages/docs/actions/wallet/watchAsset.md b/site/pages/docs/actions/wallet/watchAsset.md index fc9178aa9b..c80a32698d 100644 --- a/site/pages/docs/actions/wallet/watchAsset.md +++ b/site/pages/docs/actions/wallet/watchAsset.md @@ -10,7 +10,7 @@ Requests that the user tracks the token in their wallet. Returns a boolean indic :::code-group -```ts [example.ts] +```ts twoslash [example.ts] import { walletClient } from './client' const success = await walletClient.watchAsset({ // [!code focus:99] @@ -23,14 +23,8 @@ const success = await walletClient.watchAsset({ // [!code focus:99] }) ``` -```ts [client.ts] -import { createWalletClient, custom } from 'viem' -import { mainnet } from 'viem/chains' - -export const walletClient = createWalletClient({ - chain: mainnet, - transport: custom(window.ethereum) -}) +```ts twoslash [client.ts] filename="client.ts" +// [!include ~/snippets/walletClient.ts] ``` ::: @@ -49,7 +43,9 @@ Boolean indicating if the token was successfully added. Token type. -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut-- const success = await walletClient.watchAsset({ type: 'ERC20', // [!code focus] options: { @@ -66,7 +62,9 @@ const success = await walletClient.watchAsset({ The address of the token contract. -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- const success = await walletClient.watchAsset({ type: 'ERC20', options: { @@ -83,7 +81,9 @@ const success = await walletClient.watchAsset({ The number of token decimals. -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- const success = await walletClient.watchAsset({ type: 'ERC20', options: { @@ -100,12 +100,14 @@ const success = await walletClient.watchAsset({ A ticker symbol or shorthand, up to 11 characters. -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- const success = await walletClient.watchAsset({ type: 'ERC20', options: { address: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', - decimals: 18 + decimals: 18, symbol: 'WETH', // [!code focus] } }) @@ -117,12 +119,14 @@ const success = await walletClient.watchAsset({ A string url of the token logo. -```ts +```ts twoslash +// [!include ~/snippets/walletClient.ts] +// ---cut--- const success = await walletClient.watchAsset({ type: 'ERC20', options: { address: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', - decimals: 18 + decimals: 18, symbol: 'WETH', image: 'https://weth.com/icon.png', // [!code focus] } diff --git a/site/pages/docs/chains/introduction.md b/site/pages/docs/chains/introduction.md index ff61e3153b..4bf1379cb2 100644 --- a/site/pages/docs/chains/introduction.md +++ b/site/pages/docs/chains/introduction.md @@ -6,12 +6,12 @@ The `viem/chains` entrypoint contains references to popular EVM-compatible chain Import your chain from the entrypoint and use them in the consuming viem code: -```tsx {2,5} +```tsx import { createPublicClient, http } from 'viem' -import { zora } from 'viem/chains' +import { zora } from 'viem/chains' // [!code focus] const client = createPublicClient({ - chain: zora, + chain: zora, // [!code focus] transport: http() }) ``` diff --git a/site/pages/docs/clients/public.md b/site/pages/docs/clients/public.md index 7bbd0d55a3..e2f54b1418 100644 --- a/site/pages/docs/clients/public.md +++ b/site/pages/docs/clients/public.md @@ -18,7 +18,7 @@ Initialize a Client with your desired [Chain](/docs/chains/introduction) (e.g. ` import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' -const client = createPublicClient({ +const publicClient = createPublicClient({ chain: mainnet, transport: http() }) @@ -29,7 +29,7 @@ Then you can consume [Public Actions](/docs/actions/public/introduction): ```ts twoslash // [!include ~/snippets/publicClient.ts] // ---cut--- -const blockNumber = await client.getBlockNumber() // [!code focus:10] +const blockNumber = await publicClient.getBlockNumber() // [!code focus:10] ``` ## Optimization @@ -50,7 +50,7 @@ You can enable `eth_call` aggregation by setting the `batch.multicall` flag to ` import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' // ---cut--- -const client = createPublicClient({ +const publicClient = createPublicClient({ batch: { multicall: true, // [!code focus] }, @@ -77,9 +77,9 @@ const address = '0x' // ---cut--- import { getContract } from 'viem' import { abi } from './abi' -import { client } from './client' +import { publicClient } from './client' -const contract = getContract({ address, abi, client }) +const contract = getContract({ address, abi, client: publicClient }) // The below will send a single request to the RPC Provider. const [name, totalSupply, symbol, balance] = await Promise.all([ @@ -113,7 +113,7 @@ The [Transport](/docs/clients/intro) of the Public Client. ```ts twoslash // [!include ~/snippets/publicClient.ts:imports] // ---cut--- -const client = createPublicClient({ +const publicClient = createPublicClient({ chain: mainnet, transport: http(), // [!code focus] }) @@ -128,7 +128,7 @@ The [Chain](/docs/chains/introduction) of the Public Client. ```ts twoslash // [!include ~/snippets/publicClient.ts:imports] // ---cut--- -const client = createPublicClient({ +const publicClient = createPublicClient({ chain: mainnet, // [!code focus] transport: http(), }) @@ -148,7 +148,7 @@ Toggle to enable `eth_call` multicall aggregation. ```ts twoslash // [!include ~/snippets/publicClient.ts:imports] // ---cut--- -const client = createPublicClient({ +const publicClient = createPublicClient({ batch: { multicall: true, // [!code focus] }, @@ -169,7 +169,7 @@ The maximum size (in bytes) for each multicall (`aggregate3`) calldata chunk. ```ts twoslash // [!include ~/snippets/publicClient.ts:imports] // ---cut--- -const client = createPublicClient({ +const publicClient = createPublicClient({ batch: { multicall: { batchSize: 512, // [!code focus] @@ -190,7 +190,7 @@ The maximum number of milliseconds to wait before sending a batch. ```ts twoslash // [!include ~/snippets/publicClient.ts:imports] // ---cut--- -const client = createPublicClient({ +const publicClient = createPublicClient({ batch: { multicall: { wait: 16, // [!code focus] @@ -211,7 +211,7 @@ Time (in ms) that cached data will remain in memory. ```ts twoslash // [!include ~/snippets/publicClient.ts:imports] // ---cut--- -const client = createPublicClient({ +const publicClient = createPublicClient({ cacheTime: 10_000, // [!code focus] chain: mainnet, transport: http(), @@ -228,7 +228,7 @@ A key for the Client. ```ts twoslash // [!include ~/snippets/publicClient.ts:imports] // ---cut--- -const client = createPublicClient({ +const publicClient = createPublicClient({ chain: mainnet, key: 'public', // [!code focus] transport: http(), @@ -245,7 +245,7 @@ A name for the Client. ```ts twoslash // [!include ~/snippets/publicClient.ts:imports] // ---cut--- -const client = createPublicClient({ +const publicClient = createPublicClient({ chain: mainnet, name: 'Public Client', // [!code focus] transport: http(), @@ -262,7 +262,7 @@ Frequency (in ms) for polling enabled Actions. ```ts twoslash // [!include ~/snippets/publicClient.ts:imports] // ---cut--- -const client = createPublicClient({ +const publicClient = createPublicClient({ chain: mainnet, pollingInterval: 10_000, // [!code focus] transport: http(), diff --git a/site/pages/docs/contract/createContractEventFilter.md b/site/pages/docs/contract/createContractEventFilter.md index b0f5132542..ba26f1199f 100644 --- a/site/pages/docs/contract/createContractEventFilter.md +++ b/site/pages/docs/contract/createContractEventFilter.md @@ -142,27 +142,27 @@ const filter = await publicClient.createContractEventFilter({ By default, `createContractEventFilter` will include logs that [do not conform](/docs/glossary/terms#non-conforming-log) to the indexed & non-indexed arguments on the `event`. viem will not return a value for arguments that do not conform to the ABI, thus, some arguments on `args` may be undefined. -```ts {7} +```ts const filter = await publicClient.createContractEventFilter({ eventName: 'Transfer', }) const logs = await publicClient.getFilterLogs({ filter }) -logs[0].args -// ^? { address?: Address, to?: Address, value?: bigint } +logs[0].args // [!code focus] +// ^? { address?: Address, to?: Address, value?: bigint } // [!code focus] ``` You can turn on `strict` mode to only return logs that conform to the indexed & non-indexed arguments on the `event`, meaning that `args` will always be defined. The trade-off is that non-conforming logs will be filtered out. -```ts {7} +```ts const filter = await publicClient.createContractEventFilter({ eventName: 'Transfer', strict: true }) const logs = await publicClient.getFilterLogs({ filter }) -logs[0].args -// ^? { address: Address, to: Address, value: bigint } +logs[0].args // [!code focus] +// ^? { address: Address, to: Address, value: bigint } // [!code focus] ``` ## Returns diff --git a/site/pages/docs/contract/decodeEventLog.md b/site/pages/docs/contract/decodeEventLog.md index 6a9226b4d4..99888c22b0 100644 --- a/site/pages/docs/contract/decodeEventLog.md +++ b/site/pages/docs/contract/decodeEventLog.md @@ -82,11 +82,11 @@ By default, if the `topics` and `data` does not conform to the ABI (a mismatch b For example, the following will throw an error as there is a mismatch in non-`indexed` arguments & `data` length. -```ts {2-4} +```ts decodeEventLog({ - abi: parseAbi(['event Transfer(address indexed, address, uint256)']), - // `data` should be 64 bytes, but is only 32 bytes. - data: '0x0000000000000000000000000000000000000000000000000000000000000001', + abi: parseAbi(['event Transfer(address indexed, address, uint256)']), // [!code focus] + // `data` should be 64 bytes, but is only 32 bytes. // [!code focus] + data: '0x0000000000000000000000000000000000000000000000000000000000000001', // [!code focus] topics: [ '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', '0x000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266', @@ -97,10 +97,10 @@ decodeEventLog({ It is possible for `decodeEventLog` to try and partially decode the Log, this can be done by setting the `strict` argument to `false`: -```ts {2-4} -decodeEventLog({ - abi: parseAbi(['event Transfer(address indexed, address, uint256)']), - data: '0x0000000000000000000000000000000000000000000000000000000000000001', +```ts +decodeEventLog({ // [!code focus] + abi: parseAbi(['event Transfer(address indexed, address, uint256)']), // [!code focus] + data: '0x0000000000000000000000000000000000000000000000000000000000000001', // [!code focus] topics: [ '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', '0x000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266', diff --git a/site/pages/docs/contract/decodeFunctionData.md b/site/pages/docs/contract/decodeFunctionData.md index 4833c4da7f..49a14598b9 100644 --- a/site/pages/docs/contract/decodeFunctionData.md +++ b/site/pages/docs/contract/decodeFunctionData.md @@ -62,11 +62,12 @@ If your calldata includes argument(s) after the 4byte function signature, you ca :::code-group -```ts {7} [example.ts] +```ts [example.ts] import { decodeFunctionData } from 'viem' import { publicClient } from './client' import { wagmiAbi } from './abi' +// [!code word:args:1] const { functionName, args } = decodeFunctionData({ abi: wagmiAbi, data: '0x0423a1320000000000000000000000000000000000000000000000000000000000000001' diff --git a/site/pages/docs/contract/getContractEvents.md b/site/pages/docs/contract/getContractEvents.md index 758e719da6..24a0a81dda 100644 --- a/site/pages/docs/contract/getContractEvents.md +++ b/site/pages/docs/contract/getContractEvents.md @@ -298,27 +298,27 @@ const logs = await publicClient.getContractEvents({ By default, `getContractEvents` will include logs that [do not conform](/docs/glossary/terms#non-conforming-log) to the indexed & non-indexed arguments on the `event`. viem will not return a value for arguments that do not conform to the ABI, thus, some arguments on `args` may be undefined. -```ts {7} +```ts const logs = await publicClient.getContractEvents({ abi: erc20Abi, eventName: 'Transfer', }) -logs[0].args -// ^? { address?: Address, to?: Address, value?: bigint } +logs[0].args // [!code focus] +// ^? { address?: Address, to?: Address, value?: bigint } // [!code focus] ``` You can turn on `strict` mode to only return logs that conform to the indexed & non-indexed arguments on the `event`, meaning that `args` will always be defined. The trade-off is that non-conforming logs will be filtered out. -```ts {7} +```ts const logs = await publicClient.getContractEvents({ abi: erc20Abi, eventName: 'Transfer', strict: true }) -logs[0].args -// ^? { address: Address, to: Address, value: bigint } +logs[0].args // [!code focus] +// ^? { address: Address, to: Address, value: bigint } // [!code focus] ``` ## Returns diff --git a/site/pages/docs/ethers-migration.mdx b/site/pages/docs/ethers-migration.mdx index 4884242ba1..8ed29966d0 100644 --- a/site/pages/docs/ethers-migration.mdx +++ b/site/pages/docs/ethers-migration.mdx @@ -10,22 +10,22 @@ You may notice some of the APIs in viem are a little more verbose than Ethers. W #### Ethers -```ts {3} +```ts import { getDefaultProvider } from 'ethers' -const provider = getDefaultProvider() +const provider = getDefaultProvider() // [!code hl] ``` #### viem -```ts {4-7} +```ts import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' -const client = createPublicClient({ - chain: mainnet, - transport: http() -}) +const client = createPublicClient({ // [!code hl] + chain: mainnet, // [!code hl] + transport: http() // [!code hl] +}) // [!code hl] ``` > We are more verbose here – we want to be explicit and clear what chain you are connecting to & what transport you are using to avoid any confusion. :) @@ -36,46 +36,46 @@ const client = createPublicClient({ This is also interchangeable with `StaticJsonRpcProvider`. -```ts {3} +```ts import { providers } from 'ethers' -const provider = new providers.JsonRpcProvider('https://cloudflare-eth.com') +const provider = new providers.JsonRpcProvider('https://cloudflare-eth.com') // [!code hl] ``` Custom Chain: -```ts {3-6} +```ts import { providers } from 'ethers' -const provider = new providers.JsonRpcProvider('https://rpc.ankr.com/fantom/​', { - name: 'Fantom', - id: 250 -}) +const provider = new providers.JsonRpcProvider('https://rpc.ankr.com/fantom/​', { // [!code hl] + name: 'Fantom', // [!code hl] + id: 250 // [!code hl] +}) // [!code hl] ``` #### viem -```ts {4-7} +```ts import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' -const client = createPublicClient({ - chain: mainnet, - transport: http('https://cloudflare-eth.com') -}) +const client = createPublicClient({ // [!code hl] + chain: mainnet, // [!code hl] + transport: http('https://cloudflare-eth.com') // [!code hl] +}) // [!code hl] ``` Custom Chain: -```ts {4-7} +```ts import { createPublicClient, http } from 'viem' import { fantom } from 'viem/chains' -const client = createPublicClient({ - chain: fantom, - transport: http('https://rpc.ankr.com/fantom/​') -}) +const client = createPublicClient({ // [!code hl] + chain: fantom, // [!code hl] + transport: http('https://rpc.ankr.com/fantom/​') // [!code hl] +}) // [!code hl] ``` > viem exports custom EVM chains in the `viem/chains` entrypoint. @@ -84,22 +84,22 @@ const client = createPublicClient({ #### Ethers -```ts {3} +```ts import { providers } from 'ethers' -const provider = new providers.InfuraProvider('homestead', '') +const provider = new providers.InfuraProvider('homestead', '') // [!code hl] ``` #### viem -```ts {4-7} +```ts import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' -const client = createPublicClient({ - chain: mainnet, - transport: http('https://mainnet.infura.io/v3/') -}) +const client = createPublicClient({ // [!code hl] + chain: mainnet, // [!code hl] + transport: http('https://mainnet.infura.io/v3/') // [!code hl] +}) // [!code hl] ``` > viem does not have custom API Provider clients – you can just pass in their RPC URL. @@ -108,22 +108,22 @@ const client = createPublicClient({ #### Ethers -```ts {3} +```ts import { providers } from 'ethers' -const provider = new providers.AlchemyProvider('homestead', '') +const provider = new providers.AlchemyProvider('homestead', '') // [!code hl] ``` #### viem -```ts {4-7} +```ts import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' -const client = createPublicClient({ - chain: mainnet, - transport: http('https://eth-mainnet.g.alchemy.com/v2/') -}) +const client = createPublicClient({ // [!code hl] + chain: mainnet, // [!code hl] + transport: http('https://eth-mainnet.g.alchemy.com/v2/') // [!code hl] +}) // [!code hl] ``` > viem does not have custom API Provider clients – you can just pass in their RPC URL. @@ -132,22 +132,22 @@ const client = createPublicClient({ #### Ethers -```ts {3} +```ts import { providers } from 'ethers' -const provider = new providers.CloudflareProvider() +const provider = new providers.CloudflareProvider() // [!code hl] ``` #### viem -```ts {4-7} +```ts import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' -const client = createPublicClient({ - chain: mainnet, - transport: http('https://cloudflare-eth.com/') -}) +const client = createPublicClient({ // [!code hl] + chain: mainnet, // [!code hl] + transport: http('https://cloudflare-eth.com/') // [!code hl] +}) // [!code hl] ``` > viem does not have custom API Provider clients – you can just pass in their RPC URL. @@ -156,22 +156,22 @@ const client = createPublicClient({ #### Ethers -```ts {3} +```ts import { providers } from 'ethers' -const provider = new providers.PocketProvider('homestead', '') +const provider = new providers.PocketProvider('homestead', '') // [!code hl] ``` #### viem -```ts {4-7} +```ts import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' -const client = createPublicClient({ - chain: mainnet, - transport: http('https://eth-mainnet.gateway.pokt.network/v1/lb/') -}) +const client = createPublicClient({ // [!code hl] + chain: mainnet, // [!code hl] + transport: http('https://eth-mainnet.gateway.pokt.network/v1/lb/') // [!code hl] +}) // [!code hl] ``` > viem does not have custom API Provider clients – you can just pass in their RPC URL. @@ -180,22 +180,22 @@ const client = createPublicClient({ #### Ethers -```ts {3} +```ts import { providers } from 'ethers' -const provider = new providers.AnkrProvider('homestead', '') +const provider = new providers.AnkrProvider('homestead', '') // [!code hl] ``` #### viem -```ts {4-7} +```ts import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' -const client = createPublicClient({ - chain: mainnet, - transport: http('https://rpc.ankr.com/eth/') -}) +const client = createPublicClient({ // [!code hl] + chain: mainnet, // [!code hl] + transport: http('https://rpc.ankr.com/eth/') // [!code hl] +}) // [!code hl] ``` > viem does not have custom API Provider clients – you can just pass in their RPC URL. @@ -204,26 +204,26 @@ const client = createPublicClient({ #### Ethers -```ts {3-5} +```ts import { providers } from 'ethers' -const alchemy = new providers.AlchemyProvider('homestead', '') -const infura = new providers.InfuraProvider('homestead', '') -const provider = new providers.FallbackProvider([alchemy, infura]) +const alchemy = new providers.AlchemyProvider('homestead', '') // [!code hl] +const infura = new providers.InfuraProvider('homestead', '') // [!code hl] +const provider = new providers.FallbackProvider([alchemy, infura]) // [!code hl] ``` #### viem -```ts {4-5,9} +```ts import { createPublicClient, http, fallback } from 'viem' import { mainnet } from 'viem/chains' -const alchemy = http('https://eth-mainnet.g.alchemy.com/v2/') -const infura = http('https://mainnet.infura.io/v3/') +const alchemy = http('https://eth-mainnet.g.alchemy.com/v2/') // [!code hl] +const infura = http('https://mainnet.infura.io/v3/') // [!code hl] const client = createPublicClient({ chain: mainnet, - transport: fallback([alchemy, infura]) + transport: fallback([alchemy, infura]) // [!code hl] }) ``` @@ -239,44 +239,44 @@ Coming soon. #### Ethers -```ts {3} +```ts import { providers } from 'ethers' -const provider = new providers.Web3Provider(window.ethereum) +const provider = new providers.Web3Provider(window.ethereum) // [!code hl] ``` #### viem -```ts {4-7} +```ts import { createWalletClient, custom } from 'viem' import { mainnet } from 'viem/chains' -const client = createWalletClient({ - chain: mainnet, - transport: custom(window.ethereum) -}) +const client = createWalletClient({ // [!code hl] + chain: mainnet, // [!code hl] + transport: custom(window.ethereum) // [!code hl] +}) // [!code hl] ``` ### WebSocketProvider #### Ethers -```ts {3} +```ts import { providers } from 'ethers' -const provider = new providers.WebSocketProvider('wss://eth-mainnet.g.alchemy.com/v2/') +const provider = new providers.WebSocketProvider('wss://eth-mainnet.g.alchemy.com/v2/') // [!code hl] ``` #### viem -```ts {4-7} +```ts import { createPublicClient, webSocket } from 'viem' import { mainnet } from 'viem/chains' -const client = createPublicClient({ - chain: mainnet, - transport: webSocket('wss://eth-mainnet.g.alchemy.com/v2/') -}) +const client = createPublicClient({ // [!code hl] + chain: mainnet, // [!code hl] + transport: webSocket('wss://eth-mainnet.g.alchemy.com/v2/') // [!code hl] +}) // [!code hl] ``` ## Signers → Accounts @@ -285,27 +285,27 @@ const client = createPublicClient({ #### Ethers -```ts {5-6} +```ts import { providers } from 'ethers' const provider = new providers.Web3Provider(window.ethereum) -const [address] = await provider.listAccounts() -const signer = provider.getSigner(address) +const [address] = await provider.listAccounts() // [!code hl] +const signer = provider.getSigner(address) // [!code hl] signer.sendTransaction({ ... }) ``` #### viem -```ts {4,7} +```ts import { createWalletClient, custom } from 'viem' import { mainnet } from 'viem/chains' -const [account] = await window.ethereum.request({ method: 'eth_requestAccounts' }) +const [account] = await window.ethereum.request({ method: 'eth_requestAccounts' }) // [!code hl] const client = createWalletClient({ - account, + account, // [!code hl] chain: mainnet, transport: custom(window.ethereum) }) @@ -319,27 +319,27 @@ client.sendTransaction({ ... }) #### Ethers -```ts {5} +```ts import { providers, Wallet } from 'ethers' const provider = new providers.Web3Provider(window.ethereum) -const wallet = new Wallet('0x...', provider) +const wallet = new Wallet('0x...', provider) // [!code hl] wallet.sendTransaction({ ... }) ``` #### viem -```ts {6,9} +```ts import { createWalletClient, custom } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { mainnet } from 'viem/chains' -const account = privateKeyToAccount('0x...') +const account = privateKeyToAccount('0x...') // [!code hl] const client = createWalletClient({ - account, + account, // [!code hl] chain: mainnet, transport: custom(window.ethereum) }) @@ -353,19 +353,19 @@ client.sendTransaction({ ... }) #### Ethers -```ts {5-7} +```ts import { getDefaultProvider } from 'ethers' const provider = getDefaultProvider() -provider.getBlock(...) -provider.getTransaction(...) +provider.getBlock(...) // [!code hl] +provider.getTransaction(...) // [!code hl] ... ``` #### viem -```ts {9-11} +```ts import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' @@ -374,8 +374,8 @@ const client = createPublicClient({ transport: http() }) -client.getBlock(...) -client.getTransaction(...) +client.getBlock(...) // [!code hl] +client.getTransaction(...) // [!code hl] ... ``` @@ -389,7 +389,7 @@ client.getTransaction(...) #### Ethers -```ts {8-9} +```ts import { providers } from 'ethers' const provider = new providers.Web3Provider(window.ethereum) @@ -397,14 +397,14 @@ const provider = new providers.Web3Provider(window.ethereum) const [address] = await provider.listAccounts() const signer = provider.getSigner(address) -signer.sendTransaction(...) -signer.signMessage(...) +signer.sendTransaction(...) // [!code hl] +signer.signMessage(...) // [!code hl] ... ``` #### viem -```ts {12-13} +```ts import { createWalletClient, custom } from 'viem' import { mainnet } from 'viem/chains' @@ -416,8 +416,8 @@ const client = createWalletClient({ transport: custom(window.ethereum) }) -client.sendTransaction({ ... }) -client.signMessage({ ... }) +client.sendTransaction({ ... }) // [!code hl] +client.signMessage({ ... }) // [!code hl] ... ``` @@ -431,20 +431,20 @@ client.signMessage({ ... }) #### Ethers -```ts {6-8} +```ts import { getDefaultProvider } from 'ethers' import { wagmiContractConfig } from './abi' const provider = getDefaultProvider() -const { abi, address } = wagmiContractConfig -const contract = new Contract(address, abi, provider) -const supply = await contract.totalSupply() +const { abi, address } = wagmiContractConfig // [!code hl] +const contract = new Contract(address, abi, provider) // [!code hl] +const supply = await contract.totalSupply() // [!code hl] ``` #### viem -```ts {10-13} +```ts import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' import { wagmiContractConfig } from './abi' @@ -454,17 +454,17 @@ const client = createPublicClient({ transport: http() }) -const supply = await client.readContract({ - ...wagmiContractConfig, - functionName: 'totalSupply' -}) +const supply = await client.readContract({ // [!code hl] + ...wagmiContractConfig, // [!code hl] + functionName: 'totalSupply' // [!code hl] +}) // [!code hl] ``` ### Writing to Contracts #### Ethers -```ts {9-11} +```ts import { Contract, providers } from 'ethers' import { wagmiContractConfig } from './abi' @@ -473,22 +473,18 @@ const provider = new providers.Web3Provider(window.ethereum) const [address] = await provider.listAccounts() const signer = provider.getSigner(address) -const { abi, address } = wagmiContractConfig -const contract = new Contract(address, abi, signer) -const hash = await contract.mint() +const { abi, address } = wagmiContractConfig // [!code hl] +const contract = new Contract(address, abi, signer) // [!code hl] +const hash = await contract.mint() // [!code hl] ``` #### viem -```ts {17-22} +```ts import { createPublicClient, createWalletClient, http } from 'viem' import { mainnet } from 'viem/chains' import { wagmiContractConfig } from './abi' -const publicClient = createPublicClient({ - chain: mainnet, - transport: http() -}) const walletClient = createWalletClient({ chain: mainnet, transport: custom(window.ethereum) @@ -496,19 +492,18 @@ const walletClient = createWalletClient({ const [address] = await walletClient.getAddresses() -const { request } = await publicClient.simulateContract({ - ...wagmiContractConfig, - functionName: 'mint', - account: address, -}) -const hash = await walletClient.writeContract(request) +const hash = await walletClient.writeContract({ // [!code hl] + ...wagmiContractConfig, // [!code hl] + functionName: 'mint', // [!code hl] + account: address, // [!code hl] +}) // [!code hl] ``` ### Deploying Contracts #### Ethers -```ts {9-10} +```ts import { ContractFactory, providers } from 'ethers' import { abi, bytecode } from './abi' @@ -517,13 +512,13 @@ const provider = new providers.Web3Provider(window.ethereum) const [address] = await provider.listAccounts() const signer = provider.getSigner(address) -const contract = new ContractFactory(abi, bytecode, signer) -await contract.deploy() +const contract = new ContractFactory(abi, bytecode, signer) // [!code hl] +await contract.deploy() // [!code hl] ``` #### viem -```ts {12-16} +```ts import { createWalletClient, http } from 'viem' import { mainnet } from 'viem/chains' import { abi, bytecode } from './abi' @@ -535,38 +530,38 @@ const walletClient = createWalletClient({ const [address] = await walletClient.getAddresses() -await walletClient.deployContract({ - abi, - account: address, - bytecode, -}) +await walletClient.deployContract({ // [!code hl] + abi, // [!code hl] + account: address, // [!code hl] + bytecode, // [!code hl] +}) // [!code hl] ``` ### Contract Events #### Ethers -```ts {6-15} +```ts import { getDefaultProvider } from 'ethers' import { wagmiContractConfig } from './abi' const provider = getDefaultProvider() -const { abi, address } = wagmiContractConfig -const contract = new Contract(address, abi, provider) +const { abi, address } = wagmiContractConfig // [!code hl] +const contract = new Contract(address, abi, provider) // [!code hl] -const listener = (from, to, amount, event) => { - // ... -} -contract.on('Transfer', listener) +const listener = (from, to, amount, event) => { // [!code hl] + // ... // [!code hl] +} // [!code hl] +contract.on('Transfer', listener) // [!code hl] -// unsubscribe -contract.off('Transfer', listener) +// unsubscribe // [!code hl] +contract.off('Transfer', listener) // [!code hl] ``` #### viem -```ts {10-20} +```ts import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' import { wagmiContractConfig } from './abi' @@ -576,17 +571,17 @@ const client = createPublicClient({ transport: http() }) -const unwatch = client.watchContractEvent({ - ...wagmiContractConfig, - eventName: 'Transfer', - onLogs: logs => { - const { args: { from, to, amount }, eventName } = logs[0] - // ... - }, -}) +const unwatch = client.watchContractEvent({ // [!code hl] + ...wagmiContractConfig, // [!code hl] + eventName: 'Transfer', // [!code hl] + onLogs: logs => { // [!code hl] + const { args: { from, to, amount }, eventName } = logs[0] // [!code hl] + // ... // [!code hl] + }, // [!code hl] +}) // [!code hl] -// unsubscribe -unwatch() +// unsubscribe // [!code hl] +unwatch() // [!code hl] ``` > Note: Logs are batched between polling intervals in viem to avoid excessive callback invocations. You can disable this behavior with `batch: false` however. @@ -595,20 +590,20 @@ unwatch() #### Ethers -```ts {6-8} +```ts import { getDefaultProvider } from 'ethers' import { wagmiContractConfig } from './abi' const provider = getDefaultProvider() -const { abi, address } = wagmiContractConfig -const contract = new Contract(address, abi, provider) -const gas = await contract.estimateGas.mint() +const { abi, address } = wagmiContractConfig // [!code hl] +const contract = new Contract(address, abi, provider) // [!code hl] +const gas = await contract.estimateGas.mint() // [!code hl] ``` #### viem -```ts {10-13} +```ts import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' import { wagmiContractConfig } from './abi' @@ -618,30 +613,30 @@ const client = createPublicClient({ transport: http() }) -const gas = await client.estimateContractGas({ - ...wagmiContractConfig, - functionName: 'mint' -}) +const gas = await client.estimateContractGas({ // [!code hl] + ...wagmiContractConfig, // [!code hl] + functionName: 'mint' // [!code hl] +}) // [!code hl] ``` ### Call #### Ethers -```ts {6-8} +```ts import { getDefaultProvider } from 'ethers' import { wagmiContractConfig } from './abi' const provider = getDefaultProvider() -const { abi, address } = wagmiContractConfig -const contract = new Contract(address, abi, provider) -await contract.callStatic.mint() +const { abi, address } = wagmiContractConfig // [!code hl] +const contract = new Contract(address, abi, provider) // [!code hl] +await contract.callStatic.mint() // [!code hl] ``` #### viem -```ts {10-13} +```ts import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' import { wagmiContractConfig } from './abi' @@ -651,24 +646,24 @@ const client = createPublicClient({ transport: http() }) -await client.simulateContract({ - ...wagmiContractConfig, - functionName: 'mint' -}) +await client.simulateContract({ // [!code hl] + ...wagmiContractConfig, // [!code hl] + functionName: 'mint' // [!code hl] +}) // [!code hl] ``` ### Contract Instances #### Ethers -```ts {6-7} +```ts import { getDefaultProvider } from 'ethers' import { wagmiContractConfig } from './abi' const provider = getDefaultProvider() -const { abi, address } = wagmiContractConfig -const contract = new Contract(address, abi, provider) +const { abi, address } = wagmiContractConfig // [!code hl] +const contract = new Contract(address, abi, provider) // [!code hl] const supply = await contract.totalSupply() const listener = (from, to, amount, event) => { @@ -680,7 +675,7 @@ contract.off('Transfer', listener) #### viem -```ts {10-13} +```ts import { createPublicClient, http, getContract } from 'viem' import { mainnet } from 'viem/chains' import { wagmiContractConfig } from './abi' @@ -690,10 +685,10 @@ const client = createPublicClient({ transport: http() }) -const contract = getContract({ - ...wagmiContractConfig, - client, -}) +const contract = getContract({ // [!code hl] + ...wagmiContractConfig, // [!code hl] + client, // [!code hl] +}) // [!code hl] const supply = await contract.read.totalSupply() const unwatch = contract.watchEvent.Transfer({ @@ -801,116 +796,116 @@ viem only supports Human Readable → Object format. #### Ethers -```ts {3-10} +```ts import { utils } from 'ethers' -const interface = new Interface([ - 'constructor(string symbol, string name)', - 'function transferFrom(address from, address to, uint amount)', - 'function transferFrom(address from, address to, uint amount, bool x)', - 'function mint(uint amount) payable', - 'function balanceOf(address owner) view returns (uint)' -]) -const json = interface.format(utils.FormatTypes.json) +const interface = new Interface([ // [!code hl] + 'constructor(string symbol, string name)', // [!code hl] + 'function transferFrom(address from, address to, uint amount)', // [!code hl] + 'function transferFrom(address from, address to, uint amount, bool x)', // [!code hl] + 'function mint(uint amount) payable', // [!code hl] + 'function balanceOf(address owner) view returns (uint)' // [!code hl] +]) // [!code hl] +const json = interface.format(utils.FormatTypes.json) // [!code hl] ``` #### viem -```ts {3-10} +```ts import { parseAbi } from 'viem' -const json = parseAbi([ - 'constructor(string symbol, string name)', - 'function transferFrom(address from, address to, uint amount)', - 'function transferFrom(address from, address to, uint amount, bool x)', - 'function mint(uint amount) payable', - 'function balanceOf(address owner) view returns (uint)', - 'event Transfer(address indexed from, address indexed to, uint256 amount)' -]) +const json = parseAbi([ // [!code hl] + 'constructor(string symbol, string name)', // [!code hl] + 'function transferFrom(address from, address to, uint amount)', // [!code hl] + 'function transferFrom(address from, address to, uint amount, bool x)', // [!code hl] + 'function mint(uint amount) payable', // [!code hl] + 'function balanceOf(address owner) view returns (uint)', // [!code hl] + 'event Transfer(address indexed from, address indexed to, uint256 amount)' // [!code hl] +]) // [!code hl] ``` ### Fragment.from #### ethers -```ts {3} +```ts import { utils } from 'ethers' -const fragment = utils.Fragment.from('function balanceOf(address owner) view returns (uint)') +const fragment = utils.Fragment.from('function balanceOf(address owner) view returns (uint)') // [!code hl] ``` #### viem -```ts {3} +```ts import { parseAbiItem } from 'viem' -const abiItem = parseAbiItem('function balanceOf(address owner) view returns (uint)') +const abiItem = parseAbiItem('function balanceOf(address owner) view returns (uint)') // [!code hl] ``` ### ParamType.from #### ethers -```ts {3} +```ts import { utils } from 'ethers' -const param = utils.ParamType.from('address owner') +const param = utils.ParamType.from('address owner') // [!code hl] ``` #### viem -```ts {3} +```ts import { parseAbiParameter } from 'viem' -const param = parseAbiParameter('address owner') +const param = parseAbiParameter('address owner') // [!code hl] ``` ### Fragment Access #### Ethers -```ts {4-6} +```ts import { utils } from 'ethers' import { abi } from './abi' -const interface = new utils.Interface(abi) -interface.getFunction('transferFrom') -interface.getEvent('Transfer') +const interface = new utils.Interface(abi) // [!code hl] +interface.getFunction('transferFrom') // [!code hl] +interface.getEvent('Transfer') // [!code hl] ``` #### viem -```ts {4-5} +```ts import { getAbiItem } from 'viem' import { abi } from './abi' -getAbiItem({ abi, name: 'transferFrom' }) -getAbiItem({ abi, name: 'Transfer' }) +getAbiItem({ abi, name: 'transferFrom' }) // [!code hl] +getAbiItem({ abi, name: 'Transfer' }) // [!code hl] ``` ### Interface.encodeDeploy #### Ethers -```ts {4-5} +```ts import { utils } from 'ethers' import { abi } from './abi' -const iface = new utils.Interface(abi); -const data = iface.encodeDeploy(['SYM', 'Some Name']) +const iface = new utils.Interface(abi); // [!code hl] +const data = iface.encodeDeploy(['SYM', 'Some Name']) // [!code hl] ``` #### viem -```ts {4-8} +```ts import { encodeDeployData } from 'viem' import { abi, bytecode } from './abi' -const data = encodeDeployData({ - abi, - bytecode, - args: ['SYM', 'Some Name'] -}) +const data = encodeDeployData({ // [!code hl] + abi, // [!code hl] + bytecode, // [!code hl] + args: ['SYM', 'Some Name'] // [!code hl] +}) // [!code hl] ``` > Note: viem concatinates the contract bytecode onto the ABI encoded data. @@ -919,249 +914,249 @@ const data = encodeDeployData({ #### Ethers -```ts {4-8} +```ts import { utils } from 'ethers' import { abi } from './abi' -const iface = new utils.Interface(abi); -const data = iface.encodeErrorResult('AccountLocked', [ - '0x8ba1f109551bD432803012645Ac136ddd64DBA72', - utils.parseEther('1.0') -]); +const iface = new utils.Interface(abi); // [!code hl] +const data = iface.encodeErrorResult('AccountLocked', [ // [!code hl] + '0x8ba1f109551bD432803012645Ac136ddd64DBA72', // [!code hl] + utils.parseEther('1.0') // [!code hl] +]); // [!code hl] ``` #### viem -```ts {4-11} +```ts import { encodeErrorResult, parseEther } from 'viem' import { abi } from './abi' -const data = encodeErrorResult({ - abi: wagmiAbi, - errorName: 'AccountLocked', - args: [ - '0x8ba1f109551bD432803012645Ac136ddd64DBA72', - parseEther('1.0') - ] -}) +const data = encodeErrorResult({ // [!code hl] + abi: wagmiAbi, // [!code hl] + errorName: 'AccountLocked', // [!code hl] + args: [ // [!code hl] + '0x8ba1f109551bD432803012645Ac136ddd64DBA72', // [!code hl] + parseEther('1.0') // [!code hl] + ] // [!code hl] +}) // [!code hl] ``` ### Interface.encodeFilterTopics #### Ethers -```ts {4-8} +```ts import { utils } from 'ethers' import { abi } from './abi' -const iface = new utils.Interface(abi); -const data = iface.encodeFilterTopics('Transfer', [ - null, - '0x8ba1f109551bD432803012645Ac136ddd64DBA72' -]) +const iface = new utils.Interface(abi); // [!code hl] +const data = iface.encodeFilterTopics('Transfer', [ // [!code hl] + null, // [!code hl] + '0x8ba1f109551bD432803012645Ac136ddd64DBA72' // [!code hl] +]) // [!code hl] ``` #### viem -```ts {4-10} +```ts import { encodeEventTopics } from 'viem' import { abi } from './abi' -const data = encodeEventTopics({ - abi, - eventName: 'Transfer', - args: { - to: '0x8ba1f109551bD432803012645Ac136ddd64DBA72' - } -}) +const data = encodeEventTopics({ // [!code hl] + abi, // [!code hl] + eventName: 'Transfer', // [!code hl] + args: { // [!code hl] + to: '0x8ba1f109551bD432803012645Ac136ddd64DBA72' // [!code hl] + } // [!code hl] +}) // [!code hl] ``` ### Interface.encodeFunctionData #### Ethers -```ts {4-9} +```ts import { utils } from 'ethers' import { abi } from './abi' -const iface = new utils.Interface(abi); -const data = iface.encodeFunctionData('transferFrom', [ - '0x8ba1f109551bD432803012645Ac136ddd64DBA72', - '0xaB7C8803962c0f2F5BBBe3FA8bf41cd82AA1923C', - parseEther('1.0') -]) +const iface = new utils.Interface(abi); // [!code hl] +const data = iface.encodeFunctionData('transferFrom', [ // [!code hl] + '0x8ba1f109551bD432803012645Ac136ddd64DBA72', // [!code hl] + '0xaB7C8803962c0f2F5BBBe3FA8bf41cd82AA1923C', // [!code hl] + parseEther('1.0') // [!code hl] +]) // [!code hl] ``` #### viem -```ts {4-12} +```ts import { encodeFunctionData, parseEther } from 'viem' import { abi } from './abi' -const data = encodeFunctionData({ - abi, - functionName: 'transferFrom', - args: [ - '0x8ba1f109551bD432803012645Ac136ddd64DBA72', - '0xaB7C8803962c0f2F5BBBe3FA8bf41cd82AA1923C', - parseEther('1.0') - ] -}) +const data = encodeFunctionData({ // [!code hl] + abi, // [!code hl] + functionName: 'transferFrom', // [!code hl] + args: [ // [!code hl] + '0x8ba1f109551bD432803012645Ac136ddd64DBA72', // [!code hl] + '0xaB7C8803962c0f2F5BBBe3FA8bf41cd82AA1923C', // [!code hl] + parseEther('1.0') // [!code hl] + ] // [!code hl] +}) // [!code hl] ``` ### Interface.encodeFunctionResult #### Ethers -```ts {4-7} +```ts import { utils } from 'ethers' import { abi } from './abi' -const iface = new utils.Interface(abi); -const data = iface.encodeFunctionResult('balanceOf', [ - '0x8ba1f109551bD432803012645Ac136ddd64DBA72' -]) +const iface = new utils.Interface(abi); // [!code hl] +const data = iface.encodeFunctionResult('balanceOf', [ // [!code hl] + '0x8ba1f109551bD432803012645Ac136ddd64DBA72' // [!code hl] +]) // [!code hl] ``` #### viem -```ts {4-8} +```ts import { encodeFunctionResult, parseEther } from 'viem' import { abi } from './abi' -const data = encodeFunctionResult({ - abi, - functionName: 'balanceOf', - value: ['0x8ba1f109551bD432803012645Ac136ddd64DBA72'] -}) +const data = encodeFunctionResult({ // [!code hl] + abi, // [!code hl] + functionName: 'balanceOf', // [!code hl] + value: ['0x8ba1f109551bD432803012645Ac136ddd64DBA72'] // [!code hl] +}) // [!code hl] ``` ### Interface.decodeErrorResult #### Ethers -```ts {4-5} +```ts import { utils } from 'ethers' import { abi } from './abi' -const iface = new utils.Interface(abi); -const result = iface.decodeErrorResult("AccountLocked", '0xf7c3865a0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba720000000000000000000000000000000000000000000000000de0b6b3a7640000') +const iface = new utils.Interface(abi); // [!code hl] +const result = iface.decodeErrorResult("AccountLocked", '0xf7c3865a0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba720000000000000000000000000000000000000000000000000de0b6b3a7640000') // [!code hl] ``` #### viem -```ts {4-7} +```ts import { decodeErrorResult, parseEther } from 'viem' import { abi } from './abi' -const result = decodeErrorResult({ - abi, - data: '0xf7c3865a0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba720000000000000000000000000000000000000000000000000de0b6b3a7640000' -}) +const result = decodeErrorResult({ // [!code hl] + abi, // [!code hl] + data: '0xf7c3865a0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba720000000000000000000000000000000000000000000000000de0b6b3a7640000' // [!code hl] +}) // [!code hl] ``` ### Interface.decodeEventLog #### Ethers -```ts {4-13} +```ts import { utils } from 'ethers' import { abi } from './abi' -const iface = new utils.Interface(abi); -const result = iface.decodeEventLog( - 'Transfer', - data: '0x0000000000000000000000000000000000000000000000000de0b6b3a7640000', - topics: [ - '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', - '0x0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72', - '0x000000000000000000000000ab7c8803962c0f2f5bbbe3fa8bf41cd82aa1923c' - ] -); +const iface = new utils.Interface(abi); // [!code hl] +const result = iface.decodeEventLog( // [!code hl] + 'Transfer', // [!code hl] + data: '0x0000000000000000000000000000000000000000000000000de0b6b3a7640000', // [!code hl] + topics: [ // [!code hl] + '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', // [!code hl] + '0x0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72', // [!code hl] + '0x000000000000000000000000ab7c8803962c0f2f5bbbe3fa8bf41cd82aa1923c' // [!code hl] + ] // [!code hl] +); // [!code hl] ``` #### viem -```ts {4-12} +```ts import { decodeEventLog, parseEther } from 'viem' import { abi } from './abi' -const result = decodeEventLog({ - abi, - data: '0x0000000000000000000000000000000000000000000000000de0b6b3a7640000', - topics: [ - '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', - '0x0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72', - '0x000000000000000000000000ab7c8803962c0f2f5bbbe3fa8bf41cd82aa1923c' - ] -}) +const result = decodeEventLog({ // [!code hl] + abi, // [!code hl] + data: '0x0000000000000000000000000000000000000000000000000de0b6b3a7640000', // [!code hl] + topics: [ // [!code hl] + '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', // [!code hl] + '0x0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72', // [!code hl] + '0x000000000000000000000000ab7c8803962c0f2f5bbbe3fa8bf41cd82aa1923c' // [!code hl] + ] // [!code hl] +}) // [!code hl] ``` ### Interface.decodeFunctionData #### Ethers -```ts {4-5} +```ts import { utils } from 'ethers' import { abi } from './abi' -const iface = new utils.Interface(abi); -const result = iface.decodeFunctionData('transferFrom', '0x23b872dd0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72000000000000000000000000ab7c8803962c0f2f5bbbe3fa8bf41cd82aa1923c0000000000000000000000000000000000000000000000000de0b6b3a7640000'); +const iface = new utils.Interface(abi); // [!code hl] +const result = iface.decodeFunctionData('transferFrom', '0x23b872dd0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72000000000000000000000000ab7c8803962c0f2f5bbbe3fa8bf41cd82aa1923c0000000000000000000000000000000000000000000000000de0b6b3a7640000'); // [!code hl] ``` #### viem -```ts {4-7} +```ts import { decodeFunctionData, parseEther } from 'viem' import { abi } from './abi' -const result = decodeFunctionData({ - abi, - data: '0x23b872dd0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72000000000000000000000000ab7c8803962c0f2f5bbbe3fa8bf41cd82aa1923c0000000000000000000000000000000000000000000000000de0b6b3a7640000', -}) +const result = decodeFunctionData({ // [!code hl] + abi, // [!code hl] + data: '0x23b872dd0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72000000000000000000000000ab7c8803962c0f2f5bbbe3fa8bf41cd82aa1923c0000000000000000000000000000000000000000000000000de0b6b3a7640000', // [!code hl] +}) // [!code hl] ``` ### Interface.decodeFunctionResult #### Ethers -```ts {4-5} +```ts import { utils } from 'ethers' import { abi } from './abi' -const iface = new utils.Interface(abi); -const result = iface.decodeFunctionResult('balanceOf', '0x0000000000000000000000000000000000000000000000000de0b6b3a7640000'); +const iface = new utils.Interface(abi); // [!code hl] +const result = iface.decodeFunctionResult('balanceOf', '0x0000000000000000000000000000000000000000000000000de0b6b3a7640000'); // [!code hl] ``` #### viem -```ts {4-8} +```ts import { decodeFunctionResult, parseEther } from 'viem' import { abi } from './abi' -const result = decodeFunctionResult({ - abi, - functionName: 'balanceOf', - data: '0x0000000000000000000000000000000000000000000000000de0b6b3a7640000', -}) +const result = decodeFunctionResult({ // [!code hl] + abi, // [!code hl] + functionName: 'balanceOf', // [!code hl] + data: '0x0000000000000000000000000000000000000000000000000de0b6b3a7640000', // [!code hl] +}) // [!code hl] ``` ### Interface.getSighash #### Ethers -```ts {3-3} +```ts import { Interface, FunctionFragment } from '@ethersproject/abi'; -const hash = Interface.getSighash(FunctionFragment.from('function ownerOf(uint256)')); +const hash = Interface.getSighash(FunctionFragment.from('function ownerOf(uint256)')); // [!code hl] ``` #### viem -```ts {3-7} +```ts import { toFunctionHash } from 'viem' -const hash = toFunctionHash('function ownerOf(uint256)') +const hash = toFunctionHash('function ownerOf(uint256)') // [!code hl] ``` ## Address Utilities @@ -1170,82 +1165,82 @@ const hash = toFunctionHash('function ownerOf(uint256)') #### Ethers -```ts {3} +```ts import { utils } from 'ethers' -const address = utils.getAddress('0x8ba1f109551bd432803012645ac136ddd64dba72') +const address = utils.getAddress('0x8ba1f109551bd432803012645ac136ddd64dba72') // [!code hl] ``` #### viem -```ts {3} +```ts import { getAddress } from 'viem' -const address = getAddress('0x8ba1f109551bd432803012645ac136ddd64dba72') +const address = getAddress('0x8ba1f109551bd432803012645ac136ddd64dba72') // [!code hl] ``` ### isAddress #### Ethers -```ts {3} +```ts import { utils } from 'ethers' -const address = utils.isAddress('0x8ba1f109551bd432803012645ac136ddd64dba72') +const address = utils.isAddress('0x8ba1f109551bd432803012645ac136ddd64dba72') // [!code hl] ``` #### viem -```ts {3} +```ts import { isAddress } from 'viem' -const address = isAddress('0x8ba1f109551bd432803012645ac136ddd64dba72') +const address = isAddress('0x8ba1f109551bd432803012645ac136ddd64dba72') // [!code hl] ``` ### getContractAddress #### Ethers -```ts {3} +```ts import { utils } from 'ethers' -const address = utils.getContractAddress({ from: '0x...', nonce: 5 }); +const address = utils.getContractAddress({ from: '0x...', nonce: 5 }); // [!code hl] ``` #### viem -```ts {3} +```ts import { getContractAddress } from 'viem' -const address = getContractAddress({ from: '0x...', nonce: 5 }) +const address = getContractAddress({ from: '0x...', nonce: 5 }) // [!code hl] ``` ### getCreate2Address #### Ethers - -```ts {3-8} + +```ts import { utils } from 'ethers' -const from = '0x8ba1f109551bD432803012645Ac136ddd64DBA72'; -const salt = '0x7c5ea36004851c764c44143b1dcb59679b11c9a68e5f41497f6cf3d480715331'; -const initCode = '0x6394198df16000526103ff60206004601c335afa6040516060f3'; -const initCodeHash = utils.keccak256(initCode); +const from = '0x8ba1f109551bD432803012645Ac136ddd64DBA72'; // [!code hl] +const salt = '0x7c5ea36004851c764c44143b1dcb59679b11c9a68e5f41497f6cf3d480715331'; // [!code hl] +const initCode = '0x6394198df16000526103ff60206004601c335afa6040516060f3'; // [!code hl] +const initCodeHash = utils.keccak256(initCode); // [!code hl] -const address = utils.getCreate2Address(from, salt, initCodeHash); +const address = utils.getCreate2Address(from, salt, initCodeHash); // [!code hl] ``` #### viem -```ts {3-8} +```ts import { getContractAddress } from 'viem' -const address = getContractAddress({ - bytecode: '0x6394198df16000526103ff60206004601c335afa6040516060f3', - from: '0x8ba1f109551bD432803012645Ac136ddd64DBA72', - opcode: 'CREATE2', - salt: '0x7c5ea36004851c764c44143b1dcb59679b11c9a68e5f41497f6cf3d480715331', -}); +const address = getContractAddress({ // [!code hl] + bytecode: '0x6394198df16000526103ff60206004601c335afa6040516060f3', // [!code hl] + from: '0x8ba1f109551bD432803012645Ac136ddd64DBA72', // [!code hl] + opcode: 'CREATE2', // [!code hl] + salt: '0x7c5ea36004851c764c44143b1dcb59679b11c9a68e5f41497f6cf3d480715331', // [!code hl] +}); // [!code hl] ``` ## BigNumber Utilities @@ -1264,130 +1259,127 @@ None. We use browser native [BigInt](https://developer.mozilla.org/en-US/docs/We #### Ethers -```ts {3} +```ts import { utils } from 'ethers' -utils.isBytes(new Uint8Array([1, 69, 420])) +utils.isBytes(new Uint8Array([1, 69, 420])) // [!code hl] ``` #### viem -```ts {3} +```ts import { isBytes } from 'viem' -isBytes(new Uint8Array([1, 69, 420])) +isBytes(new Uint8Array([1, 69, 420])) // [!code hl] ``` ### isHexString #### Ethers -```ts {3} +```ts import { utils } from 'ethers' -utils.isHexString('0xdeadbeef') +utils.isHexString('0xdeadbeef') // [!code hl] ``` #### viem -```ts {3} +```ts import { isHex } from 'viem' -isHex('0xdeadbeef') +isHex('0xdeadbeef') // [!code hl] ``` ### isBytesLike #### Ethers -```ts {3} +```ts import { utils } from 'ethers' -utils.isBytesLike('0xdeadbeef') +utils.isBytesLike('0xdeadbeef') // [!code hl] ``` #### viem -```ts {3} +```ts import { isBytes, isHex } from 'viem' -isBytes('0xdeadbeef') || isHex('0xdeadbeef') +isBytes('0xdeadbeef') || isHex('0xdeadbeef') // [!code hl] ``` ### arrayify #### Ethers -```ts {3} +```ts import { utils } from 'ethers' -utils.arrayify('0xdeadbeef') +utils.arrayify('0xdeadbeef') // [!code hl] ``` #### viem -```ts {3} +```ts import { toBytes } from 'viem' -toBytes('0xdeadbeef') +toBytes('0xdeadbeef') // [!code hl] ``` ### hexlify #### Ethers -```ts {3} +```ts import { utils } from 'ethers' -utils.hexlify(new Uint8Array([1, 69, 420])) +utils.hexlify(new Uint8Array([1, 69, 420])) // [!code hl] ``` #### viem -```ts {3} +```ts import { toHex } from 'viem' -toHex(new Uint8Array([1, 69, 420])) +toHex(new Uint8Array([1, 69, 420])) // [!code hl] ``` ### hexValue #### Ethers -```ts {3} +```ts import { utils } from 'ethers' -utils.hexValue(1) +utils.hexValue(1) // [!code hl] ``` #### viem -```ts {3} +```ts import { toHex } from 'viem' -toHex(1) +toHex(1) // [!code hl] ``` ### formatBytes32String #### Ethers -```ts {3} +```ts import { utils } from 'ethers' -utils.formatBytes32String('Hello world') +utils.formatBytes32String('Hello world') // [!code hl] // 0x48656c6c6f20776f726c642e0000000000000000000000000000000000000000 ``` #### viem -```ts {3-6} +```ts import { stringToHex } from 'viem' -stringToHex( - 'Hello world', - { size: 32 } -) +stringToHex('Hello world', { size: 32 }) // [!code hl] // 0x48656c6c6f20776f726c642e0000000000000000000000000000000000000000 ``` @@ -1395,22 +1387,19 @@ stringToHex( #### Ethers -```ts {3} +```ts import { utils } from 'ethers' -utils.parseBytes32String('0x48656c6c6f20776f726c642e0000000000000000000000000000000000000000') +utils.parseBytes32String('0x48656c6c6f20776f726c642e0000000000000000000000000000000000000000') // [!code hl] // "Hello world" ``` #### viem -```ts {3-6} +```ts import { hexToString } from 'viem' -hexToString( - '0x48656c6c6f20776f726c642e0000000000000000000000000000000000000000', - { size: 32 } -) +hexToString('0x48656c6c6f20776f726c642e0000000000000000000000000000000000000000', { size: 32 }) // [!code hl] // "Hello world" ``` @@ -1418,144 +1407,144 @@ hexToString( #### Ethers -```ts {3} +```ts import { utils } from 'ethers' -utils.concat([new Uint8Array([69]), new Uint8Array([420])]) +utils.concat([new Uint8Array([69]), new Uint8Array([420])]) // [!code hl] ``` #### viem -```ts {3} +```ts import { concat, toBytes } from 'viem' -concat([new Uint8Array([69]), new Uint8Array([420])]) +concat([new Uint8Array([69]), new Uint8Array([420])]) // [!code hl] ``` ### stripZeros #### Ethers -```ts {3} +```ts import { utils } from 'ethers' -utils.stripZeros(new Uint8Array([0, 0, 0, 0, 0, 69])) +utils.stripZeros(new Uint8Array([0, 0, 0, 0, 0, 69])) // [!code hl] ``` #### viem -```ts {3} +```ts import { trim } from 'viem' -trim(new Uint8Array([0, 0, 0, 0, 0, 69])) +trim(new Uint8Array([0, 0, 0, 0, 0, 69])) // [!code hl] ``` ### zeroPad #### Ethers -```ts {3} +```ts import { utils } from 'ethers' -utils.zeroPad(new Uint8Array([69]), 32) +utils.zeroPad(new Uint8Array([69]), 32) // [!code hl] ``` #### viem -```ts {3} +```ts import { pad } from 'viem' -pad(new Uint8Array([69]), { size: 32 }) +pad(new Uint8Array([69]), { size: 32 }) // [!code hl] ``` ### hexConcat #### Ethers -```ts {3} +```ts import { utils } from 'ethers' -utils.hexConcat(['0x00000069', '0x00000420']) +utils.hexConcat(['0x00000069', '0x00000420']) // [!code hl] ``` #### viem -```ts {3} +```ts import { concat, toBytes } from 'viem' -concat(['0x00000069', '0x00000420']) +concat(['0x00000069', '0x00000420']) // [!code hl] ``` ### hexDataLength #### Ethers -```ts {3} +```ts import { utils } from 'ethers' -utils.hexDataLength('0x00000069') +utils.hexDataLength('0x00000069') // [!code hl] ``` #### viem -```ts {3} +```ts import { size } from 'viem' -size('0x00000069') +size('0x00000069') // [!code hl] ``` ### hexDataSlice #### Ethers -```ts {3} +```ts import { utils } from 'ethers' -utils.hexDataSlice('0x00000069', 4) +utils.hexDataSlice('0x00000069', 4) // [!code hl] ``` #### viem -```ts {3} +```ts import { slice } from 'viem' -slice('0x00000069', 4) +slice('0x00000069', 4) // [!code hl] ``` ### hexStripZeros #### Ethers -```ts {3} +```ts import { utils } from 'ethers' -utils.hexStripZeros('0x00000069') +utils.hexStripZeros('0x00000069') // [!code hl] ``` #### viem -```ts {3} +```ts import { trim } from 'viem' -trim('0x00000069') +trim('0x00000069') // [!code hl] ``` ### hexZeroPad #### Ethers -```ts {3} +```ts import { utils } from 'ethers' -utils.hexZeroPad('0x69', 32) +utils.hexZeroPad('0x69', 32) // [!code hl] ``` #### viem -```ts {3} +```ts import { pad } from 'viem' -pad('0x69', { size: 32 }) +pad('0x69', { size: 32 }) // [!code hl] ``` ## Display Logic & Input Utilities @@ -1564,72 +1553,72 @@ pad('0x69', { size: 32 }) #### Ethers -```ts {3} +```ts import { utils } from 'ethers' -utils.formatUnits(BigNumber.from('1000000000'), 9) +utils.formatUnits(BigNumber.from('1000000000'), 9) // [!code hl] ``` #### viem -```ts {3} +```ts import { formatUnits } from 'viem' -formatUnits(1000000000n, 9) +formatUnits(1000000000n, 9) // [!code hl] ``` ### formatEther #### Ethers -```ts {3} +```ts import { utils } from 'ethers' -utils.formatEther(BigNumber.from('1000000000000000000')) +utils.formatEther(BigNumber.from('1000000000000000000')) // [!code hl] ``` #### viem -```ts {3} +```ts import { formatEther } from 'viem' -formatEther(1000000000000000000n) +formatEther(1000000000000000000n) // [!code hl] ``` ### parseUnits #### Ethers -```ts {3} +```ts import { utils } from 'ethers' -utils.parseUnits('1.0', 18) +utils.parseUnits('1.0', 18) // [!code hl] ``` #### viem -```ts {3} +```ts import { parseUnits } from 'viem' -parseUnits('1', 18) +parseUnits('1', 18) // [!code hl] ``` ### parseEther #### Ethers -```ts {3} +```ts import { utils } from 'ethers' -utils.parseEther('1.0') +utils.parseEther('1.0') // [!code hl] ``` #### viem -```ts {3} +```ts import { parseEther } from 'viem' -parseEther('1') +parseEther('1') // [!code hl] ``` ## Encoding Utilities @@ -1638,36 +1627,36 @@ parseEther('1') #### Ethers -```ts {3} +```ts import { utils } from 'ethers' -utils.RLP.encode('0x12345678') +utils.RLP.encode('0x12345678') // [!code hl] ``` #### viem -```ts {3} +```ts import { toRlp } from 'viem' -toRlp('0x12345678') +toRlp('0x12345678') // [!code hl] ``` ### RLP.decode #### Ethers -```ts {3} +```ts import { utils } from 'ethers' -utils.RLP.decode('0x8412345678') +utils.RLP.decode('0x8412345678') // [!code hl] ``` #### viem -```ts {3} +```ts import { fromRlp } from 'viem' -fromRlp('0x8412345678') +fromRlp('0x8412345678') // [!code hl] ``` ## Hashing Utilities @@ -1676,42 +1665,42 @@ fromRlp('0x8412345678') #### Ethers -```ts {3,5-6} +```ts import { utils } from 'ethers' -utils.id('function ownerOf(uint256 tokenId)') +utils.id('function ownerOf(uint256 tokenId)') // [!code hl] // hash utf-8 data -utils.id('hello world') +utils.id('hello world') // [!code hl] ``` #### viem -```ts {3,5-6} -import { getFunctionSelector, keccak256, toHex } from 'viem' +```ts +import { toFunctionSelector, keccak256, toHex } from 'viem' -getFunctionSelector('function ownerOf(uint256 tokenId)') +toFunctionSelector('function ownerOf(uint256 tokenId)') // [!code hl] // hash utf-8 data -keccak256(toHex('hello world')) +keccak256(toHex('hello world')) // [!code hl] ``` ### keccak256 #### Ethers -```ts {3} +```ts import { utils } from 'ethers' -utils.keccak256(utils.toUtf8Bytes('hello world')) +utils.keccak256(utils.toUtf8Bytes('hello world')) // [!code hl] ``` #### viem -```ts {3} +```ts import { keccak256, toBytes } from 'viem' -keccak256(toBytes('hello world')) +keccak256(toBytes('hello world')) // [!code hl] ``` ### encodeBase64/decodeBase64 @@ -1730,38 +1719,38 @@ You can use libraries such as [`base58-js`](https://www.npmjs.com/package/base58 #### Ethers -```ts {3} +```ts import { utils } from 'ethers' -utils.namehash('awkweb.eth') +utils.namehash('awkweb.eth') // [!code hl] ``` #### viem -```ts {3} +```ts import { namehash } from 'viem' -namehash('awkweb.eth') +namehash('awkweb.eth') // [!code hl] ``` ### solidityPack & solidityKeccak256 #### Ethers -```ts {3,4} +```ts import { utils } from 'ethers' -utils.solidityPack(['int16', 'uint48'], [-1, 12]) -utils.solidityKeccak256(['int16', 'uint48'], [-1, 12]) +utils.solidityPack(['int16', 'uint48'], [-1, 12]) // [!code hl] +utils.solidityKeccak256(['int16', 'uint48'], [-1, 12]) // [!code hl] ``` #### viem -```ts {3,4} +```ts import { encodePacked, keccak256 } from 'viem' -encodePacked(['int16', 'uint48'], [-1, 12]) -keccak256(encodePacked(['int16', 'uint48'], [-1, 12])) +encodePacked(['int16', 'uint48'], [-1, 12]) // [!code hl] +keccak256(encodePacked(['int16', 'uint48'], [-1, 12])) // [!code hl] ``` ## String Utilities @@ -1770,36 +1759,36 @@ keccak256(encodePacked(['int16', 'uint48'], [-1, 12])) #### Ethers -```ts {3} +```ts import { utils } from 'ethers' -utils.toUtf8Bytes('Hello World') +utils.toUtf8Bytes('Hello World') // [!code hl] ``` #### viem -```ts {3} +```ts import { stringToBytes } from 'viem' -stringToBytes('Hello World') +stringToBytes('Hello World') // [!code hl] ``` ### toUtf8String #### Ethers -```ts {3} +```ts import { utils } from 'ethers' -utils.toUtf8String(new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])) +utils.toUtf8String(new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])) // [!code hl] ``` #### viem -```ts {3} +```ts import { bytesToString } from 'viem' -bytesToString(new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])) +bytesToString(new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])) // [!code hl] ``` ## Transaction Utilities diff --git a/site/pages/docs/migration-guide.mdx b/site/pages/docs/migration-guide.mdx index 5dbffa36e1..3d36fffa32 100644 --- a/site/pages/docs/migration-guide.mdx +++ b/site/pages/docs/migration-guide.mdx @@ -229,11 +229,11 @@ const log: Log = { For example, the following Log will throw an error as there is a mismatch in non-`indexed` arguments & `data` length. -```ts {2-4} +```ts decodeEventLog({ - abi: parseAbi(['event Transfer(address indexed, address, uint256)']), - // `data` should be 64 bytes, but is only 32 bytes. - data: '0x0000000000000000000000000000000000000000000000000000000000000001' + abi: parseAbi(['event Transfer(address indexed, address, uint256)']), // [!code focus] + // `data` should be 64 bytes, but is only 32 bytes. // [!code focus] + data: '0x0000000000000000000000000000000000000000000000000000000000000001' // [!code focus] topics: [ '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', '0x000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266', diff --git a/site/pages/docs/typescript.mdx b/site/pages/docs/typescript.mdx index ad5d015486..874c84dea4 100644 --- a/site/pages/docs/typescript.mdx +++ b/site/pages/docs/typescript.mdx @@ -36,8 +36,8 @@ const abi = [{ // [!code focus] stateMutability: 'view', // [!code focus] inputs: [{ type: 'address' }], // [!code focus] outputs: [{ type: 'uint256' }], // [!code focus] -// @log: ↑ const assertion }] as const // [!code focus] +// @log: ↑ const assertion const result = client.readContract({ address: '0x27a69ffba1e939ddcfecc8c7e0f967b872bac65c', @@ -54,8 +54,8 @@ const client = createPublicClient({ transport: http() }) // ---cut--- -const result = client.readContract({ // @log: ↓ defined inline +const result = client.readContract({ address: '0x27a69ffba1e939ddcfecc8c7e0f967b872bac65c', abi: [{ // [!code focus] type: 'function', // [!code focus] diff --git a/site/pages/docs/utilities/fromBytes.md b/site/pages/docs/utilities/fromBytes.md index 5c53743433..b97a0d1fec 100644 --- a/site/pages/docs/utilities/fromBytes.md +++ b/site/pages/docs/utilities/fromBytes.md @@ -64,21 +64,21 @@ The byte array to decode. The output type or options. -```ts {3} +```ts fromBytes( new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]), - 'string' + 'string' // [!code focus] ) // 'Hello world' ``` -```ts {3-6} +```ts fromBytes( new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), - { - size: 32, - to: 'string' - } + { // [!code focus] + size: 32, // [!code focus] + to: 'string' // [!code focus] + } // [!code focus] ) // 'Hello world' ``` diff --git a/site/pages/docs/utilities/fromHex.md b/site/pages/docs/utilities/fromHex.md index 367aeb351d..f0e7d7a91a 100644 --- a/site/pages/docs/utilities/fromHex.md +++ b/site/pages/docs/utilities/fromHex.md @@ -61,21 +61,21 @@ The hex value to decode. The output type or options. -```ts {3} +```ts fromHex( '0x48656c6c6f20776f726c642e', - 'string' + 'string' // [!code focus] ) // 'Hello world' ``` -```ts {3-6} +```ts fromHex( '0x48656c6c6f20776f726c642e0000000000000000000000000000000000000000', - { - size: 32, - to: 'string' - } + { // [!code focus] + size: 32, // [!code focus] + to: 'string' // [!code focus] + } // [!code focus] ) // 'Hello world' ``` diff --git a/site/pages/docs/utilities/toBytes.md b/site/pages/docs/utilities/toBytes.md index b5abd7cb23..ec089c1989 100644 --- a/site/pages/docs/utilities/toBytes.md +++ b/site/pages/docs/utilities/toBytes.md @@ -51,19 +51,19 @@ The byte array represented as a `Uint8Array`. The value to encode as bytes. -```ts {2} +```ts toBytes( - 'Hello world' + 'Hello world' // [!code focus] ) // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]) ``` ### options -```ts {3} +```ts toBytes( 'Hello world', - { size: 32 } + { size: 32 } // [!code focus] ) // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) ``` diff --git a/site/pages/docs/utilities/toEventHash.md b/site/pages/docs/utilities/toEventHash.md index 6c80ec61fd..a93becdcf8 100644 --- a/site/pages/docs/utilities/toEventHash.md +++ b/site/pages/docs/utilities/toEventHash.md @@ -17,8 +17,8 @@ import { toEventHash } from 'viem' ```ts twoslash import { toEventHash } from 'viem' -// @log: Output: 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef const hash_1 = toEventHash('event Transfer(address,address,uint256)') +// @log: Output: 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef const hash_2 = toEventHash({ name: 'Transfer', @@ -28,8 +28,8 @@ const hash_2 = toEventHash({ { name: 'to', type: 'address', indexed: true }, { name: 'amount', type: 'uint256', indexed: false }, ], -// @log: Output: 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef }) +// @log: Output: 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef ``` ## Returns diff --git a/site/pages/docs/utilities/toEventSelector.md b/site/pages/docs/utilities/toEventSelector.md index caca52ae8f..5947ac959d 100644 --- a/site/pages/docs/utilities/toEventSelector.md +++ b/site/pages/docs/utilities/toEventSelector.md @@ -17,11 +17,11 @@ import { toEventSelector } from 'viem' ```ts twoslash import { toEventSelector } from 'viem' -// @log: Output: 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef const selector_1 = toEventSelector('Transfer(address,address,uint256)') - // @log: Output: 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef + const selector_2 = toEventSelector('Transfer(address indexed from, address indexed to, uint256 amount)') +// @log: Output: 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef // or from an `AbiEvent` on your contract ABI const selector_3 = toEventSelector({ @@ -32,8 +32,8 @@ const selector_3 = toEventSelector({ { name: 'to', type: 'address', indexed: true }, { name: 'amount', type: 'uint256', indexed: false }, ], -// @log: Output: 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef }) +// @log: Output: 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef ``` ## Returns diff --git a/site/pages/docs/utilities/toEventSignature.md b/site/pages/docs/utilities/toEventSignature.md index 079695c9c6..581b0c1535 100644 --- a/site/pages/docs/utilities/toEventSignature.md +++ b/site/pages/docs/utilities/toEventSignature.md @@ -22,8 +22,8 @@ import { toEventSignature } from 'viem' import { toEventSignature } from 'viem' // from event definition -// @log: Output: Transfer(address,address,uint256) const signature_1 = toEventSignature('event Transfer(address indexed from, address indexed to, uint256 amount)') +// @log: Output: Transfer(address,address,uint256) // from an `AbiEvent` on your contract ABI const signature_2 = toEventSignature({ @@ -34,8 +34,8 @@ const signature_2 = toEventSignature({ { name: 'address', type: 'address', indexed: true }, { name: 'uint256', type: 'uint256', indexed: false }, ], -// @log: Output: Transfer(address,address,uint256) }) +// @log: Output: Transfer(address,address,uint256) ``` ## Returns diff --git a/site/pages/docs/utilities/toFunctionHash.md b/site/pages/docs/utilities/toFunctionHash.md index 02fd7b28c3..b7587d8910 100644 --- a/site/pages/docs/utilities/toFunctionHash.md +++ b/site/pages/docs/utilities/toFunctionHash.md @@ -17,8 +17,8 @@ import { toFunctionHash } from 'viem' ```ts twoslash import { toFunctionHash } from 'viem' -// @log: Output: 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef const hash_1 = toFunctionHash('function ownerOf(uint256)') +// @log: Output: 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef // or from an `AbiEvent` on your contract ABI const hash_2 = toFunctionHash({ @@ -27,8 +27,8 @@ const hash_2 = toFunctionHash({ inputs: [{ name: 'tokenId', type: 'uint256' }], outputs: [], stateMutability: 'view', -// @log: Output: 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef }) +// @log: Output: 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef ``` ## Returns diff --git a/site/pages/docs/utilities/toFunctionSelector.md b/site/pages/docs/utilities/toFunctionSelector.md index 76b5c19669..77a26c7766 100644 --- a/site/pages/docs/utilities/toFunctionSelector.md +++ b/site/pages/docs/utilities/toFunctionSelector.md @@ -17,11 +17,11 @@ import { toFunctionSelector } from 'viem' ```ts twoslash import { toFunctionSelector } from 'viem' -// @log: Output: 0x6352211e const selector_1 = toFunctionSelector('function ownerOf(uint256 tokenId)') - // @log: Output: 0x6352211e + const selector_2 = toFunctionSelector('ownerOf(uint256)') +// @log: Output: 0x6352211e // or from an `AbiFunction` on your contract ABI const selector_3 = toFunctionSelector({ @@ -30,8 +30,8 @@ const selector_3 = toFunctionSelector({ inputs: [{ name: 'tokenId', type: 'uint256' }], outputs: [], stateMutability: 'view', -// @log: Output: 0x6352211e }) +// @log: Output: 0x6352211e ``` ## Returns diff --git a/site/pages/docs/utilities/toFunctionSignature.md b/site/pages/docs/utilities/toFunctionSignature.md index a97966bff6..ed3d63be43 100644 --- a/site/pages/docs/utilities/toFunctionSignature.md +++ b/site/pages/docs/utilities/toFunctionSignature.md @@ -22,8 +22,8 @@ import { toFunctionSignature } from 'viem' import { toFunctionSignature } from 'viem' // from function definition -// @log: Output: ownerOf(uint256) const signature_1 = toFunctionSignature('function ownerOf(uint256 tokenId)') +// @log: Output: ownerOf(uint256) // from an `AbiFunction` on your contract ABI const signature_2 = toFunctionSignature({ @@ -32,8 +32,8 @@ const signature_2 = toFunctionSignature({ inputs: [{ name: 'tokenId', type: 'uint256' }], outputs: [], stateMutability: 'view', -// @log: Output: ownerOf(uint256) }) +// @log: Output: ownerOf(uint256) ``` ## Returns diff --git a/site/pages/docs/utilities/toHex.md b/site/pages/docs/utilities/toHex.md index 421989888e..c601fcdf00 100644 --- a/site/pages/docs/utilities/toHex.md +++ b/site/pages/docs/utilities/toHex.md @@ -53,19 +53,19 @@ The hex value. The value to hex encode. -```ts {2} +```ts toHex( - 'Hello world' + 'Hello world' // [!code focus] ) // '0x48656c6c6f20776f726c642e' ``` ### options -```ts {3} +```ts toHex( 'Hello world', - { size: 32 } + { size: 32 } // [!code focus] ) // '0x48656c6c6f20776f726c642e0000000000000000000000000000000000000000' ``` diff --git a/site/pages/op-stack.mdx b/site/pages/op-stack.mdx index bbdd6bfd7f..31e96dbd66 100644 --- a/site/pages/op-stack.mdx +++ b/site/pages/op-stack.mdx @@ -14,14 +14,14 @@ The OP Stack is a set of modular open-source software that enable developers to Firstly, set up your [Client](/docs/clients/intro) with a desired [Transport](/docs/clients/intro) & [OP Stack Chain](/op-stack/chains). -```ts {4-7} +```ts import { createPublicClient, http } from 'viem' import { base } from 'viem/chains' -const client = createPublicClient({ - chain: base, - transport: http(), -}) +const client = createPublicClient({ // [!code focus] + chain: base, // [!code focus] + transport: http(), // [!code focus] +}) // [!code focus] ``` :::info diff --git a/site/snippets/publicClient.ts b/site/snippets/publicClient.ts index 980635bbff..45b86cb8e8 100644 --- a/site/snippets/publicClient.ts +++ b/site/snippets/publicClient.ts @@ -3,7 +3,7 @@ import { http, createPublicClient } from 'viem' import { mainnet } from 'viem/chains' // [!endregion imports] -export const client = createPublicClient({ +export const publicClient = createPublicClient({ chain: mainnet, transport: http(), }) diff --git a/site/snippets/walletClient.ts b/site/snippets/walletClient.ts new file mode 100644 index 0000000000..f379a311f4 --- /dev/null +++ b/site/snippets/walletClient.ts @@ -0,0 +1,12 @@ +import 'viem/window' + +// ---cut--- +// [!region imports] +import { createWalletClient, custom } from 'viem' +import { mainnet } from 'viem/chains' +// [!endregion imports] + +export const walletClient = createWalletClient({ + chain: mainnet, + transport: custom(window.ethereum!), +})