patternjavascriptTip
viem walletClient: connecting a browser wallet for write operations
Viewed 0 times
viem 2.x
viemwalletClientcreateWalletClientwriteContractrequestAddressesbrowser wallet
Error Messages
Problem
viem's publicClient is read-only. To send transactions or sign messages from a browser wallet, you need a walletClient backed by the injected provider.
Solution
Use createWalletClient with the custom transport pointing at window.ethereum. Request accounts first, then use writeContract or sendTransaction.
import { createWalletClient, custom } from 'viem';
const client = createWalletClient({ chain: mainnet, transport: custom(window.ethereum) });
const [address] = await client.requestAddresses();Why
viem enforces a strict separation between read clients and write clients. The walletClient wraps the EIP-1193 provider and handles account management, signing, and transaction broadcasting.
Gotchas
- Always call requestAddresses() (which triggers wallet connection) before writeContract — otherwise the account field will be undefined
- Use getAddresses() instead of requestAddresses() if the user is already connected to avoid prompting again
- On account change events, recreate the walletClient or re-fetch addresses to keep the active account in sync
Code Snippets
Create a viem walletClient and call a contract write function
import { createWalletClient, createPublicClient, custom, http, parseAbi } from 'viem';
import { mainnet } from 'viem/chains';
const publicClient = createPublicClient({ chain: mainnet, transport: http() });
const walletClient = createWalletClient({ chain: mainnet, transport: custom(window.ethereum) });
async function mintNFT(contractAddress) {
const [account] = await walletClient.requestAddresses();
const abi = parseAbi(['function mint(address to) external returns (uint256)']);
const { request } = await publicClient.simulateContract({
address: contractAddress,
abi,
functionName: 'mint',
args: [account],
account,
});
const txHash = await walletClient.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash: txHash });
return receipt;
}Context
Sending write transactions from a browser dApp using viem without wagmi
Revisions (0)
No revisions yet.