typescriptethereumintegrationintermediate
Interact with Smart Contract using viem
Read from and write to a smart contract using viem's typed client.
All snippets
Code
typescript
import { createPublicClient, http, parseAbi } from "viem";
import { mainnet } from "viem/chains";
const client = createPublicClient({
chain: mainnet,
transport: http(),
});
const abi = parseAbi([
"function balanceOf(address) view returns (uint256)",
"function totalSupply() view returns (uint256)",
]);
const contractAddress = "0x...";
// Read: get token balance for an address
const balance = await client.readContract({
address: contractAddress,
abi,
functionName: "balanceOf",
args: ["0x742d35Cc6634C0532925a3b844Bc454e4438f44e"],
});
console.log("Balance:", balance);Explanation
viem provides a clean, typed interface for contract interactions.
Key differences from ethers.js:
parseAbi()accepts human-readable ABI strings — no JSON needed.readContractis for view functions (no gas cost).- Full TypeScript inference on function arguments and return types.
For write operations, use simulateContract + walletClient.writeContract.
viemcontractreadtypescript